Complete Guide to Using Sessions in Node.js (CJS & ESM) – So Your Backend Won’t Forget Users!

 


Have you ever logged into a website, navigated to another page, and suddenly got logged out? Feels like meeting an old friend who forgets your name. 😭

To prevent your Node.js backend from being forgetful, we can use sessions! 🎉

A session is like a membership card for users. Once they log in, the backend will remember them until the session expires or they log out.

Let’s dive into how to use sessions in Node.js with both CommonJS (CJS) and ES Module (ESM)! 🏆

🚀 1. What is a Session in Node.js?

A session allows the backend to temporarily store user data on the server.
Common uses of sessions:

Keep users logged in without requiring them to send a token on every request.
Store user preferences during a session.
Enhance security (safer than storing tokens in localStorage).

🔹 How does a session work?

  1. User logs in → Backend creates a session & assigns a session ID.
  2. The session ID is stored in a cookie in the user’s browser.
  3. On every request, the session ID is sent to the server.
  4. Backend checks the session ID → If valid, the user remains logged in! 🎉

🔧 2. Install express-session Package

Before we begin, we need to install the session library in our Node.js project:

npm install express-session

This works for both CJS and ESM, so let's move on to the implementation!

🔥 3. Using Sessions in Node.js (CommonJS - CJS)

If your project still uses CommonJS (require), follow these steps:

📌 Basic Session Setup in Node.js (CJS)

Open or create a server.js file and add this code:

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

const app = express();

// Session middleware
app.use(session({
  secret: "super-secret-key", // Secret key for encrypting the session
  resave: false, // Don't save session if it hasn't changed
  saveUninitialized: true, // Save session even if empty
  cookie: { secure: false } // Set to `true` if using HTTPS
}));

app.get("/", (req, res) => {
  res.send("Welcome! Session is active! 🎉");
});

// Store data in session
app.get("/login", (req, res) => {
  req.session.user = "Oyen"; // Store user name in session
  res.send("You are logged in as Oyen! 🐱");
});

// Retrieve session data
app.get("/profile", (req, res) => {
  if (req.session.user) {
    res.send(`Hello ${req.session.user}, this is your profile! 🎉`);
  } else {
    res.send("You're not logged in! 😿");
  }
});

// Logout
app.get("/logout", (req, res) => {
  req.session.destroy(() => {
    res.send("You have logged out! See you later! 👋");
  });
});

app.listen(3000, () => {
  console.log("Server running at http://localhost:3000 🚀");
});

🔹 How does this work?

  1. Visit http://localhost:3000/login → A session is created with user "Oyen".
  2. Visit http://localhost:3000/profile → The backend remembers who you are! 🐱
  3. Visit http://localhost:3000/logout → The session is deleted, and you're anonymous again.

🚀 4. Using Sessions in Node.js (ES Module - ESM)

If you’re using ES Module (import), add "type": "module" in package.json:

{
  "type": "module"
}

📌 Session Setup in Node.js (ESM)

Create a server.mjs file and add this code:

import express from "express";
import session from "express-session";

const app = express();

// Session middleware
app.use(session({
  secret: "super-secret-key",
  resave: false,
  saveUninitialized: true,
  cookie: { secure: false }
}));

app.get("/", (req, res) => {
  res.send("Welcome! Session is active! 🎉");
});

// Store data in session
app.get("/login", (req, res) => {
  req.session.user = "Oyen";
  res.send("You are logged in as Oyen! 🐱");
});

// Retrieve session data
app.get("/profile", (req, res) => {
  if (req.session.user) {
    res.send(`Hello ${req.session.user}, this is your profile! 🎉`);
  } else {
    res.send("You're not logged in! 😿");
  }
});

// Logout
app.get("/logout", (req, res) => {
  req.session.destroy(() => {
    res.send("You have logged out! See you later! 👋");
  });
});

app.listen(3000, () => {
  console.log("Server running at http://localhost:3000 🚀");
});

🔹 Differences from CJS?

  • Uses import instead of require.
  • Requires ESM activation in package.json.

🎯 5. Full express-session Options (Make Your Backend Even Smarter! 💪)

🔥 Important session options:

Option Description
secret Secret key for encrypting the session. REQUIRED!
resave If true, session is saved even if unchanged. Usually false.
saveUninitialized If true, save session even if empty. Usually true.
cookie.secure If true, only accessible via HTTPS. Use false in localhost!
cookie.maxAge Session expiration time in milliseconds.
store Save session in a database (MongoDB, Redis, etc.).

🔹 Example: Set session to expire after 30 minutes

app.use(session({
  secret: "super-secret-key",
  resave: false,
  saveUninitialized: true,
  cookie: { maxAge: 30 * 60 * 1000 } // 30 minutes
}));

🏆 Conclusion: Your Backend Won’t Forget Users Anymore! 🎉

🎯 Sessions allow the backend to "remember" users without needing to send a token on every request.
🎯 Works with both CommonJS (CJS) and ES Module (ESM).
🎯 Don't forget to configure session security & cookies, especially in production!
🎯 Can be stored in a database (Redis, MongoDB, etc.) for scalability!

Now your backend is smarter and won’t forget users easily! 🚀

#HappyCoding! 🎉🔥

Post a Comment

0 Comments