After implementing the Authentication mechanism in the part 3, we are now going to learn another interesting thing : Cookies and Sessions.
Cookies and sessions play a crucial role in the authentication and authorization process.
Most familiar scenarios with behind the scene cookies are:
❖ Keeping you logged in, even when the same website is opened in different tabs.
❖ Ensuring you don’t have to log in every time when you visit the website.
❖ Remembering what items the you added to the cart.
❖ Recommending related posts, videos, or items based on your activity.
❖ You don't have to toggle the theme(dark mode) for each pages.
Most of us have experienced it. These are just a few of the jobs cookies handle. Let’s explore them in more detail.
📌 What are cookies?
Cookies are small pieces of data that a website stores in the user's browser. They are also called HTTP cookies, web cookies, or browser cookies. Cookies help websites remember information about the user’s activity, preferences, or session.
There are different types of cookies based on their usage:
- Tracking Cookies [Track user activity to provide personalized recommendations based on browsing behavior.]
- Session Cookies [Temporary cookies that are deleted when the browser is closed, used to keep users logged in during a session.]
- Persistent Cookies [Stored on the browser for a longer time, can remember login info or user preferences across visits.] etc.
📌 How Cookies work?
⤷ Server sends a cookie to the browser in http response header (Set-Cookie).
⤷ Browser stores the cookie.
⤷ For every subsequent request, browser sends it back to the server in request header.
⤷ Server reads the cookie and performs the logic defined.
📌 Need for Cookies in Authentication and Authorization :
There are many types of cookies, but in the authentication and authorization process, we use them primarily to remember users and keep them logged in as they navigate across different pages of a website.
Without cookies, users would have to log in every time they visit a page or refresh the website, which can be frustrating. This happens because the server does not inherently know who the user is. So, it renders the login form each time authentication is required.
To provide a smooth and personalized browsing experience, the server needs a way to “remember” the user. Cookies serve this purpose by storing user specific information and sending it back to the server with every request, allowing the server to identify and authorize the user seamlessly.
Let’s see how we can create cookies in an Express.js application.
📌 Creating Cookies in Express.js : 🍪
In Express, we can create a cookie like this:
app.get('/set-cookie', (req, res) => {
res.cookie('username', 'shree'); //creates and sends cookie.
});
res.cookie(...) is a method in Express.js used to create and store cookies.
It can take up to three parameters: res.cookie(name, value, options).
So, while creating a cookie, we always send the cookie name and its value, and optionally some options (like expiry time, security flags, etc.).
📌 What the res.cookie(...) doing under the hood?
⤷ The server defines a cookie named "username" with the value "shree".
⤷ This cookie information is sent to the browser in the HTTP response header to be stored locally.
⤷ Each time the user navigates to a new page, the browser automatically attaches the cookie in the HTTP request header.
⤷ The server reads and validates it before responding again with a new HTTP response.
But there’s a small challenge...
When the browser sends cookies back, the server receives them as raw string data like this:
Cookie: username=shree
However, our Express server can’t directly read these Strings, it prefers data in JavaScript object format.
We need a stream which can parse the cookies header data. So, we use cookie-parser a npm package to parse the cookies header.
You can install it like this :
npm i cookie-parser
Use it like this :
app.use(cookieParser())
📌 What this cookie-parser do?
⤷ Looks for cookies wrapped in the HTTP headers
⤷ Parses them into a JavaScript object format
⤷ Makes them accessible via req.cookies in Express
📌 Signed Cookies
Cookies defined in the normal way (like we did before) are easily prone to tampering, since they are sent as plain text in the browser.
To secure them, we add another option: the signed parameter (while defining cookies), along with a secret key, like this:
app.use(cookieParser("secretKey")); // add secret key
res.cookie("username", "shree", { signed: true }); // while creating cookie
These Cookies now called Signed Cookies.
📌 How do Signed Cookies work?
⤷ When you set { signed: true }, Express uses the secret key you provided to cryptographically sign the cookie value.
⤷ If anyone tampers with the cookie, the signature won’t match, and Express immediately detects it.
In this way, signed cookies protect cookie data from tampering.
📌 Stateless and Stateful protocols
The difference between stateless and stateful protocols lies in their ability to remember browser data (like headers or sessions).
Stateful protocols: Remember data across multiple page navigations.
Example: FTP (File Transfer Protocol)Stateless protocols: Do not store or remember any data between requests.
Example: HTTP (HyperText Transfer Protocol)
What is the reason we are discussing about it?
By default, our Express server communicates with browsers using the HTTP protocol, which is stateless.
This means every time a user navigates to a new page, the server forgets who the user is unless we add a mechanism to “remember” them.
Our goal is to keep users logged in even after page refreshes or navigation.
That’s where sessions come in.
📌 What are sessions?
Sessions allow the server to store user-specific data temporarily, making HTTP stateful.
When we use sessions in Express, the server:
⤷ Creates a unique session ID for each user
⤷ Stores session data on the server-side (in memory or a database)
⤷ Sends that session ID to the client in a cookie
⤷ On future requests, the browser automatically sends that session ID cookie back
⤷ The server then looks up the stored session data using that ID
This is how users stay logged in even across multiple tabs or page refreshes.
📌 Cookies and Sessions Integration :
We can enable sessions in Express like this:
app.use(session({ secret: "secretkey" }));
Usage :
req.session; // to access the session
req.session.username = "shree"; // to attach data
📌 What does the express-session middleware do?
⤷ Creates a unique session ID
⤷ Stores session data on the server
⤷ Sends that session ID to the client in a cookie
⤷ Automatically validates the session on each request
💡 Since
express-sessionalready handles cookie parsing internally, we no longer need thecookie-parsermiddleware.
We have covered all the topics about cookies and sessions that are essential to understand and implement Authorization workflow.
Now let's move to the last part : Auth series #5: Authorization Implementation
Top comments (10)
I'm so glad I read this article, you explained everything so well! 👏🏻🥰 I've just learned Express and was working on implementing cookie sessions.
Reading your post confirmed what I've learned and help me understand it even better! There are only a few people who explain things patiently and in a way everyone can understand and you're one of them!🤗 Happy coding!
Thank you so much 😊.
That honestly made my day 😄.
Express sessions and cookies were the headache topics for me when I started learning authentication and authorization. It actually took me a whole week just to understand why we even need them!
But once it clicked, everything made sense.
Happy coding to you too! Keep going 🚀
Thank you! 🤗
I believe you! 🙃🤗 That’s what happens when you truly want to understand the logic behind what you’re learning, you dive a bit deeper into the details, answer your own questions and clear up any confusion about the topic.
The good part is that you’ve really understood how it works and learned it logically, so you won’t need to go back to that topic again in the future.🤗🥰
Keep coding!👌🏻
Thank you! 🙌
You are right.😀
Clearing all behind the scenes doubts help a lot. Even debugging errors become easier. Because you know what the thing is and why it's causing error. It speed up the process.
That's why backend development feels more interesting no matter how many times we mess up with it.
What about you?
Which one you enjoy the most backend or frontend?
Exactly!🤗
Once you know what your code does and understand the logic behind it, it becomes a lot easier to find and fix bugs.
To be honest, I was a bit afraid of backend development at first 🙃😀. I kept thinking about servers, security, cookies, data encryption…and all of this stuff, I knew it would be more challenging and intersting than frontend. 🤗🥰
But at the same time, I was really curious to understand what happens behind the logic, so in the end, curiosity won over fear.🤗
Things might seem a bit complicated at first, but everything new feels hard until you actually start learning it.
So I can say that, until recently, I used to prefer frontend because I love details, accessibility, and making things look professional as possible, but now I’m starting to appreciate the backend too. It’s more logical, a bit more challenging, but also really satisfying once you understand how everything connects.
I’m really curious to see what I’ll learn next in this area.🤗
Thank you for your kindness.
I loved your thoughts🤩.
I was there too...Backend development felt scary at first when i started learning it. Unlike frontend we can't see anything happening visually. So it more feels like mysterious and our mind refuses to understand the behind the scenes workflow. But once you get comfortable with it, every line of code make sense.
Personally I'm more into backend development because i like to solve and uncover those mysterious things.😄
Finally I found someone who match my vibe and energy 😄. Nice to talk with you😊
That’s great to hear!🥰 I’m enjoying our conversation as well.🤗
Keep sharing what you’ve learned here, it really helps not only to recap your own work but also beginners who are just starting out! Wishing you success in everything you do! See you around Shreelaxmi Hegde! 🤗🥰
Thank you! Theodora Cristea😊
Awesome breakdown! Makes cookies and sessions super clear.
Thanks a lot 😄
I tried to simplify those parts since they confused me too when I first learned them.