'Cannot set headers after they are sent to the client sentry
I get an error from sentry.io on this code, i's tell me that I can't set headers after they are sent to the client. It's a next js app
export async function getServerSideProps(ctx) {
const { res } = ctx
res.setHeader('Content-Type', 'text/plain')
res.write('User-agent: *\n')
res.write('Disallow: \n')
res.write('Sitemap: https://kalla.com/sitemap.xml\n')
res.end()
return {}
}
const Robots = () => null
export default Robots
Solution 1:[1]
Response header is only sent once with a request, and if you try to set it and send it again you will get an error. writeHead() can be merged with setHeader(), but the writeHead() has precedence over the latter. WriteHead() acepts these args :writeHead(statusCode, statusMessage, headers), however accepts setHeader(key, value).
export async function getServerSideProps(ctx) {
const { res } = ctx
res.setHeader('Content-Type', 'text/plain')
res.setHeader('User-agent','*\n')
res.setHeader('Disallow', '\n')
res.setHeader('Sitemap', 'https://kalla.com/sitemap.xml\n')
res.end()
return {}
}
const Robots = () => null
export default Robots
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Hamza Sehouli |
