Skip to content
Tutorials Center
My learning

Topics

Lesson 2 of 39 ยท Getting Started

Your First Fastify Server

Create and start your first Fastify server: install the package, write a route, call listen with port and host, handle startup errors and shut down cleanly.

In this lesson you build the smallest real Fastify server: install the package, create an app, define one route and start listening. You will also learn the two details that trip up almost everyone the first time: which host to bind to and what to do when startup fails.

The commands and the file layout are real. The runnable examples use the stand-in Fastify from the first lesson, so you can see the server answer a request right here.

Install and write the server

In a new folder, initialize a project, switch it to ES modules, and install Fastify:

Terminal
npm init -y
npm pkg set type=module
npm install fastify

Then create server.js:

JavaScript
import Fastify from 'fastify';

const app = Fastify({ logger: true });

app.get('/', async (request, reply) => {
  return { hello: 'world' };
});

try {
  await app.listen({ port: 3000 });
} catch (err) {
  app.log.error(err);
  process.exit(1);
}

Run it with node server.js and open http://localhost:3000. You should see {"hello":"world"}, and the terminal prints one JSON log line per event, such as the server start and each request.

Three details worth noticing:

  • Fastify() is a factory function that returns the app (also called the instance). The name you give the import (Fastify, fastify) is up to you.
  • await app.listen(...) works at the top level because the project uses ES modules. In CommonJS you would wrap it in an async function start().
  • listen takes an options object ({ port, host }). The older listen(3000, '0.0.0.0') positional form was removed in Fastify 5, so always use the object.

CommonJS version

If your project uses require, the same server looks like this:

JavaScript
const Fastify = require('fastify');
const app = Fastify({ logger: true });

app.get('/', async () => ({ hello: 'world' }));

const start = async () => {
  try {
    await app.listen({ port: 3000 });
  } catch (err) {
    app.log.error(err);
    process.exit(1);
  }
};
start();

Both styles work; this course uses ES modules because they allow top-level await and match how modern Node projects are written.

Run it with the stand-in

Node.js Start a server and call it with fetch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

listen() returns a promise that resolves with the address string (for example http://127.0.0.1:3000). Port 0 asks the operating system for a free port, which is exactly what you want in tests so parallel test files never collide.

Host and port

The host option decides which network interfaces accept connections.

host Who can connect
omitted Fastify listens on localhost (loopback only: just your own machine)
'127.0.0.1' Only your machine
'0.0.0.0' Every IPv4 interface: other computers, and containers' port mappings
'::' Every IPv6 (and usually IPv4) interface

The key rule for deployment: inside Docker or on most hosting platforms you must bind to 0.0.0.0. A server bound to loopback inside a container is reachable only from inside that container, so published ports show "connection refused" or "empty reply". Pair it with an environment variable for the port:

JavaScript
await app.listen({
  port: Number(process.env.PORT) || 3000,
  host: process.env.HOST || '0.0.0.0',
});

On your own laptop, 0.0.0.0 also exposes the dev server to your local network, which is usually fine but worth knowing.

sequenceDiagram
    participant Dev as Your code
    participant F as Fastify
    participant OS as Operating system
    Dev->>F: await app.listen({ port, host })
    F->>F: load plugins, run onReady hooks
    F->>OS: bind port and host
    OS-->>F: ok, or EADDRINUSE
    F-->>Dev: resolves with the address

What listen() does. Plugins are fully loaded before the port opens.

That second step is important: listen() first waits until all your plugins have loaded (chapter 4), so the server never accepts a request before your app is ready.

When startup fails

The most common startup error is EADDRINUSE: something else already uses the port. Because listen() returns a promise, try/catch captures it. Printing the error through app.log.error and exiting with a non-zero code lets process managers and container platforms know that the start failed.

Node.js Handling a port that is already taken

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Do not swallow the error and keep running: a server that failed to bind will never serve traffic. Exit and let the supervisor restart it.

Stopping cleanly

await app.close() stops accepting new connections, waits for in-flight requests, and runs shutdown hooks. In production you call it when the process receives a signal:

JavaScript
for (const signal of ['SIGINT', 'SIGTERM']) {
  process.once(signal, async () => {
    await app.close();
    process.exit(0);
  });
}

Chapter 8 shows a complete graceful-shutdown setup; for now remember that close() exists and returns a promise.

Common mistakes

  • Forgetting host: '0.0.0.0' in Docker. The app starts, but nothing can reach it.
  • Using the old listen(port, host) form. Fastify 5 expects an object.
  • Not awaiting listen(). Errors become unhandled rejections and the process may die with a confusing message.
  • Hard-coding the port. Read process.env.PORT so hosting platforms can choose it.
  • Starting the server in the same file that tests import. Export the app from one file and call listen from another (project structure); tests then use inject() and never open a port.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which call starts a Fastify 5 server on port 3000?

    Fastify 5 expects an options object, and listen returns a promise you should await.
  2. 2. Your app works locally but not in Docker. What is the most likely cause?

    Inside a container, loopback is not reachable from outside. Bind to 0.0.0.0.
  3. 3. What does listening on port 0 do?

    Port 0 means "any free port"; the resolved address tells you which one was chosen.
  4. 4. What should you do when listen() rejects at startup?

    A server that failed to bind cannot serve requests, so log, exit and let the supervisor restart it.

Summary

  • Install fastify, create the app with Fastify(), define routes, then await app.listen({ port, host }).
  • Use host: '0.0.0.0' in containers; read the port from process.env.PORT.
  • listen() resolves after all plugins are loaded and returns the address string.
  • Catch startup errors, log them and exit non-zero.
  • await app.close() shuts down gracefully; port 0 is ideal for tests.

Next: How a Request Flows Through Fastify