Build a Node.js Server With Fastify and TypeScript
Published: 2022-05-22 11:48:07

_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](https://expressjs.com/) framework. However, there’s a third option you can choose from — [Fastify](https://www.fastify.io/). 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](https://www.fastify.io/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](https://nodejs.org/en/) version 20
- IDE of choice (e.g. Visual Studio Code)

<hr />

### 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:
```bash
mkdir fastify-typescript
```

Afterwards, let’s navigate into our newly created directory:
```bash
cd fastify-typescript
mkdir src
mkdir build
```

The next step is to initialize an npm project
```bash
npm init -y
```

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:
```bash
npm install fastify
npm install -D typescript @types/node ts-node
```

### 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:
```bash
npx tsc --init
```

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:
{% gist https://gist.github.com/duncanlew/c3ff2284b2506df757f1268327947c7d %}

### 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:

{% gist https://gist.github.com/duncanlew/46a120eeea54b97cc0922db8ca21758f %}

Our next step is to add the following line to the scripts section of `package.json`:
{% gist https://gist.github.com/duncanlew/99e0a7976a75d140fb40b37fe8ff4d25 %}

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:
```bash
npm run start-ts
```

The Fastify server will start up and listen for a request at `localhost:8080`:
![Fastify startup output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xwzpfqb3qdulkt90ic0r.png)
 
Finally, open up a browser and visit `localhost:8080` to see the **hello there** output:
![Fastify output in the browser](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wjpgsp3aqzaznp89zu5q.png)

### 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:
{% gist https://gist.github.com/duncanlew/755b52abeb7bf8688ee607ab396867d0 %}

Now you can run your transpiled TypeScript project like this:
```bash
npm run build
npm run start
```

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:
```bash
const fastify = Fastify({logger: true});
```

Afterwards, you can replace your console.log() statements with this Fastify statement:
```bash
fastify.log.info('Incoming request at /');
```
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ckwljl04co9zrqin73qz.png)

### 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](https://github.com/duncanlew/demo-fastify-typescript).
{% github https://github.com/duncanlew/demo-fastify-typescript %}

<hr />
If the content was helpful, feel free to support me [here](https://www.buymeacoffee.com/duncanlew):
<a href="https://www.buymeacoffee.com/duncanlew" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/default-orange.png" alt="Buy Me A Coffee" height="41" width="174"></a>