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?