Fastify starting the server

Safet Zahirovic (@zahsaf17)

Fastify tutorial in 4 parts

First we need to install packages:

npm i fastify (or what ever package manager youยดre using)

With that out of the way, it's time to creat instance of our server. Let's create a file called app.js. Inside write the following code:

import Fastify from 'fastify';

const app = Fastify({
  logger: true,
});

app.listen({ port: 3000 }, function (err, address) {
  if (err) {
    app.log.error(err);
    process.exit(1);
  }
  console.log('Server is now listening on ${address}');
});

With that done, run you server with node app.js. You should now see a message that your server is listening on wich address, port, etc.

Fastify supports async/await out of the box, and we can do som adjustments to our code here. Instad of writing

app.listen({ port: 3000 }, function (err, address) {
  if (err) {
    app.log.error(err);
    process.exit(1);
  }
  console.log('Server is now listening on ${address}');
});

We can write this

try {
  const address = await app.listen({ port: 3000 });
  console.log('Server is now listening on ${address}');
} catch (err) {
  app.log.error(err);
  process.exit(1);
}

Now our code is more concise and is not relying on callbacks.

In order to test our code (we'll come back to this later) we would like to be able to export our instance. Now let's refactor our code. In app.js, write following:

import Fastify from 'fastify';

export function buildApp(args = {}) {
  const app = Fastify({
    logger: true,
  });

  return app;
}

This exports a function now that creates an app instance. It takes arguments in as we will need it later.

Now create a new file called index.js. In this file, we would create our app instance:

import { buildApp } from './app.js';

const app = buildApp();

try {
  const address = await app.listen({ port: 3000 });
  console.log('Server is now listening on ${address}');
} catch (err) {
  app.log.error(err);
  process.exit(1);
}

Now instead of running app.js, run our newly created index.js and you'll see that the server is running.

Congrats ๐Ÿฅณ You've created your first Fastify server. It is missing som key ingredients and we will look how to season this app this those ingredients in the next post.

Fastify tutorial in 4 parts