modern-cookies
v2.0.0
Published
πͺ A Lightweight and Modern Cookie Utility for Express and Nest.js
Maintainers
Readme
Highlights β¨
- Simple API β
setCookie,getCookie, anddeleteCookie - Framework compatibility β supports Express v5/v4 and NestJS (Express adapter)
- Security-first enforcement β enforces
__Secure-/__Host-rules and auto-forcessecure: trueforsameSite: "none" - Graceful error handling β returns
boolean, never throws - Built on the RFC-compliant
cookielibrary
Installation π¦
Requires Node.js >= 18.
npm install modern-cookies
# or
pnpm add modern-cookiesQuick Start π
import express from "express";
import { getCookie, setCookie, deleteCookie } from "modern-cookies";
const app = express();
app.post("/login", (req, res) => {
setCookie(res, "session", "abc123", { httpOnly: true, secure: true, sameSite: "lax", maxAge: 86400 });
res.json({ message: "Logged in" });
});
app.get("/profile", (req, res) => {
const session = getCookie(req, "session");
res.json({ session });
});
app.post("/logout", (req, res) => {
deleteCookie(res, "session");
res.json({ message: "Logged out" });
});
app.listen(3000);API Reference π
getCookie(req, name, logError?): string | undefined
Retrieves a cookie value from the request's Cookie header. Returns undefined if not found.
| Parameter | Type | Default | Description |
| ---------- | --------- | ------- | --------------------------------------------- |
| req | Request | β | The Express request object |
| name | string | β | The name of the cookie to retrieve |
| logError | boolean | false | If true, logs parsing errors to the console |
const session = getCookie(req, "session");
// Enable error logging for debugging
const theme = getCookie(req, "theme", true);setCookie(res, name, value, options, logError?): boolean
Sets a cookie on the response. The options parameter is required. Returns true on success, false on failure.
| Parameter | Type | Default | Description |
| ---------- | --------------- | ------- | --------------------------------------------------- |
| res | Response | β | The Express response object |
| name | string | β | The name of the cookie to set |
| value | string | β | The value of the cookie |
| options | CookieOptions | β | Configuration for the cookie's attributes |
| logError | boolean | false | If true, logs serialization errors to the console |
setCookie(res, "theme", "dark", { maxAge: 60 * 60 * 24 * 365, sameSite: "strict" });
// Check if the cookie was set successfully
const ok = setCookie(res, "lang", "en", { maxAge: 60 * 60 * 24 * 365 });Tip: For session or auth cookies, always set
{ httpOnly: true, secure: true, sameSite: "lax" }to mitigate XSS and CSRF risks.
deleteCookie(res, name, options?, logError?): boolean
Deletes a cookie by setting maxAge: 0 and expires to the Unix epoch for maximum browser compatibility. If the cookie was set with a specific path or domain, pass the same values to ensure the correct cookie is removed. Similarly, if the cookie was set with sameSite: "none", pass sameSite: "none" in the delete options so the browser matches and removes the correct cookie.
| Parameter | Type | Default | Description |
| ---------- | --------------- | ------- | ------------------------------------------- |
| res | Response | β | The Express response object |
| name | string | β | The name of the cookie to delete |
| options | CookieOptions | {} | Additional options (e.g., path, domain) |
| logError | boolean | false | If true, logs errors to the console |
deleteCookie(res, "session");
// If the cookie was set with a specific path/domain, match them
deleteCookie(res, "tracking", { path: "/app", domain: "example.com" });
// If the cookie was set with sameSite: "none", pass it on delete too
deleteCookie(res, "cross-origin", { sameSite: "none" });CookieOptions
interface CookieOptions {
httpOnly?: boolean;
secure?: boolean;
sameSite?: "strict" | "lax" | "none" | "Strict" | "Lax" | "None";
maxAge?: number; // Lifetime in seconds; omit for session cookie
expires?: Date; // Exact expiration date (Expires attribute)
path?: string; // URL path scope (default: "/")
domain?: string; // Domain scope; omit to restrict to current host
priority?: "low" | "medium" | "high";
}Type export:
import type { CookieOptions } from "modern-cookies"
Security Features π‘οΈ
Cookie Prefix Enforcement
When you use special cookie name prefixes, setCookie automatically enforces the required attributes:
| Prefix | Enforced Attributes |
| ----------- | --------------------------------------------- |
| __Secure- | secure: true |
| __Host- | secure: true, path: "/", domain removed |
// secure is automatically forced to true
setCookie(res, "__Secure-Token", value, { httpOnly: true });
// secure, path, and domain are all enforced
setCookie(res, "__Host-Token", value, { httpOnly: true });sameSite: "none" Enforcement
When sameSite is set to "none", secure: true is automatically added. This prevents browsers from silently rejecting the cookie.
// secure: true is added automatically
setCookie(res, "cross-origin", value, { sameSite: "none" });Safe Error Logging
When logError is enabled, error messages include only the cookie name and the error reason β never the cookie value. All logged strings are sanitized (newlines and control characters are stripped, length is capped) to prevent log injection.
NestJS π§©
import { Controller, Get, Post, Req, Res } from "@nestjs/common";
import type { Request, Response } from "express";
import { getCookie, setCookie, deleteCookie } from "modern-cookies";
@Controller("auth")
export class AuthController {
@Post("login")
login(@Res() res: Response) {
const token = "generated-session-token";
setCookie(res, "session", token, { httpOnly: true, secure: true, sameSite: "lax", maxAge: 60 * 60 * 24 });
res.json({ success: true });
}
@Get("me")
me(@Req() req: Request, @Res() res: Response) {
const session = getCookie(req, "session");
if (!session) return res.status(401).json({ error: "Not authenticated" });
res.json({ session });
}
@Post("logout")
logout(@Res() res: Response) {
deleteCookie(res, "session");
res.json({ success: true });
}
}Credits π
Built on the cookie package for RFC-compliant parsing and serialization.
Contributions π€
- Open an issue or feature request
- Submit a PR to improve the package
- Star the repo if you find it useful
Crafted carefully by WolfieLeader
This project is licensed under the MIT License.
