DEV Community

Cover image for Build a Node.js Server With Fastify and TypeScript
Duncan Lew
Duncan Lew

Posted on • Updated on • Originally published at duncanlew.Medium

Build a Node.js Server With Fastify and TypeScript

Editor's notice: This guide has been revised in March 2024 to accommodate the latest version of Fastify.

If you’re setting up a Node.js server, your main options are mostly the built-in http module delivered by Node.js itself or the minimal Express framework. However, there’s a third option you can choose from — Fastify. Fastify is a very actively maintained project for setting up a web server. What makes Fastify shine compared to other options is its highly performant framework being able to handle up to 30,000 requests per second! You can check out the benchmarks to get a better idea of the possible traffic load. To sweeten the deal even more, Fastify supports TypeScript and logging right out of the box. So let’s get started with this web framework and see how we can set up a simple project with Fastify. 🧑‍💻

What you will need to get started

  • Node.js version 20
  • IDE of choice (e.g. Visual Studio Code)

1. Start a project with required dependencies

We are going to set up a Fastify project from scratch. The first thing we need is a directory for our source code. Let’s create a new directory via our terminal:

mkdir fastify-typescript
Enter fullscreen mode Exit fullscreen mode

Afterwards, let’s navigate into our newly created directory:

cd fastify-typescript
mkdir src
mkdir build
Enter fullscreen mode Exit fullscreen mode

The next step is to initialize an npm project

npm init -y
Enter fullscreen mode Exit fullscreen mode

The -y means that we’re going to accept the defaults.

Finally, we’re going to install the required production and development dependencies for our project like this:

npm install fastify
npm install -D typescript @types/node ts-node
Enter fullscreen mode Exit fullscreen mode

2. Set up the TypeScript compiler

TypeScript is our language of choice for developing the Fastify server. To get started, we’re going to initialize a TypeScript configuration file like this:

npx tsc --init
Enter fullscreen mode Exit fullscreen mode

The TypeScript compiler will create a tsconfig.json file with some defaults. Make sure to change the target value to es2017 or later. Doing this will prevent Fastify from throwing deprecation warnings later in the process. Also, make sure to add the rootDir and outDir to specify where the source code and compiled code should be placed. Your resulting tsconfig.json file should look like this:

3. Set up a simple Fastify server with ts-node

Let’s create an index.ts file in the src directory that contains a simple Fastify setup. We create a GET path for / which sends back a simple response. The contents of the file should look like this:

Our next step is to add the following line to the scripts section of package.json:

We use ts-node to run the TypeScript file directly without having to transpile it first to JavaScript. This prevents us from doing it in a two-step process. Our final step is to run our newly created command in the terminal:

npm run start-ts
Enter fullscreen mode Exit fullscreen mode

The Fastify server will start up and listen for a request at localhost:8080:
Fastify startup output

Finally, open up a browser and visit localhost:8080 to see the hello there output:
Fastify output in the browser

4. Set up Fastify server with transpilation

Using ts-node is a good alternative for quickly getting your application up and running with TypeScript for testing purposes. But if you’re going to use it in a production setting, it’s better not to rely on ts-node, but to actually transpile your code to JavaScript and run the transpiled file with node. This can be done by adding the following two lines to the scripts section in your package.json file:

Now you can run your transpiled TypeScript project like this:

npm run build
npm run start
Enter fullscreen mode Exit fullscreen mode

The first command transpiles the TypeScript file in the src directory and stores the output in the build directory. The second command uses node to run the transpiled JavaScript files.

5. Integrate logging

Fastify supports logging right out of the box. However, this functionality is disabled by default. The logging can be enabled easily by passing the parameter logging: true to the Fastify constructor. The benefit of using the integrated Fastify logger instead of the plain-old console.log() is because the Fastify logger adds extra information which makes it easier to track important information like server name and request IDs. This can make debugging errors and warnings in your Fastify server more easily when you have this extra tracking information.

Logging can be turned on in Fastify like this:

const fastify = Fastify({logger: true});
Enter fullscreen mode Exit fullscreen mode

Afterwards, you can replace your console.log() statements with this Fastify statement:

fastify.log.info('Incoming request at /');
Enter fullscreen mode Exit fullscreen mode

If you run your application again with the logging turned on and the modified logging statements, your terminal output will look like this:
Fastify logging output

Takeaway

TypeScript support for Fastify makes it easy to check for errors early on in the development cycle with the help of type-checking. Fastify has less overhead compared to other systems while beating out the competition in terms of high traffic performance. Best of all it provides a bunch of plugins and hooks making it very developer-friendly to expand its functionality.

Where to take this from here? You can connect Fastify with a database adapter to connect it to a database. You can try running this Fastify server on a cloud platform. There are endless possibilities with a web server. Happy coding to you all! 👋

The complete source code can be found here.

Build a Node.js Server With Fastify and TypeScript

The tutorial for this project can be found on Medium and dev.to.









If the content was helpful, feel free to support me here:

Buy Me A Coffee

Top comments (3)

Collapse
 
mahmoud_bebars profile image
m.bebars

I am searching for a template like this but has a mysql || postgreSQL
I hope you can help Me Because I can't understand the Fastify Syntax for db connection 🤷‍♂️

Collapse
 
andrewbaisden profile image
Andrew Baisden

Cool the syntax does not seem very hard to understand. I have used Express and NestJS already I know that Fastify is quite popular too!

Collapse
 
duncanlew profile image
Duncan Lew

Thanks Andrew for checking out the article! :-)
It's indeed easy to get started with Fastify