Managing User Authentication and Sessions
Learn how to manage user authentication and sessions in Express using TypeScript and the express-session library.
We'll cover the following...
The express-session library
Now that we have access to the username and password data from the login form,
we can set an application variable that can tell our application whether or not the user has been logged in. To do this, we will store the username in a session variable so that it is persisted between application screens. We will make use of the express-session library to handle session storage.
We can configure our application to use this library by updating our main.ts file with the following changes:
// Existing code not shownimport expressSession from 'express-session';app.use(expressSession({secret: `asdfghjkl`,resave: false,saveUninitialized: true}));app.use(`/`, Index.router);app.use(`/`, Login.router);// Existing code not shown
Here, we are importing the express-session library and then calling the
app.use function with the expressSession function in order to configure it.
The expressSession function uses a configuration object to set the secret, resave, and saveUninitialized required properties:
-
The
secretproperty, as described by theexpress-sessiondocumentation, is used to sign the session ID cookie. This means that the session cookie values will become invalid if they are modified somehow and provides an extra level of security to ...