Search code examples
node.jsreactjsexpresscorsgoogle-oauth

CORS Issues with Google Authentication


I have been implementing Google Auth on my MERN stack web application. However, I encountered an error: 'Redirected from 'http://localhost:5000/api/v1/auth/google' from origin 'http://localhost:5173' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.' even tho i've already set cors on my server.

const cors = require("cors");
app.use(cors());

enter image description here


Solution

  • You'll need to whitelist certain origins, otherwise CORS will deny all traffic that doesn't match the domain:

    See https://github.com/expressjs/cors#configuring-cors-asynchronously

    const whitelist = config.getWhiteList(); // ["http://localhost:5173"]
    
    const corsConfig = cors({
      origin: (origin, callback) => {
        if (!origin || whitelist.includes(origin)) {
          callback(null, true);
        } else {
          callback(new Error('Not allowed by CORS'));
        }
      },
    });
    
    app.use(corsConfig);