Q1. How do you set cookies in Express?
Use
Example:
Options include
res.cookie(name, value, options).Example:
res.cookie('username', 'john', { maxAge: 900000, httpOnly: true });Options include
maxAge (expiry), httpOnly (prevents client-side access), secure (HTTPS only), sameSite, and domain/path.Q2. How do you read cookies in Express?
First, install and use cookie-parser middleware:
Then cookies are available in
Example:
Signed cookies are in
app.use(require('cookie-parser')());Then cookies are available in
req.cookies.Example:
const username = req.cookies.username;Signed cookies are in
req.signedCookies if you use a secret.Q3. How do you clear cookies?
Use
Usually you specify the same path and domain used when setting the cookie.
Example:
This removes the cookie from the client.
res.clearCookie(name, options).Usually you specify the same path and domain used when setting the cookie.
Example:
res.clearCookie('username', { path: '/' });This removes the cookie from the client.
Q4. What are signed cookies?
Signed cookies are cookies that are cryptographically signed to prevent tampering.
When setting a cookie with
The client can't modify the cookie without breaking the signature.
You access them via
When setting a cookie with
{ signed: true }, Express creates a signature and sends it separately.The client can't modify the cookie without breaking the signature.
You access them via
req.signedCookies.Q5. What security options should you set for cookies?
Always set
Use
Set
Set appropriate domain and path.
Use signed cookies to detect client-side modifications.
httpOnly: true for session cookies to prevent XSS attacks.Use
secure: true in production (HTTPS).Set
sameSite: 'strict' or 'lax' to prevent CSRF.Set appropriate domain and path.
Use signed cookies to detect client-side modifications.
