Languages
[Edit]
EN

Node.js / Express.js - create session

0 points
Created by:
Dirask JS Member
3640

In this article, we would like to show you how to create a session in Express.js.

First step is to install express-session using npm: 

npm install express-session

Then we import the module with require and use it as middleware using app.use().
There we also set session options, such as secret (you can find the full list of options here).

Practical example

const express = require('express');
const session = require('express-session');
const app = express();

app.use(
    session({
        secret: 'secret',
    })
);

app.get('/', (request, response) => {
    if (request.session.views) {
        request.session.views++;
    } else {
        request.session.views = 1;
    }
    response.send(`Number of views ${request.session.views}`);
});

app.listen(3000);

Note: 

secret is used to sign the session ID cookie.

If you go to localhost:3000 from two different browsers, each browser will be assigned a different session.

Two different browsers having separate sessions.
Two different browsers having separate sessions.

Node.js / Express.js - session management

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join