API Versioning with Fastify


In this article, We will see how we can create an API route with versioning. Something like example.com/api/v1/process

Grouping or Versioning is a technique to isolate the working API endpoint from the newly developed API. We can group it inside the v prefix to do that.

To do this all you have to do is. Wrap everything inside the Fastify register and pass the prefix: /v1

import Fastify from 'fastify';

fastify.register(async (v1, opts, done) => {
    v1.get('/', async (request, reply) => {
        reply.send("Hello World");
    });
}, { prefix: '/v1' });

const start = async () => {
    try {
        await fastify.listen({ port: 3000 });
    } catch (err) {
        fastify.log.error(err);
        process.exit(1);
    }
};

start();

Now save the file and run it. Your API endpoint will be accessible under http://localhost:3000/v1/