What is cookie?
The 'cookie' npm package is a simple, lightweight utility for parsing and serializing cookies in Node.js. It is designed to work with the HTTP server's cookie headers to read and write cookies on the server side.
What are cookie's main functionalities?
Parse Cookie Header
This feature allows you to parse the Cookie header string into an object where each property is a cookie name and its value is the cookie value. It automatically handles URL-encoded cookie values.
const cookie = require('cookie');
const cookies = cookie.parse('foo=bar; equation=E%3Dmc%5E2');
Serialize Cookie
This feature lets you serialize a cookie name-value pair into a Set-Cookie header string with optional attributes such as `HttpOnly`, `Max-Age`, and others. It is useful for setting cookies in HTTP responses.
const cookie = require('cookie');
const serializedCookie = cookie.serialize('foo', 'bar', { httpOnly: true, maxAge: 60 * 60 * 24 });
Other packages similar to cookie
js-cookie
js-cookie is a simple, lightweight JavaScript API for handling cookies. It works well in all browsers and provides a clean API for cookie manipulation. Unlike 'cookie', js-cookie is primarily designed for client-side use and does not have built-in support for Node.js environments.
tough-cookie
tough-cookie is a more robust package for handling cookies in Node.js. It offers a wider range of features compared to 'cookie', including cookie jar support, which allows for storing and iterating over multiple cookies easily. It also handles parsing and serialization but with more options and considerations for security and cookie management.
cookies
The 'cookies' package is another alternative for handling cookies in Node.js and is often used with the Koa web framework. It provides a higher-level API for cookie management, including encryption and signing of cookie values, which 'cookie' does not offer out of the box.
cookie
cookie is a basic cookie parser and serializer. It doesn't make assumptions about how you are going to deal with your cookies. It basically just provides a way to read and write the HTTP cookie headers.
See RFC6265 for details about the http header for cookies.
how?
npm install cookie
var cookie = require('cookie');
var hdr = cookie.serialize('foo', 'bar');
var cookies = cookie.parse('foo=bar; cat=meow; dog=ruff');
more
The serialize function takes a third parameter, an object, to set cookie options. See the RFC for valid values.
path
cookie path
expires
absolute expiration date for the cookie (Date object)
maxAge
relative max age of the cookie from when the client receives it (seconds)
domain
domain for the cookie
secure
true or false
httpOnly
true or false