WittCode💻

Node and Express - Cookies

By

Learn how to set and clear cookies with Express. Also learn what a cookie is and why they are needed.

Table of Contents 📖

A cookie is a small piece of data stored on the client. After a cookie is set on the client, it is sent alongside every request until it expires or gets cleared.

Cookies are used because HTTP is stateless, meaning that a server cannot tell if a request came from a client that has already made a request, or if it is a request from a new client. Cookies allow the server to identify a user (request's sender) on a website. This can be used to keep a user logged in even after leaving the webpage, collect user data, and more.

A cookie is a key value pair along with other attributes that specify things such as how long until the cookie expires, if the cookie is only valid on HTTPS, and more. For example, the following cookie has the key sid and the value 123. It also has an expiration date and is only sent over HTTPS.

sid=123; Expires=Thu, 21 Oct 2022 07:28:00 GMT; Secure;

How do Cookies Work?

Cookies usually store a session id, abbreviated as sid. This session id represents a user. When the server receives a request, it can lookup this session id in a database and bring back all the information about the user.

Image

To handle cookies with Express, we need to install a middleware called cookie-parser.

npm install cookie-parser

cookie-parser is a middleware that parses cookies attached to the request object. It is similar to the express.json() middleware but for parsing cookies instead of request payloads.

Similar to how the express.json() middleware parses a POST request payload and places it inside request.body, the cookie-parser middleware parses cookies attached to the request and places them inside request.cookies.

Lets register the cookie-parser middleware as global middleware inside our main index.js file.

const cookieParser = require('cookie-parser');
app.use(cookieParser());

To set a cookie on a client, we use the response.cookie() method. Lets set a cookie on the client when they are added to the database. This will be done inside our users.create middleware. Add the following above the response.send() method in controllers/user.js in our create method.

response.cookie('username', username);

This sets a cookie on the client with a key of "username" and a value of the username that the user entered into the form.

Accessing our /login POST Route

Lets first fill out our login form with a username and password.

Image

Checking request.cookies

Remember, cookie-parser places cookies inside request.cookies for every request. So, lets log request.cookies in a route and see what we get. For example, if we visit localhost:1234/posts/most-popular we can access the cookies like this.

router.get('/most-popular', (request, response) => {

    console.log(request.cookies);
    response.send('These are the most popular posts.');

});

Image

request.cookies will be an object that contains all the cookies we set.

Checking for Cookies with the Browser

We can also check whether the cookie was successfully set on the client using the browser. Cookies can be found in the application tab in Google Chrome. The application tab contains information on local storage, cookies, cache, etc. for a webpage. The application tab basically contains useful information on storage for a webpage. To see the cookie, right click on the browser window, click inspect, and then go to the application tab.

Image

From inspecting the application tab, we can see our cookie under cookies and then the domain name (localhost:1234). Specifically, we can see the key username and the value "my%20username" which is a URL encoded version of "my username". This is from the following Express code.

response.cookie('username', username);

What is URL Encoding?

URL encoding converts certain characters into a format that is transmissable over the internet. For example, URLs cannot contain spaces. This is why the space in "my username" was replaced with %20.

Remember, cookies are not only a key value pair, they also contain information that impacts its security, access, expiration, and more. For example, lets say we want to make it so the cookie we set on the client will only be sent along with the request on HTTPS. To do this with Express, we pass an object as a third parameter to response.cookie().

response.cookie('username', username, { secure: true });

Setting secure to true will make it so this cookie is only sent to the server on HTTPS.

Image

Lets head on over to our application tab again and look for the presence of this new cookie.

Image

Now, our cookie with the "username" key has the value WittCode. It also has the secure attribute checked, meaning this cookie will only be sent to the server over HTTPS. There are several other attributes we can set or modify for our cookie. We will be doing that later on in this series.

If we don't set the expiration/max-age property on a cookie, then the cookie will expire when the browser is closed. To demonstrate this, close the browser (not the tab) and then reopen it. The cookie we set will be gone.

To remove a cookie from the client with Express, we use the response.clearCookie() method and pass it the key of the cookie we want to remove.

Creating a Logout Route

Lets use this response.clearCookie() method inside a logout route. Create a folder called logout and place an index.js file inside it with the following contents.

const express = require('express');
const router = express.Router();

router.get('/', (request, response) => {

    response.clearCookie('username');
    response.redirect('/login');

});

module.exports = router;

undefined

Image

Register Logout Router with Express Application

Don't forget to register this router object with our Express application. Place the following inside our main index.js file.

const logout = require('./routes/logout');
app.use('/logout', logout);

Inside our profile.pug file, lets add a link that sends a GET request to /logout. Place the following inside views/profile.pug.

a(href="/logout") Logout

When our profile.pug file is rendered, it should now look like this.

Image

When we click this link, the username cookie will be cleared.

Image

Summary

But there we have it! In the next article we will talk about sessions and how to implement them with Express. If this article was helpful, please consider donating by using the link at the top of the page, sharing this article, and subscribing to my YouTube channel WittCode!

Node and Express - Cookies