As asked
Your Next.js API is getting CORS errors from a browser making a POST request with a JSON body. Walk me through what CORS is, what a preflight request does, and how you fix this correctly on the server.
Sample answer outline
CORS is the browser's enforcement of the same-origin policy for cross-origin requests. A preflight OPTIONS request is sent by the browser before a cross-origin request that meets certain conditions: non-simple method like PUT or DELETE, or custom headers like Content-Type: application/json. The server must respond to the OPTIONS request with the correct Access-Control-Allow-Origin, Access-Control-Allow-Methods, and Access-Control-Allow-Headers headers before the browser will send the actual request. The fix is to handle OPTIONS in your route handler and set those headers, or use a CORS middleware. A strong answer notes that CORS is enforced by the browser, not the server, and that server-to-server calls are not affected.
Expect these follow-ups
- Why is Access-Control-Allow-Origin: * insufficient for requests that include cookies or Authorization headers?