CORS issue when linking Next.js frontend on Vercel with Node.js backend on AWS EC2

I’m facing CORS issues while attempting to connect my Next.js frontend hosted on Vercel to my Node.js Express backend located on AWS EC2. I’ve created a subdomain specifically for my API but the connection keeps failing.

Here’s the CORS setup I’m currently using:

const allowedOrig = [
  "https://mywebsite.com",
  "https://www.mywebsite.com",
];

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

    if (allowedOrig.includes(requestOrigin)) {
      console.log(`CORS allowed for: ${requestOrigin}`);
      callback(null, true);
    } else {
      console.log(`CORS denied for: ${requestOrigin}`);
      callback(new Error(`Not allowed for origin: ${requestOrigin}`));
    }
  },
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: [
    'Content-Type',
    'Authorization',
    'X-Requested-With',
    'Accept',
    'Origin'
  ]
};

app.use(cors(corsSettings));

And this is how I set up RTK Query:

export const apiSlice = createApi({
  baseQuery: customFetchBase,
  reducerPath: "apiSlice",
  tagTypes: ["Users", "Data"],
  endpoints: (builder) => ({
    fetchUser: builder.query({
      queryFn: async (_, api, options, baseQuery) => {
        try {
          const user = await getCurrentUser();
          const session = await fetchSession();
          
          if (!session) {
            return {
              error: {
                status: 401,
                data: 'Authentication required'
              }
            };
          }
          
          const response = await baseQuery(`user/${session.userId}`);
          return response.error ? { error: response.error } : { data: response.data };
        } catch (error) {
          return {
            error: {
              status: 'FETCH_ERROR',
              data: error.message || 'Could not retrieve user information'
            }
          };
        }
      }
    })
  })
});

I have nginx running on my EC2 server along with a subdomain for the API. Is it necessary to adjust my nginx settings or security group permissions on EC2 to resolve this CORS issue?

you should def add your vercel URL in the allowedOrig array like your-app.vercel.app. also, double-check your EC2 security group to make sure it allows HTTPS. this could fix your CORS issues!

any error messages showing up in your browser console or network tab? what’s your customFetchBase setup look like? sometimes it’s the base query config that’s the problem, not just CORS.

This is probably happening because Vercel’s deployment URLs aren’t in your allowed origins. Vercel creates multiple URLs for each deployment - preview URLs plus your production domain. I ran into this same issue with a similar setup. Just add both your production Vercel URL and any preview deployment URLs to your allowedOrig array. That should fix the CORS errors. Also double-check that nginx is forwarding the Origin header to your Express app. If it’s not forwarding headers properly, your CORS middleware can’t figure out where the request is coming from. Make sure your nginx proxy_pass config has proxy_set_header directives for Origin and other headers you need.