Now that we have express-session
installed, we can configure the middleware and implement it in app.js
. Let’s explore a few of the options we can configure:
secret
: Thesecret
property is a key used for signing and/or encrypting cookies in order to protect our session ID.
The next two properties determine how often the session object will be saved.
resave
: Setting this option totrue
will force a session to be saved back to the session data store, even when no data was modified. Typically, this option should befalse
, but also depends on your session storage strategy.saveUninitialized
: This property is a boolean value. If it’s set totrue
, the server will store every new session, even if there are no changes to the session object. This might be useful if we want to keep track of recurring visits from the same browser, but overall, setting this property tofalse
allows us to save memory space.
Once all options are configured we configure the properties for express-session
like so:
app.use( session({ secret: "D53gxl41G", resave: false, saveUninitialized: false, }) );
Note that we are using a hardcoded string of characters for the secret
property. Usually, this random string should be stored securely in an environment variable, not in the code.
The resave
and saveUninitialized
properties are set to false in order to avoid saving or storing unmodified sessions. With those options put in place, we have the most basic setup of our middleware!
In the next exercise, we will specify where the session data should be stored.
Instructions
Add a session middleware in app.js
.
Set the secret
to a random string. We don’t want to save the session unless it’s modified, so set the other properties to the appropriate values.
Type node app.js
into the Terminal to start the node app.
Press Check Work button to check your work.