CORS issues when connecting Next.js frontend on Vercel to Express.js backend on AWS EC2

I’m having trouble connecting my Next.js frontend deployed on Vercel to my Express.js backend running on AWS EC2. I keep getting CORS errors even though I think I configured everything correctly.

Here’s my backend CORS setup:

const permittedDomains = [
  "https://myapp.com",
  "https://www.myapp.com"
];

const corsConfig = {
  origin: (requestOrigin, cb) => {
    if (!requestOrigin) {
      console.log("Request without origin - permitted");
      return cb(null, true);
    }

    if (permittedDomains.indexOf(requestOrigin) !== -1) {
      console.log(`CORS accepted for: ${requestOrigin}`);
      cb(null, true);
    } else {
      console.error(`CORS rejected: ${requestOrigin}`);
      cb(new Error(`Access denied for origin: ${requestOrigin}`));
    }
  },
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With']
};

server.use(cors(corsConfig));

And here’s my frontend API configuration:

export const apiSlice = createApi({
  baseQuery: customFetch,
  tagTypes: ["User", "Data"],
  endpoints: (builder) => ({
    fetchCurrentUser: builder.query({
      queryFn: async (args, api, options, baseQuery) => {
        try {
          const userData = await getUser();
          const authSession = await getSession();
          
          if (!authSession) {
            return {
              error: {
                status: 401,
                data: 'Authentication required'
              }
            };
          }
          
          const response = await baseQuery(`user/${authSession.id}`);
          return response.error ? { error: response.error } : { data: response.data };
        } catch (err) {
          return {
            error: {
              status: 'FETCH_ERROR',
              data: err.message || 'Failed to get user'
            }
          };
        }
      }
    })
  })
});

I set up a subdomain api.myapp.com pointing to my EC2 instance but the CORS errors persist. My EC2 has Nginx configured. Do I need additional Nginx configuration or proxy settings to make this work? What am I missing to properly connect my Vercel frontend with my EC2 backend?

Your CORS config looks fine - the problem’s probably your Nginx proxy. When requests go through Nginx to Express, it can mess with or strip the origin header. Throw these directives into your Nginx location block:

proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;

Also make sure Express trusts the proxy by adding app.set('trust proxy', true) before your CORS middleware. I had the same setup and this fixed the origin header issue. Check your browser’s network tab to see what origin is actually being sent.

wait, you’re callin api.myapp.com from your frontend? your CORS config only allows myapp.com and www.myapp.com - it doesn’t include the api subdomain. what’s your customFetch baseQuery look like? check what origin it’s actually sendin.

double-check your vercel deploy url - vercel makes those auto-generated urls like myapp-xyz123.vercel.app for previews, and your actual domain might not be what you expect. also, nginx could be stripping headers. try adding proxy_pass_header directives to your nginx config.