How to handle cookie information in Express.js

Introduces how to handle cookie information in Express.js. The code is also posted on Git Hub, so please refer to it.

overview

In Express.js, cookie handling is done inside a middleware function. A request object and a response object are passed as arguments to the middleware function. Use these objects to retrieve cookie-related data, generate responses, and so on.

Here, I will explain how to handle cookies with Express.js using the following versions.

Express.js v4.17.1
nodejs v19.7.0
cookie-parser v1.4.5

In addition, all the code created this time is posted on GitHub.

In this article, we use the cookie-parser module, so enter the following command to install cookie-parser.

npm install cookie-parser

To get information about cookies, use the cookie-parser middleware and request object. Cookie-parser parses cookies included in requests from clients. Parsed cookies are stored in the cookies property of the request object.

The sample code below is an example for understanding cookies in Express.js. Receive a GET request, access the cookies in the request, and return a response containing those values.

cookie.js

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

app. use(cookieParser());

app.get('/', (req, res) => {
  // get cookie
  const cookies = req.cookies;

  const response = {
    cookies: cookies
  };

  res.json(response);
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

Commentary

  • Create an instance of Express and cookie-parser
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();

Import the Express module and the cookie-parser module and create an instance of it.

  • Using cookie-parser middleware functions
app. use(cookieParser());

Use the cookie-parser middleware function. This will automatically parse any cookies included in the request and store them in req.cookies.

  • Defining route handlers
app.get('/', (req, res) => {
  // get cookie
  const cookies = req.cookies;

  const response = {
    cookies: cookies
  };

  res.json(response);
});

Handles GET requests to the root (’/’). When a request comes, get the cookie included in the request and return an object containing it in JSON format as a response.

  • Start server
app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

Start the server with an instance of Express listening on port 3000. When the server starts, print the message “Server is running on port 3000” to the console.

test

curl -b "key=value" http://localhost:3000

This command will send a request containing a cookie with key “key” and value “value”

summary

This article introduced how to handle cookies using Express.js. By using cookies, it is possible to manage the user’s state and save the user’s settings.