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





Awesome breakdown! Makes cookies and sessions super clear.