Languages
[Edit]
EN

Express.js - create session

1 points
Created by:
jarlh
635

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

Quick overview

The development of web application pages has made it necessary to store certain user information. Early on, browsers provided a cookie mechanism. However, due to its limitations, it was impossible to store certain information on the browser side.

These limitations are:

  • storage - the amount of information stored in cookies is limited,
  • security - sensitive informations should not be stored in cookies (directly in the browser).

The solution to this problem is the session mechanism which is based on association. The identifier (key) representing the object physically located on the server is stored in the web browser. This identifier is stored in a special cookie called a session cookie. When queries are sent to the server from the web browser, the web browser automatically also sends this identifier, based on which the related object is provided on the server side and the programmer can operate on it (read, set, delete information).

Practical example

1. First step is to install express-session package using npm: 

npm install express-session

2. Import the package with require() and use it as middleware using app.use().

3. From now you can also set session options, such as secret (you can find the full list of options here).

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

const app = express();

app.use(
    session({
        secret: 'replace this value with secret string ...'  // it is good to use random string
    })
);

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:

The secret is used to sign the session cookie, preventing possible cookie values from being guessed by other users.

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.
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

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