Saswat
Saswat

Reputation: 339

Cannot set headers after they are sent to the client while using res.redirect()

So basically i have a route in express. If the user is logged in or they are verified redirect me to the dashboard if i am on the login page else stay where i am in the login page.

function checkGuest(req,res,next) {
  let token = req.cookies['session-token'];
  async function verify() {
    const ticket = await client.verifyIdToken({
      idToken: token,
      audience: CLIENT_ID
    })
  }
  verify()
  .then(() => {
    res.redirect('/dashboard') //if the user is logged in go to dashboard
    next();
  })
  .catch(err => {
    next(); //else stay where you are
  }) 
}

And here's how i am using it in my route:

router.get('/',checkGuest,(req,res) => {
    res.render('login',{
        layout: 'login'
    })
})

This is the error Error [ERR_HTTP_HEADERS_SENT] cannot send headers after they are sent back to the client

Hope you understood it.

Your suggestions and quick replies are appreciated

Upvotes: 0

Views: 56

Answers (1)

Sahid Hossen
Sahid Hossen

Reputation: 1467

Please return your response. You are not returning the response that's why the header moves to the next line.

function checkGuest(req,res,next) {
  let token = req.cookies['session-token'];
  async function verify() {
    const ticket = await client.verifyIdToken({
      idToken: token,
      audience: CLIENT_ID
    })
  }
  verify()
  .then(() => {
    return res.redirect('/dashboard') //if the user is logged in go to dashboard
  })
  .catch(err => {
    next(); //else stay where you are
  }) 
}
router.get('/',checkGuest,(req,res) => {
    return res.render('login',{
        layout: 'login'
    })
})

Upvotes: 3

Related Questions