Introduction:
Express JS is a popular and powerful web application framework for Node.js. In this tutorial, we will be discussing how to implement sessions in Express JS, which is essential for maintaining user authentication and managing state between client and server. This is the first part of a two-part series on sessions in Express JS.
What are sessions?
Sessions are a way to store and manage user data across multiple requests. When a user logs into a web application, a session is created to store the user’s data, which can then be accessed throughout the user’s visit. Sessions are typically stored on the server and identified by a unique session ID.
Why are sessions important?
Sessions are important for maintaining user authentication and managing state between client and server. By using sessions, you can keep track of users who are logged in, store user-specific data, and prevent unauthorized access to certain parts of your application.
Setting up sessions in Express JS:
To start using sessions in Express JS, you need to install the ‘express-session’ package. You can do this by running the following command in your terminal:
npm install express-session
Once the package is installed, you can require it in your Express application and use it to set up sessions. Here’s how you can do that:
const express = require('express');
const session = require('express-session');
const app = express();
app.use(session({
secret: 'your_secret_key',
resave: false,
saveUninitialized: false
}));
In the code above, we are creating a new session middleware using the express-session
package. We are passing in an object with three options: secret
, resave
, and saveUninitialized
.
secret
: This is a string that is used to sign the session cookie. It should be a random, long, and unique string to enhance security.resave
: This option determines whether the session should be saved back to the session store if it hasn’t changed during the request. Set this tofalse
to prevent unnecessary updates to the session.saveUninitialized
: This option determines whether a session should be created for a new but unmodified session. Set this tofalse
if you don’t want to save uninitialized sessions.
Accessing and updating session data:
Once you have set up sessions in your Express application, you can access and update session data using the req.session
object. Here’s an example of how you can set and get session data:
app.get('/', (req, res) => {
req.session.username = 'john.doe';
res.send(`Welcome, ${req.session.username}`);
});
app.get('/profile', (req, res) => {
const username = req.session.username;
res.send(`Profile page for ${username}`);
});
In the code above, we are setting the username
property in the session object to ‘john.doe’ when a user accesses the home route. We then retrieve the username
property from the session object and display it on the profile page.
Conclusion:
In this tutorial, we have learned how to set up sessions in Express JS using the express-session
package. We have also seen how to access and update session data in your Express application. Sessions are crucial for maintaining user authentication and managing state between client and server, making them an essential feature for web applications. In the next part of this series, we will explore more advanced topics related to sessions in Express JS.
i don't understand how server will identify who the user is. i understand when user will first visit a website, server will send a session id to client and client will send the session in each subsequent request to server. but how server will recognize who the user actually is? what the role of the user, is he authenticated or not? i will appreciate the clarification. thank you.
So in the real world development, we have to modify the session object manually to keep the sessionId to be same?
Probably the best video i've seen explaining this. Thanks a lot.
Hi, lovely video but i do get a cookies
error in production
for me without setting session.visited = true the session id is same , is that a problem?
excellent
Hey, it's me again. I hope you're not bored of me. I was using fastify instead of ExpressJS, and for some reason fastify doesn't destroy expired sessions from memory or database store. I have a GitHub issue about it. And someone said: "Express gives a new session to the user when it got expired but ExpressJS doesn't destroy them either, these plugins don't care about expired sessions." Is this true? Because if it's true, that's ridiculous, because fastify doesn't delete expired sessions, so I can access expired sessions by playing a little trick on cookies. And that's a security vulnerability. Doesn't Express also delete expired sessions?
Thank you for the answer. Appreciate it.
even with the visited set to true , its still generating new sessions for the same requests
Thank you Anson for the material you provide to all of us.
In this course Anson artificially alters the session object in the index.js, at `app.get('/', …)`, so that when he makes a request using development tools like `thunder client` or `postman`, the output of `console.log(req.sessionID)` will always be the same on any request. This tries to justify how applications sever can keep track of user for subsequent requests. Cool !
And the game is totally different on a real web browser: there, developers don't have to do anything on the session object and the sessionID value will remain the same. Am I wrong Anson ?
signedCookies.hello in products components is undefined how to resolve this.
Slides are too fast in start.. o/w HQ content❤
thank you very much
Best tutorial.
hey anson i have a qn… So for example, when u visit the ecomm web app how does the app knows whether to render an admin login page or user login page? As i know usually there is a different login page based on the user role like admin and user
Great content. Can you please tell What is the theme and the font you are using?