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?