Cookie
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
Usage
Install the package from npm as follows:
npm i @poppinss/cookie
yarn add @poppinss/cookie
and then use it as follows
import { serialize, CookieOptions } from '@poppinss/cookie'
import { createServer } from 'http'
const expiresAt = new Date()
expiresAt.setDate(new Date().getDate() + 7)
const options: CookieOptions = {
domain: 'foo.com',
expires: expiresAt,
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.
import { parse } from '@poppinss/cookie'
const parsed = parse(req.headers.cookie)
API
Following are the autogenerated files via Typedoc.
Change log
The change log can be found in the CHANGELOG.md file.
Contributing
Everyone is welcome to contribute. Please go through the following guides, before getting started.
- Contributing
- Code of conduct
Authors & License
Harminder virk and contributors.
MIT License, see the included MIT file.