res.headersSent is a boolean that tells you whether the response headers have already
been sent to the client.
Syntax
res.headersSent
Example
const express = require("express");
const app = express();
const PORT = 4800;
app.get("/", (req, res) => {
console.log("before send:", res.headersSent); // false
res.send("OK");
console.log("after send:", res.headersSent); // true
});
app.listen(PORT, () => console.log(`Listening on ${PORT}`));
Use cases
- Preventing "headers already sent" errors by checking before calling
res.set()again. - Writing custom error-handling middleware that avoids double responses.
- Deciding whether a response can still be modified.