Cookies Handling in Express JS and EJS


Handling cookies in an Express.js application involves setting, reading, and deleting cookies. Cookies are useful for storing small pieces of data on the client-side, such as user preferences, authentication tokens, or session identifiers. Here’s how you can handle cookies in an Express.js application with EJS templates:

1. Installing Required Package

To handle cookies in Express.js, you need the cookie-parser middleware.

Install it via npm:

npm install cookie-parser

2. Setting Up Cookie-Parser

Configure cookie-parser in your Express.js application to handle cookies.

const express = require('express'); const cookieParser = require('cookie-parser'); const path = require('path'); const app = express(); // Set up cookie-parser middleware app.use(cookieParser('your-secret-key')); // Replace with a secret key for signing cookies // Set the view engine to EJS app.set('view engine', 'ejs'); app.set('views', path.join(__dirname, 'views')); // Example route to set a cookie app.get('/set-cookie', (req, res) => { res.cookie('userName', 'JohnDoe', { httpOnly: true, // Helps prevent XSS attacks secure: false, // Set to true if using HTTPS maxAge: 24 * 60 * 60 * 1000 // Cookie expiry time (1 day) }); res.send('Cookie has been set'); }); // Example route to read a cookie app.get('/get-cookie', (req, res) => { const userName = req.cookies.userName || 'Guest'; res.send(`UserName from cookie: ${userName}`); }); // Example route to delete a cookie app.get('/delete-cookie', (req, res) => { res.clearCookie('userName'); res.send('Cookie has been deleted'); }); app.listen(3000, () => { console.log('Server is running on http://localhost:3000'); });

3. Setting Cookies

You can set cookies using the res.cookie method. Here’s a breakdown of the options:

  • name: The name of the cookie.
  • value: The value of the cookie.
  • options: Optional settings such as httpOnly, secure, and maxAge.

Example:

app.get('/set-cookie', (req, res) => { res.cookie('userName', 'JohnDoe', { httpOnly: true, // Cookie is accessible only by the web server secure: false, // Set to true if using HTTPS maxAge: 24 * 60 * 60 * 1000 // Cookie expiry time (1 day) }); res.send('Cookie has been set'); });

4. Reading Cookies

To read cookies, use req.cookies (populated by cookie-parser).

Example:

app.get('/get-cookie', (req, res) => { const userName = req.cookies.userName || 'Guest'; res.send(`UserName from cookie: ${userName}`); });

5. Deleting Cookies

To delete cookies, use res.clearCookie.

Example:

app.get('/delete-cookie', (req, res) => { res.clearCookie('userName'); res.send('Cookie has been deleted'); });

6. Using Cookies in EJS Templates

You can pass cookie values to EJS templates and use them for personalization.

Example Route:

app.get('/', (req, res) => { const userName = req.cookies.userName || 'Guest'; res.render('index', { userName }); });

EJS Template (views/index.ejs):

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Home Page</title> </head> <body> <h1>Welcome, <%= userName %>!</h1> <a href="/set-cookie">Set Cookie</a> <a href="/get-cookie">Get Cookie</a> <a href="/delete-cookie">Delete Cookie</a> </body> </html>

7. Security Considerations

  • httpOnly: Prevents JavaScript from accessing the cookie, reducing XSS risks.
  • secure: Ensures cookies are only sent over HTTPS, preventing them from being transmitted over unsecured connections.
  • sameSite: Controls whether cookies are sent with cross-site requests. Options include Strict, Lax, or None.

Example with Additional Security Settings:

app.get('/set-cookie', (req, res) => { res.cookie('userName', 'JohnDoe', { httpOnly: true, secure: true, // Set to true if using HTTPS sameSite: 'Strict', // Restrict cookie to same-site requests maxAge: 24 * 60 * 60 * 1000 // 1 day }); res.send('Cookie has been set with additional security settings'); });

Summary

  1. Install and Configure: Use cookie-parser to handle cookies in Express.js.
  2. Set Cookies: Use res.cookie to create cookies with various options.
  3. Read Cookies: Access cookies with req.cookies.
  4. Delete Cookies: Remove cookies with res.clearCookie.
  5. Use in EJS: Pass cookie data to EJS templates to personalize content.
  6. Implement Security: Use httpOnly, secure, and sameSite settings to enhance cookie security.