How Fastify Handles Session Information

overview

Fastify handles session information in middleware functions. A request object and a reply object are passed as arguments to the middleware function. Use these objects to retrieve session-related data, generate responses, and so on.

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

Fastify v4.0.0
Node v20.0.0
@fastify/session v10.4.0
@fastify/cookie v8.3.0

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

In this article, we use the @fastify/session module, so please enter the following command to install @fastify/session.

npm install fastify @fastify/session @fastify/cookie @fastify/formbody @fastify/view ejs

How to get session information

Use the @fastify/session middleware and request object to get information about the session. @fastify/session parses session information included in requests from clients. The parsed session is stored in the session property of the request object.

The sample code below is an example for understanding sessions in Fastify. Receive a GET request, access the session contained in the request, and return a response containing those values.

session.js

const fastify = require("fastify")({ logger: true });
const session = require("@fastify/session");
const cookie = require("@fastify/cookie");
const formbody = require("@fastify/formbody");
const view = require("@fastify/view");
const ejs = require("ejs");

fastify.register(cookie);
fastify.register(session, {
  secret: "a secret with minimum length of 32 characters",
  cookies: {
    secure: false,
  },
  saveUninitialized: false,
});
fastify.register(formbody);

fastify.register(view, {
  engine: {
    ejs: ejs,
  },
});
fastify.get("/", (req, reply) => {
  reply.view("/views/index.ejs");
});

fastify.get("/dashboard", (req, reply) => {
  if (req.session.user) {
    reply.view("/views/dashboard.ejs", { username: req.session.user });
  } else {
    reply.redirect("/");
  }
});

fastify.post("/login", (req, reply) => {
  const { username, password } = req.body;

  // Validate username and password here (omitted)
  req.session.user = username;

  reply.redirect("/dashboard");
});

fastify.listen({ port: 3000 }, (err, address) => {
  if (err) throw err;
  fastify.log.info(`server listening on ${address}`);
});


Commentary

This code shows a server-side implementation of a web application using the Fastify framework. The main parts are explained in bullet points below.

  • Import required modules
const fastify = require("fastify")({ logger: true });
const session = require("@fastify/session");
const cookie = require("@fastify/cookie");
const formbody = require("@fastify/formbody");
const view = require("@fastify/view");
const ejs = require("ejs");

Here we are importing the Fastify framework, some Fastify plugins (cookie management, session management, form data parsing, view rendering) and the template engine EJS.

  • Registration of Fastify plugins
fastify.register(cookie);
fastify.register(session, {
  secret: "a secret with minimum length of 32 characters",
  cookies: {
    secure: false,
  },
  saveUninitialized: false,
});
fastify.register(formbody);
fastify.register(view, {
  engine: {
    ejs: ejs,
  },
});

I am registering each plugin in my Fastify instance. This enables features such as sessions, cookies, form data parsing, EJS views, etc.

  • Defining route handlers
fastify.get("/", (req, reply) => {
  reply.view("/views/index.ejs");
});

fastify.get("/dashboard", (req, reply) => {
  if (req.session.user) {
    reply.view("/views/dashboard.ejs", { username: req.session.user });
  } else {
    reply.redirect("/");
  }
});

fastify.post("/login", (req, reply) => {
  const { username, password } = req.body;
  // Validate username and password here (omitted)
  req.session.user = username;
  reply.redirect("/dashboard");
});

fastify.get and fastify.post define routes that handle HTTP GET and POST requests respectively. Each route has a function (handler) that is called when a request comes in on a particular path.

  • Start server
fastify.listen({ port: 3000 }, (err, address) => {
  if (err) throw err;
  fastify.log.info(`server listening on ${address}`);
});

Use fastify.listen to start the server on a specific port (3000 in this case). When the server starts, it prints address information to the log.

summary

In this article, we showed you how to handle session information using Fastify. Specifically, it showed how to use the @fastify/session middleware to retrieve the session information included in the request and return it as a response. Session information plays a very important role in web applications, so it’s important to understand its handling. I hope this article helps you understand it.