How to get up and running with Fastify

Computer Science students at Wentworth Institute of Technology. Future software engineer at Microsoft. Lots of JavaScript/TypeScript open source with Fastify and Matterhorn

Fast and low overhead web framework, for Node.js

Fastify version 1 was released on March 7th. This post will show you how to get it set up, and we’ll discuss some of the incredible features Fastify has to offer. No configuration is necessary — Fastify’s code base will run on Node versions 6.x, 8.x, and 9.x.

What’s going on here?

const fastify = require('fastify')()

Line 1 is importing the Fastify framework into the JavaScript project and instantiating it. Your server instance is now stored in the fastify variable. You can pass additional options to this line like so:

Powered by the Pino logger, this option makes the console output easy to read and colorful. Check out the Pino documentation for more logger options, and the Fastify documentation for more Fastify instance options.

Next up: Routing

Lines 3 through 5 define a very basic Route. Routes are the core to any Node.js backend server. Fastify supports two methods of defining routes: the shorthand method used above, or a general .route method as shown below.

Start your engines! 3…2…1…GO!

Finally, start the Fastify instance on localhost port 3000. This is the last step required to create your own Fastify instance. Internally this method will wait for .ready() (which is called after loading plugins). No new routes can be defined after calling the .listen() method.

Whats next? Plugins!

One of the best features of Fastify is how easy it is to write and incorporate plugins into a server instance. To start, define a function:

Now you can call the superMethod anywhere you have access to your Fastify instance.

/* server.js */

fastify.listen(3000, err => { fastify.superMethod()})

Just to note: you can register plugins within other plugins, which locks that child plugin’s scope to the parent plugin only. This topic is too advanced for this article, so I won’t be covering it any more detail. You can read more about Fastify plugins here. Check out the full example files in a Github gist here.

Our mission: to help people learn to code for free. We accomplish this by creating thousands of
videos, articles, and interactive coding lessons - all freely available to the public. We also have
thousands of freeCodeCamp study groups around the world.