I am trying to do Google Login using a Nextjs frontend and an Expressjs backend. I followed this tutorial.
I use the URL http://localhost:5200/auth/google
and expect the same response I get using Postman: <title>Sign in - Google Accounts</title>
(plus 1885 lines of other stuff)
I get this error when trying to connect via Nextjs: Access to XMLHttpRequest at 'https://accounts.google.com/o/oauth2/v2/auth?response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fauth%2Fgoogle%2Fcallback&scope=email%20profile&client_id=493322088126-0kd18q0if7ccc333b3jahdh5gmgojsbgig.apps.googleusercontent.com' (redirected from 'http://localhost:5200/auth/google') from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
My frontend's query: const response = await axios.get("http://localhost:5200/auth/google");
My backend's middlewares:
middlewares: [
allowAll,
cors({ origin: "*", methods: "GET, POST, PATCH, DELETE, PUT", allowedHeaders: "Content-Type, Authorization" }),
accessControlAllowOriginDev,
bodyParser.json(),
bodyParser.urlencoded({ extended: true }),
cookieParser(),
passport.initialize(),
(req: any, res: any, next: any) => {
console.log(req.originalUrl); //confirms the url is correct
next();
},
]
The route that uniquely fails: this.router.get("/google", passport.authenticate("google", { scope: ["email", "profile"] })); // the route is correct
I have tried:
- Changing the order of the middleware.
cors()
was last in the stack, now its first. - Adding
passport.initialize()
&passport.session()
. Prior to this, both were missing. Pretty sure it's unrelated, however. - Sending a request to my auth controller's health check route from Nextjs and Postman. Both confirm the controller is active and running. Neither is blocked by CORS.
- This solution which involves modifying
local.settings.json
{
"Host": {
"CORS": "*"
}
}
In summary: Postman receives the correct response from the endpoint, but Nextjs uniquely does not. Nextjs can access the healthCheck endpoint just like Postman; hence the problem is uniquely the combination of Nextjs and Passport. I have no idea what's wrong.
edit: Can someone tell me? If I had CORS configured correctly, every request would come back with "Allow-access-control-origin: *" on the headers, right? My Postman response headers do say X-Powered-By: Express Access-Control-Allow-Origin: *
edit2: I'm hot on the trail of a solution. This looks similar