JavaScript

Express.js Cookies Tutorial

Hello in this tutorial, we will understand Cookies and implement them in an Express.js application.

1. Introduction

Cookies are a piece of any information sent from the server and are stored in the client’s browser. This information helps to track the client’s action and the browser sent it back to the server every time a client visits the website to recognize the client and its actions. Cookies in an application are used to manage sessions, client personalization, and tracking.

1.1 Setting up Node.js

To set up Node.js on windows you will need to download the installer from this link. Click on the installer (also include the NPM package manager) for your platform and run the installer to start with the Node.js setup wizard. Follow the wizard steps and click on Finish when it is done. If everything goes well you can navigate to the command prompt to verify if the installation was successful as shown in Fig. 1.

express.js cookies - npm installation
Fig. 1: Verifying node and npm installation

2. Express.js Cookies Tutorial

To set up the application, we will need to navigate to a path where our project will reside. For programming stuff, I am using Visual Studio Code as my preferred IDE. You’re free to choose the IDE of your choice.

2.1 Setting up dependencies

Navigate to the project directory and run npm init -y to create a package.json file. This file holds the metadata relevant to the project and is used for managing the project dependencies, script, version, etc. Add the following code to the file wherein we will specify the required dependencies.

package.json

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
{
  "name": "expressjs-cookies",
  "version": "1.0.0",
  "description": "Express js and cookies tutorial",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "expressjs"
  ],
  "author": "daniel atlas",
  "license": "MIT",
  "dependencies": {
    "cookie-parser": "^1.4.5",
    "express": "^4.17.1"
  },
  "devDependencies": {
    "nodemon": "^2.0.7"
  }
}

To download the dependencies navigate to the directory path containing the file and use the npm install command. If everything goes well the dependencies will be loaded inside the node_modules folder and you are good to go with the further steps.

2.2 Creating the controller file

Create a controller file in the routes folder. This file will expose endpoints that will be responsible to entertain the request from the client.

api.js

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
const express = require('express');
const router = express.Router();
 
// http get
 
router.get('/', (req, res) => {
    res.status(200).json({info: 'Application is working fine'});
});
 
// http post
 
router.post('/set', (req, res) => {
    console.log('Setting cookie');
 
    let obj = {
        id: req.query.id,
        full_name: req.query.full_name
    };
 
    res.status(201)
        .cookie('emp', obj, {maxAge: 360000})   //The cookie will expire after 360000 ms from the time it is set.
        .json({info: 'Cookie set successfully'});
});
 
// http get
 
router.get('/get', (req, res) => {
    console.log('Returning cookie');
 
    res.status(200).json({info: req.cookies});
});
 
// routes
module.exports = router;

2.3 Creating an index file

Create an index file that will act as an entry point for our server. The file will contain the code to define the routes to the application endpoints.

index.js

01
02
03
04
05
06
07
08
09
10
11
12
13
const express = require('express');
const cookieParser = require('cookie-parser');
 
const app = express();
 
app.use(cookieParser())
//Application routes
app.use('/', require('./routes/api'));
 
const PORT = process.env.port || 4001;
app.listen(PORT, () => {
    console.log(`Server started on port ${PORT}`);
});

3. Run the Application

To run the application navigate to the project directory and enter the following command as shown in Fig. 4. If everything goes well the application will be started successfully on port number 4001.

express.js cookies - starting the app
Fig. 2: Starting the application

4. Project Demo

When the application is started, open the Postman tool to hit the application endpoints. You are free to choose any tool of your choice.

Application endpoints

1
2
3
4
5
6
7
8
// index
HTTP GET url - http://localhost:4001/
 
// set the cookie
 
// get the cookie

Similarly, you can create other endpoints. That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!

5. Summary

In this tutorial, we learned –

  • Introduction to Cookies
  • Steps to setup Node.js
  • Sample programming stuff

You can download the source code of this tutorial from the Downloads section.

6. Download the Project

This was a programming tutorial to manage cookies in an express.js application.

Download
You can download the full source code of this example here: Express.js Cookies Tutorial

Yatin Batra

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button