How to create login functionality with Fastify

overview

Fastify implements the login functionality within a middleware function. A request object and a reply object are passed as arguments to the middleware function. These objects are used for login processing, response generation, and so on.

Here, we will explain how to implement login functionality in Fastify using the following versions:

Fastify v3.22.1
nodejs v19.7.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 create backend for login functionality

Use the fastify-session middleware and request object to implement the login process. fastify-session parses session information included in client requests. After a successful login, store the session in the request object’s session property.

The sample code below is an example to understand the login function in Fastify. Receives a POST request, processes the user’s login, and returns a response containing the result.

login.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

Below is a detailed explanation of the code.

  • Load the required modules.
const fastify = require('fastify')({ logger: true })
const session = require('fastify-session');
const cookie = require('fastify-cookie');
const path = require("path");
const pointOfView = require('point-of-view');
const ejs = require('ejs');

These modules provide the basic functionality required for web application development on Fastify.

  • Register the Fastify plugin.
fastify.register(cookie)
fastify.register(session, {
  secret: 'a secret with minimum length of 32 characters',
  cookies: {
    secure: false,
  },
  saveUninitialized: false,
})
fastify.register(pointOfView, {
  engine: {
    ejs: ejs
  }
})

These plugins manage cookies, session management, and view engine (EJS) settings.

  • Handle GET requests to the root path ("/").
fastify.get('/', (req, reply) => {
  reply.view('/views/index.ejs');
})

This will render the “index.ejs” template when a user visits the root of your website.

  • Handle GET requests to the dashboard.
fastify.get('/dashboard', (req, reply) => {
  if (req.session.user) {
    reply.view('/views/dashboard.ejs', { username: req.session.user });
  } else {
    reply.redirect('/');
  }
})

This route is only accessible to logged in users. If the user is logged in, the “dashboard.ejs” template will be rendered. If the user is not logged in, root will redirect to the root path.

  • Handle POST requests to login.
fastify.post('/login', (req, reply) => {
  const { username, password } = req.body;

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

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

This route receives the user’s login information and validates that information. If the validation is successful, save the user information in the session and redirect the user to the dashboard.

  • Start Fastify servers.
fastify.listen(3000, (err, address) => {
  if (err) throw err
  fastify.log.info(`server listening 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 port 3000” to the console.

How to create a frontend for the login functionality

Add the following code to “views/index.ejs” to create the login form.

views/index.ejs

<!DOCTYPE html>
<html>
  <head>
    <title>Login Page</title>
  </head>
  <body>
    <h1>Login</h1>
    <form action="/login" method="POST">
      <label for="username">Username:</label><br />
      <input type="text" id="username" name="username" /><br />
      <label for="password">Password:</label><br />
      <input type="password" id="password" name="password" /><br />
      <input type="submit" value="Login" />
    </form>
  </body>
</html>

Add the following code to “views/dashboard.ejs” to create a dashboard after login. views/dashboard.ejs

<!-- views/dashboard.ejs -->
<!DOCTYPE html>
<html>
  <head>
    <title>Dashboard</title>
  </head>
  <body>
    <h1>Welcome, <%= username %>!</h1>
    <p>This is your dashboard.</p>
  </body>
</html>

After creating all the files, the directory structure will be as follows.

certification
|- views
| |- dashboard.ejs
| |- index.ejs
|- app.js
|-package.json
|-package-lock.json

After creating all the files, run the following command to start the server.

node app.js

summary

In this article, I introduced how to implement a login function in Node.js using Fastify. Fastify is a fast and efficient framework for developing web applications with Node.js. Fastify is a fast and efficient framework compared to other frameworks for Node.js. Fastify is a fast and efficient framework compared to other frameworks for Node.js. Fastify is a fast and efficient framework compared to other frameworks for Node.js. Fastify is a fast and efficient framework compared to other frameworks for Node.js. Fastify is a fast and efficient framework compared to other frameworks for Node.js. Fastify is a fast and efficient framework compared to other frameworks for Node.js. Fastify is a fast and efficient framework compared to other frameworks for Node.js. Fastify is a fast and efficient framework compared to other frameworks for Node.js.