5

I want to send an 'httpOnly' cookie with my response from Vercel serverless functions. I am NOT using Express.

I tried res.setHeader("Set-Cookie", `ck=${cookie_value}`);

This doesn't work. How do I send cookies and put an expiry time on it?

styfle
  • 22,361
  • 27
  • 86
  • 128
Aritra Dattagupta
  • 760
  • 1
  • 7
  • 22

1 Answers1

7

The standard Node.js setHeader works with the standard Set-Cookie header.

Try using an array like this:

module.exports = (req, res) => {
  res.setHeader('Set-Cookie', ['ck=value; Expires=Tue, 01 Dec 2020 00:00:00 GMT; HttpOnly']);
  res.end('It worked, check your cookies in devtools');
}

For a nicer interface, you might try installing the cookie package.

const { serialize } = require('cookie')

module.exports = (req, res) => {
  const cookie = serialize('ck', 'value', {httpOnly: true, expires: new Date('2020-12-01')})
  res.setHeader('Set-Cookie', [cookie]);
  res.end('It worked, check your cookies in devtools');
}
styfle
  • 22,361
  • 27
  • 86
  • 128