DEV Community

gaurbprajapati
gaurbprajapati

Posted on

What is session and how to create with detailed code explaination in Nodejs

A session is a mechanism that allows servers to store user-specific data and maintain stateful interactions with clients. It is used to track and manage user sessions across multiple requests. Sessions are typically implemented using a unique session identifier stored on the client-side (usually in a cookie) and corresponding session data stored on the server-side.

  1. Set up the project:

    • Create a new directory for your project and navigate to it.
    • Initialize a new Node.js project and install the required dependencies:
     npm init -y
     npm install express express-session
    
  2. Create a server.js file and set up the basic Express server:

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

   // Middleware for parsing JSON requests
   app.use(express.json());

   // Configure session middleware
   app.use(
     session({
       secret: 'your-secret-key',
       resave: false,
       saveUninitialized: true,
     })
   );

   // Endpoint for setting session data
   app.get('/set-session', (req, res) => {
     req.session.username = 'exampleuser';
     res.send('Session data set successfully');
   });

   // Endpoint for retrieving session data
   app.get('/get-session', (req, res) => {
     const username = req.session.username;
     res.send(`Session data: ${username}`);
   });

   // Start the server
   app.listen(port, () => {
     console.log(`Server listening on port ${port}`);
   });
Enter fullscreen mode Exit fullscreen mode
  1. Start the server:

    • Run node server.js in the command line to start the server.
  2. Testing the session:

    • Access http://localhost:3000/set-session in a web browser or using an API testing tool like Postman.
    • After accessing the endpoint, the server will respond with the message "Session data set successfully" and set a session variable named "username" with the value "exampleuser".
    • Access http://localhost:3000/get-session to retrieve the session data. The server will respond with the session data, in this case, "Session data: exampleuser".

Let's break down the relevant code:

  • app.use(session({ ... })): This sets up the session middleware using the express-session package. It takes an options object as an argument. In this example, we specify a secret key to sign the session ID, resave: false to avoid resaving the session on every request, and saveUninitialized: true to save uninitialized sessions.

  • req.session: This is an object attached to the request that represents the session data. You can assign values to it, retrieve values from it, and modify session-specific data as needed.

  • req.session.username = 'exampleuser': This line sets the session variable username to the value 'exampleuser'. You can store any necessary data in the session based on your application's requirements.

  • req.session.username: This line retrieves the value of the username session variable. You can access session data in a similar way.

By using the session middleware, the server assigns a unique session ID to each client and stores the associated session data on the server-side. The session ID is typically sent to the client as a cookie, allowing the client to include it in subsequent requests. The server can then identify the client and retrieve the corresponding session data.

In addition to secret, resave, and saveUninitialized, the express-session middleware supports several other options that you can pass to configure session behavior. Here are some commonly used options:

  • name: Specifies the name of the session cookie. By default, the cookie is named 'connect.sid'. You can set a custom name for the session cookie.

  • cookie: Allows you to configure various properties of the session cookie. For example:

    • maxAge: Sets the maximum age (in milliseconds) of the session cookie. After this duration, the cookie will expire.
    • secure: When set to true, the session cookie will only be sent over HTTPS connections.
    • httpOnly: When set to true, the session cookie cannot be accessed by client-side JavaScript, enhancing security.
    • sameSite: Specifies the SameSite attribute of the session cookie to control its behavior in cross-site requests.
  • store: Specifies the session store to use for storing session data. By default, session data is stored in memory, but you can choose alternative session stores such as databases (e.g., MongoDB, Redis) or other external storage options.

  • rolling: When set to true, the session cookie's expiration is updated on every request. This is useful to keep the session alive as long as the user is actively interacting with the application.

  • proxy: When set to true, the session cookie will be trusted even if the application is behind a reverse proxy. This is necessary for certain deployment scenarios.

  • proxySecure: When set to true, the session cookie will be set as secure even if the application is behind a reverse proxy. This ensures the session cookie is only sent over secure connections.

Example of how to use some of the additional options in the express-session middleware:

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

// Middleware for parsing JSON requests
app.use(express.json());

// Configure session middleware
app.use(
  session({
    secret: 'your-secret-key',
    resave: false,
    saveUninitialized: true,
    name: 'mySession',
    cookie: {
      maxAge: 86400000, // 24 hours
      secure: true,
      httpOnly: true,
      sameSite: 'strict'
    },
    store: mySessionStore, // Replace with your preferred session store
    rolling: true,
    proxy: true,
    proxySecure: true
  })
);

// Endpoint for setting session data
app.get('/set-session', (req, res) => {
  req.session.username = 'exampleuser';
  res.send('Session data set successfully');
});

// Endpoint for retrieving session data
app.get('/get-session', (req, res) => {
  const username = req.session.username;
  res.send(`Session data: ${username}`);
});

// Start the server
app.listen(port, () => {
  console.log(`Server listening on port ${port}`);
});
Enter fullscreen mode Exit fullscreen mode

Let's go through the additional options used in this code:

  • name: The session cookie is set with the name 'mySession' instead of the default name 'connect.sid'. You can customize the cookie name as per your preference.

  • cookie: The cookie option is an object that allows you to configure various properties of the session cookie. In this example, we have set:

    • maxAge: The session cookie will expire after 24 hours (in milliseconds).
    • secure: The session cookie will only be sent over secure (HTTPS) connections.
    • httpOnly: The session cookie cannot be accessed by client-side JavaScript.
    • sameSite: The session cookie will only be sent with requests from the same site.
  • store: The store option allows you to specify a custom session store for storing session data. You can replace mySessionStore with your preferred session store (e.g., a database-backed store like connect-mongo or connect-redis).

  • rolling: Setting rolling to true ensures that the session cookie's expiration is updated on every request, effectively extending the session duration as long as the user remains active.

  • proxy and proxySecure: Setting these options to true allows the session cookie to be trusted even when the application is behind a reverse proxy and ensures that the session cookie is set as secure even if the application is accessed via a reverse proxy.

Remember to adjust these options based on your specific requirements and security considerations.

Top comments (0)