Skip to content
engineering workbench.by StudyPort Academy
All errors
runtime · DEBUG LIBRARY

Cannot set headers after they are sent

Locate the failed assumption, reproduce it, then repair the cause.

What actually caused it

One request gets one response. res. and res.send write the status line and the body, and then the headers are sent. A later res.status, res.json, or res.send tries to start a second response on a connection that already has one. Node reports that the headers were already sent. The second call is often in a middleware that runs after the route, or in a branch you thought had not already answered. The first write succeeded. The error is the extra write, not a failed database or a bad status code.

Minimal reproduction

Two writes

app.post('/notes', (req, res) => {
  res.status(201).json({ saved: true });
  res.send('done');
});

The second send runs after the response has already started.

The fix

Send the response in one place. If a guard should answer, return after it sends so the route does not answer again. If you need a different status, set it before the single or send call, as in res.status(201).json(body). Search the handler for a second res.json or res.send. Remove it, then run the same request and confirm one status and one body.

One write

app.post('/notes', (req, res) => {
  res.status(201).json({ saved: true });
});

Status and body leave together, once.