Sling Academy
Home/Node.js/Using Sessions in Express.js

Using Sessions in Express.js

Last updated: December 28, 2023

Overview

Sessions are a critical component in web development for maintaining the state between multiple page requests. Express.js, a fast and minimalist web framework for Node.js, provides easy-to-use mechanisms for handling sessions. In this tutorial, you will learn how to implement sessions to manage user data securely and reliably.

What is a Session?

A session is a server-side storage of user data that can persist across multiple requests. Whenever a user interacts with a web application, a unique session ID is generated and sent to the client-side in the form of a cookie. This ID is then sent back to the server with each subsequent request, allowing the server to retrieve the stored user data and provide a personalized experience.

Why Do We Need Sessions?

Sessions are essential for identifying users across requests, carrying data through your web application, and implementing features like user login systems, shopping carts, or any scenario where the server needs to remember user-specific information.

How to Use Sessions in Express.js

To manage sessions in Express.js, you often utilize middleware that handles the session logic. One common package used for this is ‘express-session’, which provides session support out-of-the-box.

Basic Code Example

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

const app = express();

app.use(session({
  secret: 'your_secret_key',
  resave: false,
  saveUninitialized: true,
  cookie: { secure: true }
}));

app.get('/', (req, res) => {
  if (req.session.views) {
    req.session.views++;
    res.write('<p>Views: ' + req.session.views + '</p>');
    res.write('<p>Expires in: ' + (req.session.cookie.maxAge / 1000) + ' seconds</p>');
    res.end();
  } else {
    req.session.views = 1;
    res.end('Welcome to this page for the first time!');
  }
});

app.listen(3000, () => {
  console.log('Server running on port 3000.');
});

Advanced Code Example

For more advanced session management, you can use stores like ‘connect-redis’ to keep your session state even if your server restarts, and manage large-scale applications.

const express = require('express');
const session = require('express-session');
const redis = require('redis');
const RedisStore = require('connect-redis')(session);
const redisClient = redis.createClient();

const app = express();

app.use(session({
  store: new RedisStore({ client: redisClient }),
  secret: 'your_secret_key',
  resave: false,
  saveUninitialized: false
}));

// ... Your routes here

app.listen(3000, () => {
  console.log('Server running with Redis store on port 3000.');
});

Summary

In this guide, we explored the concept of sessions in Express.js applications, their necessity, and the way they are implemented, from basic usage with ‘express-session’ to more advanced session handling with a Redis store. Properly using sessions can greatly enhance your application’s functionality and user experience. Remember to handle user data with care, ensuring privacy and security are always at the forefront of your session management strategy.

Next Article: Node.js & Express: Implementing Route Guards with Middleware (3 Ways)

Previous Article: How to Download a File from NodeJS Server using Express

Series: Node.js & Express Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates