@poppinss/cookie
v1.0.8
Published
Cookie parser for Node.js
Downloads
47
Readme
Cookie
Cookie parser and serializer for Node.js
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'
)