How Fastify handles cookie information

overview

Fastify handles cookies in hooks and route handlers. These are used to retrieve data related to cookies, generate responses, and so on.

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

Fastify v3.20.2
nodejs v19.7.0
fastify-cookie v5.3.0

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

In this article, we will use the fastify-cookie plugin, so please enter the following command to install fastify-cookie.

npm install fastify-cookie

Use the fastify-cookie plugin and the request object to get information about cookies. fastify-cookie parses cookies 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 Fastify. Receive a GET request, access the cookies in the request, and return a response containing those values.

cookie.js

const fastify = require('fastify')({ logger: true });
const fastifyCookie = require('fastify-cookie');

fastify.register(fastifyCookie);

fastify.get('/', (request, reply) => {
  // get cookie
  const cookies = request.cookies;

  const response = {
    cookies: cookies
  };

  reply.send(response);
});

fastify.listen(3000, (err, address) => {
  if (err) {
    fastify.log.error(err)
    process.exit(1)
  }
  fastify.log.info(`Server is running on ${address}`)
});

Commentary

  • Create instances of Fastify and fastify-cookie
const fastify = require('fastify')({ logger: true });
const fastifyCookie = require('fastify-cookie');

Import the fastify and fastify-cookie modules and create an instance of them.

  • Using fastify-cookie middleware functions
fastify.register(fastifyCookie);

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

  • Defining route handlers
fastify.get('/', (request, reply) => {
  // get cookie
  const cookies = request.cookies;

  const response = {
    cookies: cookies
  };

  reply.send(response);
});

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

  • Start server
fastify.listen(3000, (err, address) => {
  if (err) {
    fastify.log.error(err)
    process.exit(1)
  }
  fastify.log.info(`Server is running on ${address}`)
});

Start the server with an instance of Fastify listening on port 3000. When the server starts, print the message “Server is running on ${address}” 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 explains how to handle cookies using Fastify

introduced. By using cookies, it is possible to manage the user’s state and save the user’s settings. Fastify is a highly performant web framework and the fastify-cookie plugin makes handling cookies easy.