Ilja
Ilja

Reputation: 46527

Express / node.js Can't set headers after they are sent

I am trying to pipe my session api request through server in order to set an httpOnly cookie with session token, and ran into an error saying:

Can't set headers after they are sent

Not entirely sure what this means, but here is my interceptor in express, that listens to a post to /api/sessions endpoint and in successful scenario sets a cookie

app.post('/api/sessions', (req, res) => {
  const url = `${config.API_HOST}/sessions`
  let apiCall = request.post(url, (err, response, body) => {
    if (!err && response.statusCode === 200) {
      const data = JSON.parse(body)
      let sessionCookie = { 
        path: '/', 
        hostOnly: true,
        secure: true,
        httpOnly: true
      }
      res.cookie('SESS', data.token, sessionCookie)
    }
  })
  req.pipe(apiCall).pipe(res)
})

EDIT: reason why I pipe it is to be able and use promisses in my client side app.

Upvotes: 1

Views: 726

Answers (1)

realbisoye
realbisoye

Reputation: 88

From the error message above, you are are trying to send a response twice some where in your code. Can't set headers after they are sent implies that you code is trying to modify the response headers (probably in order to send a new response) after a previous response has been sent.

From your implementation, you are calling res in res.cookie('SESS', data.token, sessionCookie)in apiCall definition and also piping the apiCall to res in on this line req.pipe(apiCall).pipe(res), modifying the response object a second time. I think res.cookie calls res.end internally. If this is the case any further call or edit to res will throw the error you have.

You should be able to fix this by removing .pipe(res) part in req.pipe(apiCall).pipe(res).and simply use

req.pipe(apiCall)

You can check this question on how to set and send cookies in express and this question on better explanation of the error message.

Upvotes: 2

Related Questions