Sometimes, we may run into the “Can’t set headers after they are sent to the client” when we run our Express app.
In this article, we’ll look at how to fix the “Can’t set headers after they are sent to the client” in our Express app.
Fix the “Can’t set headers after they are sent to the client” Error in an Express App
To fix the “Can’t set headers after they are sent to the client” in our Express app, we should make sure that we only send a response once in our Express middleware chain.
For instance, we shouldn’t have code like:
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => {
res.send('hello world')
res.send('hello world')
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
which calls res.send
twice.
We should make sure that we only send a response once in our middleware chain.
This also means we shouldn’t have code like:
const express = require('express')
const app = express()
const port = 3000
app.use((req, res, next) => {
res.send('hello world')
next()
})
app.get('/', (req, res) => {
res.send('hello world')
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
where we call res.send
in our middleware that’s run before the /
route handler.
And res.send
is also called in the /
route handler itself.
This will also cause the error.
Instead, we should write:
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => {
res.send('hello world')
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
or:
const express = require('express')
const app = express()
const port = 3000
app.use((req, res, next) => {
console.log('hello world')
next()
})
app.get('/', (req, res) => {
res.send('hello world')
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
where we only return a response once in the whole middleware chain.
Conclusion
To fix the “Can’t set headers after they are sent to the client” in our Express app, we should make sure that we only send a response once in our Express middleware chain.