Fastify first route

Safet Zahirovic (@zahsaf17)

Fastify tutorial in 4 parts

Now the first ingredient we need is routing. Right now our server is quite bland, and doesn't answer to our requests. In order to do so, we need to define a route inside our app. Let's do that now:

Inside app.js write following:


export function buildApp(args={}) {
  ...

  app.get('/', async (request, reply) => {
    return { hello: 'world' }
  })
}

Now run node index.js, and go to localhost:3000 in your browser. You'll see now that the server is responding with {"hello":"world"}. We have defined our GET route now, and server is now replying on that request.

However, here we don't know if we have any query string parameters, or what type of response we're going to return. So let's rewrite it a little bit.

Instad of using .get property, we can use .route to achieve this. Let's change our code a bit:

fastify.route({
  method: 'GET',
  url: '/',
  schema: {
    querystring: {
      name: { type: 'string' },
      excitement: { type: 'integer' },
    },
    response: {
      200: {
        type: 'object',
        properties: {
          hello: { type: 'string' },
        },
      },
    },
  },
  handler: function (request, reply) {
    reply.send({ hello: 'world' });
  },
});

If you run node index.js again, you'll see that we get the same result in the browser, but now we are serializing our response if response is 200 OK. At the same time, we are saying that this route can have name and excitment as querystring, and we can can get them from request object.

Change your route code to:

app.route({
  method: 'GET',
  url: '/',
  schema: {
    querystring: {
      name: { type: 'string' },
      excitement: { type: 'integer' },
    },
    response: {
      200: {
        type: 'object',
        properties: {
          hello: { type: 'string' },
        },
      },
    },
  },
  handler: function (request, reply) {
    const { name } = request.query;

    reply.send({ hello: name });
  },
});

Now run index.js file again, and go to localhost:3000/?name=world. You will get the same output in the browser as before, because we are passing query parameters as a value to our response.

Congrats 🥳 you have learned now how to declare a route, define query params and serielize your response. Now we have salt in our meal, but that' not enough. In the next chapter, we are going to learn how to serve views from our app.

Fastify tutorial in 4 parts