Cannot set Headers for 'OPTIONS' API requests on dev server
See original GitHub issueBug report
Describe the bug
I am using micro-cors to allow cors on my next.js project. It works fine on my production environment. I am trying to setup a complete development environment on my laptop. So I started my Next.js application at localhost:8080, and my React app that consumes the API on localhost:3000. The OPTIONS request produces this error:
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:470:11)
at C:\Users\romai\IdeaProjects\Interlude\node_modules\micro-cors\lib\index.js:31:11
at corsHandler (C:\Users\romai\IdeaProjects\Interlude\.next\server\static\development\pages\api\graphql.js:1898:79)
at Object.apiResolver (C:\Users\romai\IdeaProjects\Interlude\node_modules\next\dist\next-server\server\api-utils.js:47:15)
at DevServer.handleApiRequest (C:\Users\romai\IdeaProjects\Interlude\node_modules\next\dist\next-server\server\next-server.js:475:27)
I added so logs to my application to see what is happening:
async function corsHandler(req: NextApiRequest, res: NextApiResponse) {
console.log(res.headersSent)
console.log(res.getHeaders())
cors((req, res) => req.method === 'OPTIONS' ? res.end() : handler(req, res))(req, res)
}
export default corsHandler
It appears that some headers are already send in the response, but only for OPTIONS request in development environments:
'access-control-allow-origin': 'http://localhost:3000',
'access-control-allow-methods': 'OPTIONS, GET',
'access-control-allow-headers': 'content-type'
I don’t know where those headers comes from, however it is send before my handler is executed (and before micro-cors is called).
Expected behavior
No headers send before my handler gets called, or some workaround.
Additional context
I found that issue that might be related: https://github.com/zeit/next.js/issues/11752 However, I tried to setup the experimental feature described in that issue but my handler is no longer called, and the headers are not impacted either.
Issue Analytics
- State:
- Created 3 years ago
- Reactions:3
- Comments:5 (3 by maintainers)
Top GitHub Comments
I tried it, and it works indeed! Thanks
This issue has been automatically locked due to no recent activity. If you are running into a similar issue, please create a new issue with the steps to reproduce. Thank you.