DEV Community

Christopher Ribeiro for Dymme

Posted on

From zero to production with Fastify

When developing an application we often ask ourselves

Which framework should I use?

We know this question actually comes a lot in the JavaScript ecosystem.

In this post I show why at Dymme we chose Fastify as our back-end framework and how we use it.

The why

1. Fast by default:
Fastify kills at every benchmark see

2. Express like:
We can write code just like in the ol' Express days if we want to.

fastify.get('/', async function handler (request, reply) {
  return { hello: 'world' }
})
Enter fullscreen mode Exit fullscreen mode

3. Configurable:
Fastify offers a plugin system just like Express. Plugins can modify Fastify or act in certain moments (when the server closes or the request is sent for example).
The chosen approach makes us write decoupled code.

Each plugin is independent. Meaning that they can't talk to each other directly.
All plugins talk to the Fastify instance directly, which itself is a plugin. And if a plugin wants to communicate with another it communicates via the Fastify instance.

fastify.decorate('db', new DbConnection())

fastify.get('/', async function (request, reply) {
  return { hello: await this.db.query('world') }
})
Enter fullscreen mode Exit fullscreen mode

See that, we make the db plugin available for the whole instance. This makes possible to use this plugin directly from anywhere that has access to the Fastify instance.
In this case, our route handler has the Fastify instance by default and we can access it to call our db plugin without direct access to it.

And if you followed along, you may note that a route is also a plugin 🤯 that's how it can talk to the Fastify instance and use the db plugin added to it.

Take a look in:

4. TypeScript:

Yes it supports TypeScript, so you can have autocomplete (and make some guy want to remove it from your codebase).

The how

By now I may have convinced you that Fastify is the best Express alternative than others. But what about how we do it at Dymme?

Glad you asked!

Dymme is a Startup that enables merchants to sell their products in one click and shoppers to pay also in one click, instantly. As we deal with real time payments, we need to have an API that handles heavy traffic and be able to move quickly.

Fastify allows all that but if you start from scratch you may not perceive the difference from Express.
That's why we recommend you to start your application with the CLI.
It will not only bootstrap you application but will configure it to have TypeScript if you want.

The CLI will also setup your API to use filesystem routing (Yes, you heard that).

Take a look in this base template we are using internally.
We will update it in the future with better patterns, so stay tuned and give it a star!


Dymme.

Top comments (0)