Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Installing and the first server

A Fastify server is a JavaScript file that creates an application instance, adds a route and starts listening on a port. A port is the number a client uses to reach the server, for example 3000.

Creating a project

Create a project folder and install Fastify:

mkdir blog-api
cd blog-api
npm init -y
npm install fastify

npm init -y creates package.json, and npm install fastify adds the package to the dependencies.

Turning on ES modules

Open package.json and add the type field and the scripts section:

{
  "name": "blog-api",
  "type": "module",
  "scripts": {
    "dev": "node --watch src/server.js",
    "start": "node src/server.js"
  },
  "dependencies": {
    "fastify": "^5.0.0"
  }
}

"type": "module" allows import, and the --watch flag restarts the server every time you save a file.

The first server

Create the file src/server.js:

// src/server.js
import Fastify from 'fastify';
 
const app = Fastify({ logger: true });
 
app.get('/', async () => {
  return { message: 'Hello from the blog!' };
});
 
try {
  await app.listen({ port: 3000 });
} catch (error) {
  app.log.error(error);
  process.exit(1);
}

Fastify() creates the application, app.get() adds a route, and app.listen() starts the server and returns a promise. The handler returns an object, and Fastify turns it into JSON.

Running it

npm run dev

The terminal shows a log line with Server listening at http://127.0.0.1:3000. Open that address in a browser and you see {"message":"Hello from the blog!"}. Stop the server with Ctrl+C.

The logger

The logger: true option turns on the built-in logger. Every request is written to the terminal as two JSON lines: "incoming request" and "request completed" with the status code and the response time. Logging is covered in a separate lesson.

A request from the terminal

You can check the API not only in a browser but also with curl:

curl http://localhost:3000/

The command prints the same JSON. In later lessons curl is needed for POST and DELETE requests, which a browser address bar cannot send.

Common mistake

If the port is already taken — for example, the server is running in a second terminal window — listen fails with EADDRINUSE. Stop the old process or choose another port: app.listen({ port: 3001 }).

Thanks for reading!

Donate to the site — we work hard for you.