How to Use Node.js Sessions to Persist Data

When your web application needs to “remember” users, it typically uses either of two mechanisms: cookies or sessions. A cookie is a small area of storage in the browser where you can keep user-related data like search preferences, for example. Sessions allow you to store sensitive information on the server instead.

Discover how to set up sessions in an Express server powered by Node.js.

MAKEUSEOF VIDEO OF THE DAY

SCROLL TO CONTINUE WITH CONTENT

What You’ll Need

To follow this tutorial, you need both Node.js and npm installed. Any recent version of Node.js should come with npm, a package manager for installing dependencies.

You’ll use npm to install Express and express-session. These are the tools you’ll use to create the web server and session.

What Is a Session in Node.js?

A cookie is a small file that your browser uses to store data. You can use cookies to store non-sensitive data like search preferences.

You should not store sensitive data (such as usernames and passwords) in cookies. When your browser sends cookies over HTTP, they’re vulnerable to hackers who may be able to intercept them. They’re also stored in plain text on your computer, so hackers can potentially inspect them and steal your data.

Instead of saving sensitive data as a cookie on the client, you should store it on the server. This keeps it protected from the outside world.

Sessions allow you to store sensitive data your app needs to identify the user. Examples are username, password, and email. They’re more secure because they live on the server, not the client.

Any time you have data that you want to persist across requests, save it on the server side using a session. You’ll learn how to create a session in the following section.

Creating a Session in an Express Server

Express is a popular web framework for Node.js. It lets you set up a web server application that listens to client requests at your chosen port number. You can create API routes, apply middleware and even connect the application to a database, all thanks to the APIs provided by the framework.

1. Create a Node.js Project

Create a brand-new folder for your project, then launch your command line tool and cd into that folder.

Next, run the following command to initialize a Node.js project:

 npm init -y 

This generates a package.json file in the project’s root folder with the default setup. The package.json file for running npm scripts.

2. Install Express and express-session

You’ll use Express to create the web server application. And express-session to create sessions on that server application.

On the terminal, run the following command to install both dependencies:

 npm i express express-session 

After installing both packages, the next step would be to create the server.

3. Create Sessions in the App

Create a file named App.js in your project’s root folder and import the dependencies:

 

const

express =

require

(

'express'

)

const

session =

require

(

'express-session'

)
app = express()

Next, register the session middleware. Pass in an object with the secret property (for signing the sessionID cookie) and the cookie.

 app.use(
  session({
    secret:

"some secret"

,
    cookie: {

maxAge

:

30000

},
    saveUninitialized:

false

,
  })
);

Here you set the greatest age of the session to 30 seconds (30000 milliseconds). Setting saveUnitialized to false is essential if you have a login system. If you fail to do so, your server will generate a new sessionID every time the user sends a request.

Next, create a login route to change the session. When a user hits this route, you expect the client to send the username and password in the request body. First, you access these values and check if they exist (and if the user has authenticated):

 app.post(

"/login"

, (req, res) => {
  

const

{ username, password } = req.body;

  

if

(username && password) {
    

if

(req.session.authenticated) {
      res.json(session);
    }

else

{
      

if

(password ===

"123"

) {
        req.session.authenticated =

true

;
        req.session.user = { username };
        res.json(req.session);
      }

else

{
        res.status(

403

).json({

msg

:

"Bad credentials"

});
      }
    }
  }

else

{
    res.status(

403

).json({

msg

:

"Bad credentials"

});
  }
});

With the first if statement, you perform a dummy check. This check is to ensure that you proceed only if the username and password are present.

Next, you check if the user is already authenticated. If so, send the session back to the client. If not, set the authenticated property to true and save the username to the session. Then send it back to the client.

With the above code, the server will remember each user that sends a request to the server. This is because they have authenticated and had their unique details (username and password) saved in the session.

Start your server by adding the following code at the bottom of App.js:

 app.listen(

3000

, () => {
  

console

.log(

"Server is running on port 3000"

);
});

To test this route, use an API client to send a request to the login route you created. Be sure to send the username and password in the request’s body. Here’s how your API request would look like if using Rest Client:

 POST http:
Content-Type:

"application/json"


{

username

:

"Kingsley"

, password:

"123"

}

If everything goes well, you’ll get the following object:

 {
  

"cookie"

: {
    

"originalMaxAge"

:

30000

,
    

"httpOnly"

:

true

,
    

"path"

:

"/"


  },
  

"authenticated"

:

true

,
  

"user"

: {
    

"username"

:

"Kingsley"

,
    

"password"

:

"123"


  }
}

With this code, two things have happened. First, you’ve authenticated on the server. Second, the session now has your login details, so the server now knows who you are. Any time you send a new request, it will remember you until the session expires and the server removes it.

Sessions Improve User Experience

Sessions are a vital part of Node.js applications. This is because they allow you to maintain a state of interaction across many requests and responses. Sessions are especially important for applications that need you to log in.

Use sessions in your backend application to keep track of user-specific data. An example of such data is the items your user has added to a shopping cart.

Without sessions, you’d have to maintain a separate data store for each user in your application. This would be inefficient and increase the complexity of the application.

Express.js Simplifies Sessions, Routing, and More

Express.js is the most popular Node.js web framework currently in use. It provides many tools and libraries for creating backend applications, and the express-session library is just one of them.

If you want to use Node.js for backend web development, then check out Express.