WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Node.js · Intermediate · question 30 of 100

How do you manage sessions in Express.js?

📕 Buy this interview preparation book: 100 Node.js questions & answers — PDF + EPUB for $5

Managing sessions in Express.js is typically done with the help of middleware, particularly the ‘express-session‘ and ‘cookie-parser‘ middleware packages. These facilitate storing session data either in memory, server-side (such as a database), or client-side (as cookies).

Here’s a step-by-step guide on how to manage sessions using Express.js:

1. Install the required dependencies:

npm install express express-session cookie-parser

2. Import the dependencies in your app:

const express = require('express');
const session = require('express-session');
const cookieParser = require('cookie-parser');

3. Initialize the middleware and define session options:

const app = express();
app.use(cookieParser());
app.use(session({
    secret: 'your-secret-key',
    resave: false,
    saveUninitialized: true,
    cookie: { secure: false }
}));

In this example, ‘your-secret-key‘ should be replaced with a secret key unique to your application. ‘secure: false‘ indicates that cookies are not using SSL, but you should typically set it to ‘true‘ in a production environment.

4. Now, you can set, access, and delete sessions in your route handlers.

Example: setting a session value on a route:

app.post('/login', (req, res) => {
    // Authenticate the user and then set the session value
    req.session.user = {
        id: 1,
        username: 'johndoe'
    };
    res.send('User logged in');
});

Example: accessing the session value in another route:

app.get('/profile', (req, res) => {
    if (req.session.user) {
        res.send(`Welcome ${req.session.user.username}`);
    } else {
        res.send('Please log in first');
    }
});

Example: deleting a session value (logout):

app.get('/logout', (req, res) => {
    if (req.session) {
        req.session.destroy((err) => {
            if (err) {
                return res.send('Error: ' + err.message);
            }
            res.send('Session destroyed, user logged out');
        });
    } else {
        res.send('No active session found');
    }
});

In this example, the session data is stored in memory. However, this is not recommended for production environments. Popular options for persistent storage include using Redis or MongoDB as a session store, by using additional middleware packages such as ‘connect-redis‘ or ‘connect-mongo‘ respectively.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Node.js interview — then scores it.
📞 Practice Node.js — free 15 min
📕 Buy this interview preparation book: 100 Node.js questions & answers — PDF + EPUB for $5

All 100 Node.js questions · All topics