How to Manage Sessions in Node.js and Express

After someone signs in, an Express app needs a way to associate later requests with that browser’s session. express-session links a server-side record to the browser with a cookie that carries a session ID.

This article shows how to configure express-session and manage session data through the sign-in and logout flow.

TL;DR

Use express-session to associate a browser’s session ID cookie with data stored on the server, and mount its middleware before routes that read or change that data.

  • Use an unpredictable secret from an environment variable, not a literal committed to source.
  • Set resave and saveUninitialized explicitly, and configure cookies for HTTPS in deployment.
  • Replace the default MemoryStore before production, especially across restarts or multiple app processes.

What is an Express session?

An Express session is a server-side record associated with a browser through a session ID. express-session places that ID in a signed cookie, and the configured store uses it to find the record on a later request.

PartWhere it livesWhat it does
Session ID cookieBrowserCarries the signed identifier, not the application’s session values.
req.sessionExpress requestGives route handlers access to the current session data.
Session storeServer-side backendLooks up and saves values associated with the identifier.

A session suits a preference that belongs to one browser because that browser returns its own cookie on later requests. Keep session values serializable, such as an ID or preference name, so the store can persist them between requests. A database connection is a runtime resource, not session data.

How to manage a session in Express step by step

The following procedure installs the middleware and configures options before route handlers use them.

Step 1: Install Express and express-session

Run the install command in an existing Node.js project. Express provides routing, while express-session adds the session API.

npm install express express-session

Current express-session versions read and write the cookie themselves, so this example does not need cookie-parser for session handling.

The name option changes the session cookie name. Give each app on a shared host its own name so one app does not mistake another app’s cookie for its own.

Step 2: Configure session middleware before routes

Mount session middleware after proxy setup and before routes that read req.session, because Express processes middleware in registration order.

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

const app = express();
const secret = process.env.SESSION_SECRET;

if (!secret) {
  throw new Error('Set SESSION_SECRET before starting the app');
}

if (app.get('env') === 'production') {
  app.set('trust proxy', 1);
}

app.use(session({
  name: 'app.sid',
  secret,
  resave: false,
  saveUninitialized: false,
  cookie: {
    httpOnly: true,
    secure: app.get('env') === 'production',
    sameSite: 'lax',
    maxAge: 30 * 60 * 1000
  }
}));
SettingEffectChoice in this example
httpOnlyPrevents ordinary browser JavaScript from reading the cookie.Enabled to limit direct script access.
secureSends the cookie only over HTTPS.Enabled in production, where the app must receive HTTPS requests or trust its configured proxy.
sameSiteControls when browsers attach the cookie to cross-site requests.Lax for the common same-site navigation flow.
maxAgeSets the browser cookie lifetime in milliseconds.Configured separately from the store’s own expiry.

Set SESSION_SECRET in deployment configuration. It must be unpredictable, absent from source control and logs, and available before the app starts.

With resave false, an unchanged session is not written again when the store can refresh its expiry through touch. Check the store documentation because a backend without touch may handle expiry differently.

Set saveUninitialized to false when routes should not create empty sessions. Middleware then waits until a handler changes a new session before storing it or issuing the cookie.

Secret rotation can keep existing cookies valid while apps roll out the new key. express-session accepts an array with the signing secret first and previous verification secrets after it, so remove an old key only after that overlap ends.

The production branch sets trust proxy to one hop, a choice that fits only when exactly one trusted reverse proxy sits in front of Express.

httpOnly protects the cookie from direct JavaScript reads. It does not stop injected code from sending authenticated requests, so keep output escaping and request protections in place.

Step 3: Store and read a value across requests

Write and read a req.session field in separate handlers so the same browser can request the second route with its cookie.

app.get('/visit', (req, res) => {
  req.session.visits = (req.session.visits || 0) + 1;
  res.send(`Visit ${req.session.visits} recorded`);
});

app.get('/count', (req, res) => {
  if (typeof req.session.visits !== 'number') {
    return res.status(404).send('No visit has been recorded');
  }
  res.send(`Visits: ${req.session.visits}`);
});

Each /visit request increments the numeric visits field. Refreshing /count only reads the stored value, so it does not add another visit.

When the field is absent, /count returns 404 instead of interpolating undefined into a greeting. That response distinguishes a new or expired session from a saved count of zero.

To see both paths, request /count first, then request /visit and /count. The first response uses the missing-value path, while the later response reads the saved count.

If a route redirects immediately after changing the session, call save before sending the response. Its callback waits for the store write so the next request does not race it.

req.session.notice = 'Profile updated';
req.session.save((err) => {
  if (err) return next(err);
  res.redirect('/profile');
});

Step 4: Regenerate the session after authentication

Regenerate only after credentials pass and before assigning the user’s ID. That replaces any identifier issued before login, which helps prevent session fixation.

function finishLogin(req, res, next, user) {
  req.session.regenerate((err) => {
    if (err) return next(err);
    req.session.userId = user.id;
    req.session.save((saveError) => {
      if (saveError) return next(saveError);
      res.redirect('/account');
    });
  });
}

The regenerated identifier receives user.id only after the callback succeeds. The handler forwards errors rather than writing an authenticated ID after a failed rotation.

Step 5: Destroy the session when the user logs out

Forward a destroy error through next so Express can handle a failed logout. The browser should receive success only after the store confirms removal.

app.post('/logout', (req, res, next) => {
  req.session.destroy((err) => {
    if (err) return next(err);
    res.clearCookie('app.sid', { path: '/' });
    res.send('Logged out');
  });
});

Use the configured name and path in res.clearCookie so the browser removes the session cookie.

Logout removes the current session only. Other browsers remain signed in unless the application revokes their records after an account recovery or security event.

Logout may also involve separate access tokens or WebSocket connections. Session middleware does not revoke credentials managed by another system or close an independently authenticated connection.

Session cookies and storage issues to check

When a session appears to disappear, check whether the browser returned its cookie and whether the server can reach the same session store. Cookie transport, process restarts and middleware ordering account for common failures.

SymptomLikely causeCheck or fix
Session is empty on the next routeMiddleware is mounted after the route or browser omitted the cookieMount app.use(session(…)) before routes. Inspect the cookie name, path and security attributes.
Cookie is absent over HTTPS behind a proxyExpress does not know the original request used HTTPSSet trust proxy to match the actual proxy topology before enabling secure cookies.
Sessions disappear after restartDefault MemoryStore keeps state in process memoryUse a persistent compatible store and check its expiry configuration.
Users lose sessions across app instancesEach process has a separate in-memory store or inconsistent secretUse a shared store and the same secret configuration across instances.
New requests do not get a cookiesaveUninitialized is false and no session data was changedChange the session only when the application has a reason to persist it.
Cookie stops working after a deploymentThe signing secret changedKeep the same secret across instances or rotate with overlapping verification secrets.
Session ends earlier than expectedCookie lifetime and store expiry do not matchAlign cookie maxAge with the backend store’s TTL or expiry policy.
Cross-site request omits the cookieBrowser credentials or cookie policy blocks itUse an exact allowed origin and compatible credentials and SameSite settings over HTTPS.

The default MemoryStore is process-local, so a restart drops its records and separate workers cannot share them. A compatible persistent store keeps records outside app memory. Check that backend’s connection, TTL and touch behavior before relying on expiry.

For cross-origin requests that need a cookie, the browser client must include credentials and the server’s CORS policy must allow the exact frontend origin.

CORS determines which scripts can read a response. Add CSRF validation to state-changing routes because CORS is not authorization.

Use browser developer tools to find where a session disappears. Inspect the response for Set-Cookie after a route changes the session, then inspect the next request for Cookie. A missing header can mean no session data was written or the browser rejected the cookie attributes.

For local testing, run the app in development mode so this configuration does not mark the cookie Secure. Keep the production setting enabled when checking the deployed HTTPS flow.

SameSite=None is needed for some cross-site designs, and browsers require Secure with that setting. Test the actual frontend and API domains because local ports can behave differently from the deployed HTTPS setup.

Check the store adapter first. Confirm that it can connect and find the expected session record in the backend this app selected.

Conclusion

Choose the session store to match how the app runs, then test the login, redirect and logout flow with the deployed cookie settings. The Express middleware documentation and each store’s setup guide define the options to check.

For option details and compatible stores, use the Express session middleware documentation and the expressjs/session README. For broader setup, see CodeForGeek’s Express and Node.js tutorial.

CodeForGeek’s overview of Node.js Connect and Express gives broader middleware context for readers adding other request handlers.

FAQ

These answers cover the session behavior and configuration choices that commonly affect Express applications.

Where is express-session data stored?

The session data is stored on the server in the configured session store. The browser cookie holds the signed session identifier used to find that data.

Can I use MemoryStore in production?

No. The default MemoryStore is intended for development and debugging. Use a compatible persistent store for a production deployment.

Does express-session verify passwords?

No. The login handler must verify credentials before it writes a user ID to the session. Protected routes still check whether that user may access a resource.

When should I call req.session.save()?

Call it before a redirect that depends on the new session value. Send the redirect from its callback after the store write completes, and pass callback errors to Express.

Why does a session disappear after a restart?

The default MemoryStore keeps records in one process, so restarting clears them. Use a compatible persistent store for deployed apps, and share it across app instances that serve the same users.

What do resave and saveUninitialized control?

resave controls whether unchanged sessions are written again. saveUninitialized controls whether new, untouched sessions are stored. Choose these settings with the selected store’s touch behavior and the app’s anonymous-session needs in mind.

Why does Express need trust proxy for secure cookies?

When TLS ends at a reverse proxy, Express must know whether the original request used HTTPS. Set trust proxy to match only the trusted hops in front of the app so the secure-cookie check uses the real deployment path.

Aditya Gupta
Aditya Gupta

Aditya Gupta is a founding member and editor at CodeForGeek. He first found his way into tech by reading articles, and now writes approachable guides to Node.js security, authentication, AI tools, coding agents, and web scraping.

Articles: 529