Learn

Now that the middleware will create sessions, let’s configure how the middleware saves session data.

Sessions are typically stored in three different ways:

  • In memory (this is the default storage)
  • In a database like MongoDB or MySQL
  • A memory cache like Redis or Memcached

Whenever a user makes a request from the same client with a valid session identifier, the server retrieves the valid session information.

express-session provides an in-memory store called, MemoryStore(). If no other store is specified, then this is set as the default storage. Let’s explore how we would add this to the middleware.

We can instantiate a new store like so:

const store = new session.MemoryStore();

Once instantiated, we can add it in the configuration of our session:

app.use( session({ secret: "secret-key", resave: false, saveUninitialized: false, store, }) );

Note: Storing in-memory sessions is something that should be done only during development, NOT during production due to security risks.

Instructions

1.

The session middleware has been created but it’s missing a store. Create a new instance of MemoryStore and store it in a variable called store.

Type node app.js into the Terminal to start the node app.

Press the Check Work button to check your work for each checkpoint.

2.

Add store into your session middleware.

Take this course for free

By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.
Already have an account?