1.0.8 • Published 4 years ago

@poppinss/cookie v1.0.8

Weekly downloads
89
License
MIT
Repository
github
Last release
4 years ago

Cookie

Cookie parser and serializer for Node.js

circleci-image typescript-image npm-image license-image

A generic cookie parser and serializer for Node.js. This module exports handful of functions that can be used with any framework or even raw HTTP server to parse and serialize cookies.

Table of contents

Installation

Install the package from npm as follows:

npm i @poppinss/cookie

# yarn
yarn add @poppinss/cookie

Usage

import { serialize, CookieOptions } from '@poppinss/cookie'
import { createServer } from 'http'

const options: CookieOptions = {
  domain: 'foo.com',
  expires: () => {
    const expiresAt = new Date()

    // Expires in a week
    expiresAt.setDate(new Date().getDate() + 7)
  },
  httpOnly: true,
  path: '/',
  sameSite: true,
  secure: false,
}

createServer((req, res) => {
  const value = serialize('session-id', '1', null, options)
  res.setHeader('set-cookie', value)
  res.end()
})

Config

Under the hood this package uses cookie module, so make sure to check their docs for the config.

Signing cookies

It is recommended to sign the cookie values using a secret. The signed cookies ensures that they are not tampered on the client side and can be fully trusted.

To sign a cookie, you need to pass a secret as 3rd argument to the serialize method.

import { serialize } from '@poppinss/cookie'
const serialized = serialize('key', 'value', 'a-long-secret-to-sign-cookie')

res.setHeader('set-cookie', serialized)

For reading signed cookies, you will need the same secret, otherwise they will be considered as tampered and removed from the output.

Parsing cookies

You can parse the incoming cookies using the parse method.

import { parse } from '@poppinss/cookie'
const parsed = parse(req.headers.cookie)

For parsing signed cookies, you need the same secret that was used for signing cookies.

import { parse } from '@poppinss/cookie'

const parsed = parse(
  req.headers.cookie,
  'a-long-secret-to-sign-cookie'
)
1.0.8

4 years ago

1.0.7

4 years ago

1.0.6

4 years ago

1.0.5

4 years ago

1.0.4

4 years ago

1.0.3

4 years ago

1.0.2

5 years ago

1.0.1

5 years ago

1.0.0

5 years ago