Cookies
LiteNode includes a complete cookie management system: parsing incoming cookies, setting response cookies, and signing cookies for tamper detection.
Enabling Cookie Parsing
Call enableCookieParser() once before your routes to parse incoming Cookie headers into req.cookies:
const app = new LiteNode()
app.enableCookieParser()
Setting Cookies
app.get("/welcome", (req, res) => {
res.setCookie("greeting", "hello")
res.txt("Cookie set!")
})
Cookie Options
res.setCookie("preferences", "dark-mode", {
maxAge: 30 * 24 * 60 * 60, // 30 days in seconds
path: "/",
httpOnly: true,
secure: true,
sameSite: "Strict",
})
| Option | Type | Description |
|---|---|---|
maxAge |
number | Max age in seconds |
expires |
Date | string | Specific expiration date |
path |
string | Cookie scope path (default: /) |
domain |
string | Cookie scope domain |
secure |
boolean | HTTPS only |
httpOnly |
boolean | Inaccessible to JavaScript |
sameSite |
string | "Strict", "Lax", or "None" |
Reading Cookies
app.get("/dashboard", (req, res) => {
const theme = req.cookies.theme || "light"
res.render("dashboard.html", { theme })
})
Clearing Cookies
app.get("/logout", (req, res) => {
res.clearCookie("session")
res.redirect("/login")
})
If the cookie was set with a specific path or domain, pass the same options when clearing:
res.clearCookie("tracking", { path: "/products" })
getCookies()
Returns all cookies set on the current response as an array of raw strings — useful for debugging:
res.setCookie("a", "1")
res.setCookie("b", "2")
console.log(res.getCookies())
// → ['a=1; Path=/', 'b=2; Path=/']
Signed Cookies
Signed cookies are cryptographically verified — if the value is tampered with, getCookie returns null.
Setup
app.enableCookieParser()
const signedCookies = app.createSignedCookies("your-secret-key-min-16-chars")
Setting a Signed Cookie
app.post("/login", async (req, res) => {
await signedCookies.setCookie(res, "userId", "42", {
maxAge: 24 * 60 * 60,
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "Lax",
})
res.redirect("/dashboard")
})
Reading and Verifying
app.get("/dashboard", async (req, res) => {
const userId = await signedCookies.getCookie(req, "userId")
if (!userId) return res.redirect("/login") // missing or tampered
res.render("dashboard.html", { userId })
})
API
createSignedCookies(secret) returns:
| Method | Description |
|---|---|
setCookie(res, name, value, options) |
Set a signed cookie |
getCookie(req, name) |
Get and verify — returns null if invalid |
sign(value) |
Sign a raw value |
verify(signedValue) |
Verify a signed value directly |
Security Best Practices
- Always set
httpOnly: truefor session/auth cookies - Set
secure: truein production - Use
sameSite: "Strict"or"Lax"against CSRF - Use signed cookies for any value that must be trusted
- Store only the minimum — session IDs, not full user objects
- Set the shortest practical
maxAge
See the Examples page for complete auth and preferences patterns.