I'm using Next.js 14 with Express and attempting to implement Google OAuth using passport-google-oauth2. However, I'm encountering an error on my frontend. When my server sends a redirection link to the frontend, I encounter a CORS error. My backend is functioning correctly because when I copy that link and paste it into a new tab, everything works fine.
Here is my code where I'm making a GET request to my server:
const handleGoogleLogin = () => {
startTransition(async () => {
try {
const response = await axiosInstance.get("/api/auth/google", {
withCredentials: true,
});
console.log(response);
} catch (error) {
console.log(error);
}
});
};
And here is the Passport.js implementation and CORS config:
app.use(passport.initialize());
passport.serializeUser(function (user, done) {
done(null, user);
});
passport.deserializeUser(function (user, done) {
done(null, user);
});
passport.use(
new GoogleStrategy(
{
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: "http://localhost:3001/api/auth/callback/google",
passReqToCallback: true,
},
(request, accessToken, refreshToken, profile, done) => {
return done(null, profile);
}
)
);
app.get(
"/api/auth/google",
passport.authenticate("google", {
scope: ["email", "profile"],
session: false,
})
);
app.get(
"/api/auth/callback/google",
passport.authenticate("google", {
failureRedirect: "/login",
session: false,
}),
function (req, res) {
res.json(req.user);
}
);
// CORS
app.use(
cors({
origin: ["http://localhost:3000"],
credentials: true,
})
);
The error I am encountering is:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://accounts.google.com/o/oauth2/v2/auth?response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A3001%2Fapi%2Fauth%2Fcallback%2Fgoogle&scope=email%20profile&client_id=CLIENT_ID. (Reason: CORS request did not succeed). Status code: (null).
Could anyone help me fix this error?