modern-cookies
v1.0.3
Published
๐ช A Lightweight and Modern Cookie Utility for Express and Nest.js
Maintainers
Readme
Why modern-cookies? ๐ค
- ๐ก Simple API โ Intuitive functions
setCookie,getCookie, anddeleteCookiefor effortless cookie management. - ๐จ Built on Reliability โ Uses the proven cookie library for RFC-compliant parsing and serialization.
- โ Graceful Error Handling โ Returns
falseon failures and provides alogErrorflag for optional console logging. - ๐ก๏ธ Security-Aware Defaults โ Automatically enforces rules for special prefixes:
__Secure-and__Host-.
Installation ๐ฅ
npm install modern-cookies@latest
# or
yarn add modern-cookies@latest
# or
pnpm install modern-cookies@latest
# or
bun add modern-cookies@latestUsage ๐ช
Express ๐ซ
import express from "express";
import { getCookie, setCookie, deleteCookie } from "modern-cookies";
import { env } from "./env";
function bootstrap() {
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.get("/get-cookie", (req, res) => {
const cookieValue = getCookie(req, "myCookie");
res.json({ cookieValue });
});
app.get("/set-cookie", (req, res) => {
const isSet = setCookie(res, "myCookie", "SomeValue123", {
httpOnly: true,
maxAge: 60, // 1 minute
});
res.json({ message: isSet ? "Cookie set successfully" : "Failed to set cookie" });
});
app.get("/delete-cookie", (req, res) => {
const isDeleted = deleteCookie(res, "myCookie");
res.json({ message: isDeleted ? "Cookie deleted successfully" : "Failed to delete cookie" });
});
app.listen(env.PORT || 3000, () => {
console.log(`๐ Express server running on: http://localhost:${env.PORT || 3000}`);
});
}
bootstrap();NestJS ๐ชบ
import { Controller, Get, Req, Res } from "@nestjs/common";
import type { Request, Response } from "express";
import { getCookie, setCookie, deleteCookie } from "modern-cookies";
@Controller("")
export class PublicController {
@Get("get-cookie")
getCookie(@Req() req: Request) {
const cookieValue = getCookie(req, "myCookie");
return { cookieValue };
}
@Get("set-cookie")
setCookie(@Res() res: Response) {
const isSet = setCookie(res, "myCookie", "SomeValue123", {
httpOnly: true,
maxAge: 60, // 1 minute
});
// Since we used the `Res` we need to send the response manually
res.json({ message: isSet ? "Cookie set successfully" : "Failed to set cookie" });
}
@Get("delete-cookie")
deleteCookie(@Res() res: Response) {
const isDeleted = deleteCookie(res, "myCookie");
res.json({ message: isDeleted ? "Cookie deleted successfully" : "Failed to delete cookie" });
}
}Credit ๐ช๐ฝ
Huge credit to Cookie NPM package for the cookie parsing and serialization used in this package.
Contributions ๐ค
Want to contribute or suggest a feature or improvement?
- Open an issue or feature request
- Submit a PR to improve the packages or add new ones
- Star โญ the repo if you like what you see
