Express sessions with EJS


Using Express sessions with EJS allows you to maintain user state across multiple requests in your Express.js application. Sessions are useful for storing user-specific data, such as login status, user preferences, or shopping cart contents. Here’s how you can set up and use Express sessions in combination with EJS:

1. Installing Required Packages

To use sessions in Express.js, you need to install the express-session package. This package provides session management middleware for Express applications.

npm install express-session

2. Setting Up Express Sessions

  1. Configure Express to Use Sessions:

    In your main application file (e.g., app.js), configure the express-session middleware. This middleware will handle session management and store session data.

    const express = require('express'); const session = require('express-session'); const path = require('path'); const app = express(); // Set the view engine to EJS app.set('view engine', 'ejs'); app.set('views', path.join(__dirname, 'views')); // Configure express-session middleware app.use(session({ secret: 'your-secret-key', // A secret key for signing the session ID cookie resave: false, // Whether to save the session even if it was not modified saveUninitialized: true, // Whether to save a session that is new but not modified cookie: { secure: false } // Set secure: true if you're using HTTPS })); // Example route app.get('/', (req, res) => { // Access session data const userName = req.session.userName || 'Guest'; res.render('index', { userName }); }); app.listen(3000, () => { console.log('Server is running on http://localhost:3000'); });

    In this setup:

    • secret is used to sign the session ID cookie. It should be a unique and secure string.
    • resave and saveUninitialized control session behavior. Typically, resave should be set to false unless you have specific requirements.
    • cookie.secure should be set to true in production if you’re using HTTPS.
  2. Using Sessions in Routes:

    You can use sessions to store and retrieve user-specific data in your route handlers.

    // Route to set session data app.post('/login', (req, res) => { req.session.userName = req.body.userName; res.redirect('/'); }); // Route to destroy the session app.get('/logout', (req, res) => { req.session.destroy((err) => { if (err) { return res.redirect('/'); } res.redirect('/'); }); });

3. Using Session Data in EJS Templates

In your EJS templates, you can use the data stored in sessions to personalize content. For example, if you want to display a user’s name:

<!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> <% if (userName !== 'Guest') { %> <a href="/logout">Logout</a> <% } else { %> <form action="/login" method="POST"> <input type="text" name="userName" placeholder="Enter your name" required> <button type="submit">Login</button> </form> <% } %> </body> </html>

4. Securing Sessions

For added security, consider the following:

  • Use HTTPS: Set cookie.secure to true to ensure cookies are only sent over HTTPS.

  • Session Store: By default, Express sessions are stored in memory, which is not suitable for production. Consider using a session store like Redis, MongoDB, or a database-backed store for scalability and persistence.

    npm install connect-redis redis
    const session = require('express-session'); const RedisStore = require('connect-redis')(session); const redisClient = require('redis').createClient(); app.use(session({ store: new RedisStore({ client: redisClient }), secret: 'your-secret-key', resave: false, saveUninitialized: false, cookie: { secure: true } // Set secure to true if using HTTPS }));

5. Testing Sessions

To test sessions, perform the following actions:

  1. Login: Submit the login form to set session data.
  2. Access Protected Routes: Navigate to different routes to see session data being utilized.
  3. Logout: Click the logout link to destroy the session and verify redirection.

Summary

  1. Install and Configure: Use express-session to manage sessions in Express.js.
  2. Store and Access Data: Use session data in your route handlers and EJS templates.
  3. Secure Sessions: Configure HTTPS, use a session store, and manage session security settings.
  4. Testing: Ensure that session functionality works as expected through login, logout, and data persistence.

By setting up and using sessions effectively, you can create dynamic, personalized web applications with Express.js and EJS.