3 Highly Recommended Fastify Plugins You Must Use!

Written by: Bagus Facsi Aginsa
Published at: 12 Apr 2023


As we know that fastify has many plugin ecosystem to extend its functionality. You can see the list of fastify plugin ecosystems in Fastify Ecosystem. Some plugins will make your code easier to read, some plugins just easy to use, and some plugins also has better performance than the more popular npm package. In this tutorial, I will show you 3 plugins that I always use in my project that easy to use and made my life easier.

The 3 plugins that I highly recommend are fastify-cors for handling CORS, fastify-jwt for handling JWT auth, and fastify-healthcheck for generating health-check routes automatically.

Fastify Plugin for Handling CORS: fastify-cors

Did you ever see this error message?

Access to XMLHttpRequest at https://example.com from https://example2.com 
has been blocked by CORS Policy: No 'Access-Control-Allow-Origin' header 
is present on the requested resource.

Well, in fastify, you can solve this problem by using fastify-cors plugin, and you will never see that annoying message again. To use this plugin in your backend, install the plugin inside your project folder just like installing npm packages:

npm install @fastify/cors

Register the plugin to the fastify:

const fastify = require('fastify')()

fastify.register(require('@fastify/cors'), { 
    origin: *
})

The configuration above will allow requests from any origin, if you want to be more specific you can mention the origin domain in the options like this:

const fastify = require('fastify')()

fastify.register(require('@fastify/cors'), { 
    origin: 'https://example.com'
})

If you have multiple origins, you can add the origin as an array in the options like this:

const fastify = require('fastify')()

fastify.register(require('@fastify/cors'), { 
    origin: ['https://example.com', 'http://localhost:3000']
})

That’s it. You will never see the CORS error message again.

Fastify Plugin for Handling JWT: fastify-jwt

This plugin will make your code easier to read. Also, fastify already choose the fastest npm library for handling the JWT for you. To use this plugin, install the plugin inside your project folder just like installing npm packages:

npm install @fastify/jwt

Register the plugin to the fastify:

const fastify = require('fastify')()

fastify.register(require('@fastify/jwt'), {
    secret: 'yoursupersecretthatnooneknows'
    sign: {
        expiresIn: '1d'
    }
})

You can sign the jwt by using this function:

...

const login = async (req, res) => {
    try {

        let { username, password } = req.body

        // Do authentication here

        let jwtPayload = {
            username
        }
        let token = await fastify.jwt.sign(jwtPayload)
        res.status(200).send({
            message: 'Login success',
            data: {
                token
            }
        })
    } catch (e) {
        res.status(500).send({ message: 'login error because: ' + e.message })
    }
}

And then, you can just create a middleware on your project to verify every incoming request:

const authMiddleware = async (req, res) => {
    try {
        let decoded = await req.jwtVerify()
        if (!decoded) {
            res.send({ message: 'token is not valid' })
        }
        req.jwtPayload = decoded
 
    } catch (e) {
        res.status(403).send({ message: 'verify error because: ' + e.message })
    }
}

Later, you can access the payload by calling req.jwtPayload object.

With this plugin, we don’t have to dig into the request header, the plugin will do that for us.

Fastify Plugin for Generating Healthcheck Route: fastify-healthcheck

This plugin is useful when you use orchestration tools like Kubernetes in your production environment. It is recommended to use readiness, liveness, and startup probe. This plugin will help you generate a health-check path automatically, and then you can use it as liveness, readiness, or startup probe.

To use this plugin, install the package:

npm install fastify-healthcheck

Register the plugin to the fastify

const fastify = require('fastify')()

fastify.register(require('fastify-healthcheck'))

After that, just start the server and you can access the health-check path in /health.

curl localhost:3000/health

You will get a return like this:

{"statusCode":200,"status":"ok"}

You can set a different path by passing an option when registering the plugin like this:

fastify.register(require('fastify-healthcheck'), {
    healthcheckUrl: '/health-check'
})

The healthcheck path will be changed to /health-check