res.cookie()

Sets a cookie with name (name) and value (value) to be sent along with the response.

Usage

  1. res.cookie(name, value [,options]);

Details

The “path” option defaults to “/“.

The “maxAge” option is a convenience option for setting “expires” relative to the current time in milliseconds. The following is equivalent to the previous example.

  1. res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })

An object may be passed which is then serialized as JSON, which is automatically parsed by the bodyParser() middleware.

  1. res.cookie('cart', { items: [1,2,3] });
  2. res.cookie('cart', { items: [1,2,3] }, { maxAge: 900000 });

Signed cookies are also supported through this method. Simply pass the signed option. When given res.cookie() will use the secret passed to express.cookieParser(secret) to sign the value.

  1. res.cookie('name', 'tobi', { signed: true });

Example

  1. res.cookie('name', 'tobi', {
  2. domain: '.example.com',
  3. path: '/admin',
  4. secure: true
  5. });
  6. res.cookie('rememberme', '1', {
  7. expires: new Date(Date.now() + 900000),
  8. httpOnly: true
  9. });