Play by Play: NodeJS Express Session's storage configuration

Setting up sessions and using express-session in an Express application is essential for managing user state across multiple requests.

Why We Need Sessions

  1. Stateful Interactions: HTTP is a stateless protocol, meaning each request from a client to a server is independent, with no memory of previous interactions. Sessions provide a way to maintain state between these requests.

  2. User Authentication: Sessions are commonly used to maintain a user's logged-in state. When a user logs in, their session is created and stored, allowing the server to recognize the user on subsequent requests without requiring them to log in again.

  3. Personalized Experience: Sessions enable personalized user experiences by storing user-specific data (like preferences, shopping cart contents, etc.) across multiple interactions with the web application.

  4. Security: Sessions can help manage and secure user interactions by tracking login status and ensuring that sensitive operations are performed by authenticated users.

express-session is a middleware for managing sessions in an Express application. It provides several features that make session management easier and more secure:

  1. Session Management: express-session automatically handles creating, updating, and destroying sessions. This simplifies session management and ensures consistency across your application.

  2. Session Storage: By default, express-session uses an in-memory store, but it supports various other stores (like Redis, MongoDB, etc.) for better scalability and persistence. This flexibility allows you to choose a storage solution that fits your needs.

  3. Session Cookies: express-session manages session cookies for you. It sets, retrieves, and secures session cookies, ensuring that session data is correctly tied to user interactions.

  4. Configuration Options: express-session provides numerous configuration options, allowing you to customize session behavior, such as cookie settings, session lifetime, and security options (like secure cookies and HTTP-only cookies).

While I was working on a friend's project, I came across the following warning: connect.session() MemoryStore is not designed for a production environment., as it will leak memory, and will not scale past a single process. If you are seeing this warning, it indicates that you are using the default "MemoryStore" for session storage in your express application. "MemoryStore" is not suitable for production because it stores session data in memory.

The error message is corresponding to the follow code:

app.use(
  session({
    secret: process.env.SESSION_SECRET,
    resave: false,
    saveUninitialized: false,
  })
);

If you're already using mongodb, we can use connect-mongo package to configure our session storage.

 npm install connect-mongo
import session from 'express-session';
import MongoStore from 'connect-mongo';

app.use(session({
  store: MongoStore.create({
    mongoUrl: 'mongodb://localhost:27017/your-database-name'
  }),
  secret: 'your-secret-key',
  resave: false,
  saveUninitialized: false,
  cookie: { secure: true } // Set to true if using HTTPS
}));

Now, go ahead and check your application logs to ensure this error message is gone.

0
Subscribe to my newsletter

Read articles from Hooman Pegahmehr directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Hooman Pegahmehr
Hooman Pegahmehr

Hooman Pegahmehr is a performance-driven, analytical, and strategic Technology Management Professional, employing information technology best practices to manage software and web development lifecycle in alignment with client requirements. He builds high-quality, scalable, and reliable software, systems, and architecture while ensuring secure technology service delivery as well as transcending barriers between technology, creativity, and business, aligning each to capture the highest potential of organization resources and technology investments. He offers 8+ years of transferable experience in creating scalable web applications and platforms using JavaScript software stack, including MongoDB, Express, React, and Node, coupled with a focus on back-end development, data wrangling, API design, security, and testing. He utilizes a visionary perspective and innovative mindset to collect and translate technical requirements into functionalities within the application while writing codes and producing production-ready systems for thousands of users. He designs, develops, and maintains fully functioning platforms using modern web-based technologies, including MERN Stack (MongoDB, Express, React, Node). As a dynamic and process-focused IT professional, Hooman leverages cutting-edge technologies to cultivate differentiated solutions and achieve competitive advantages while supporting new systems development lifecycle. He excels in creating in-house solutions, replacing and modernizing legacy systems, and eliminating outsourcing costs. He exhibits verifiable success in building highly responsive full-stack applications and incident management systems using advanced analytical dashboards while translating complex concepts in a simplified manner. Through dedication towards promoting a culture of collaboration, Hooman empowers and motivates diverse personnel to achieve technology-focused business objectives while administering coaching, training, and development initiatives to elevate personnel performance and achieve team synergy. He earned a winning reputation for transforming, revitalizing, streamlining, and optimizing multiple programs and web-based applications to drive consistent communications across cross-functional organization-wide departments. He manages multiple projects from concept to execution, utilizing prioritization and time management capabilities to complete deliverables on time, under budget, and in alignment with requirements.