DEV Community

Cover image for Project setup — Fastify with TypeScript (part 3/18)
Antonio Tripodi
Antonio Tripodi

Posted on

Project setup — Fastify with TypeScript (part 3/18)

Project setup

Third chapter of the "Fastify with TypeScript" series. Before writing a single line of business logic, you need a properly configured project: a package.json, two tsconfig files (one for type-checking, one for the production build), and a folder structure that scales. At the end of the chapter we'll run four commands to check that everything works.

Requirements: Node.js ≥ 22.19 (24 LTS recommended) and TypeScript 6.x. Type stripping runs flag-free from Node 22.19 / 23.6 / 24; on older 22.x you'd need --experimental-strip-types.


Initialization

mkdir my-fastify-app && cd my-fastify-app
npm init -y
npm pkg set type=module
npm install fastify
npm install -D typescript@6 @types/node@24
mkdir src test
Enter fullscreen mode Exit fullscreen mode

@types/node describes Node's own APIs to TypeScript. Pin it to the major version of the Node you run (@24 here, @22 if you are on Node 22): without a version npm installs the newest one, which may describe APIs your Node doesn't have yet.

package.json

npm init created a package.json for you. Open it and change three fields, main, scripts and engines, leaving everything else as it is (in particular the dependencies and devDependencies that npm just wrote):

{
  "name": "my-fastify-app",
  "type": "module",
  "main": "dist/server.js",
  "scripts": {
    "dev": "node --watch --env-file-if-exists=.env src/server.ts",
    "build": "tsc -p tsconfig.build.json",
    "start": "node --env-file-if-exists=.env dist/server.js",
    "test": "node --test 'test/**/*.test.ts'",
    "typecheck": "tsc --noEmit"
  },
  "engines": {
    "node": ">=22.19.0"
  }
}
Enter fullscreen mode Exit fullscreen mode

node --watch restarts the server on every file change and --env-file-if-exists loads a local .env when there is one, so the project never needs dotenv. start uses the same flag so you can run the built output locally; in production there is no .env file and the variables come from the real environment. Note that typescript is only a devDependency: in development Node runs the .ts files directly.

.env and .gitignore

Create the .env file now, even though it only holds one value for the moment:

echo "PORT=3000" > .env
printf 'node_modules\ndist\n.env\n' > .gitignore
Enter fullscreen mode Exit fullscreen mode

Two reasons. The .env file will soon contain secrets, so it must never be committed: that's what the .gitignore line is for. And in watch mode Node also watches the .env file for changes, so on some versions npm run dev stops with an ENOENT error if the file isn't there.

tsconfig.json (type-checking)

This file is only used by tsc --noEmit and by your editor: the code is executed by Node with type stripping, no compilation involved.

{
  "compilerOptions": {
    "target": "ES2024",
    "lib": ["ES2024"],
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "types": ["node"],
    "rootDir": ".",
    "strict": true,
    "noEmit": true,
    "skipLibCheck": true,
    "verbatimModuleSyntax": true,
    "erasableSyntaxOnly": true,
    "allowImportingTsExtensions": true,
    "rewriteRelativeImportExtensions": true
  },
  "include": ["src/**/*.ts", "test/**/*.ts"]
}
Enter fullscreen mode Exit fullscreen mode

A few notes specific to TypeScript 6:

  • strict is now true by default, but we keep it explicit so the intent is obvious to anyone reading the file.
  • types is no longer auto-discovered (it defaults to []), so ["node"] is required or process, Buffer and friends won't exist.
  • rootDir is no longer inferred from your sources; set it explicitly.
  • erasableSyntaxOnly makes the compiler reject the TypeScript syntax that Node's type stripping can't handle (see the note below). This is the single most useful flag in this file.
  • verbatimModuleSyntax forces import type for type-only imports, which type stripping requires.
  • allowImportingTsExtensions + rewriteRelativeImportExtensions let you write import './app.ts' (what Node needs at runtime) and have tsc rewrite it to ./app.js in the build output.

tsconfig.build.json (production build)

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "noEmit": false,
    "rootDir": "src",
    "outDir": "dist",
    "declaration": true,
    "sourceMap": true
  },
  "include": ["src/**/*.ts"]
}
Enter fullscreen mode Exit fullscreen mode

A note on type stripping: Node removes type annotations without transforming code, so your source must avoid the TypeScript features that generate JavaScript: enum, namespace, constructor parameter properties (constructor(private x: string)) and import x = require(). With erasableSyntaxOnly: true, tsc reports an error on each of these, so you find out before Node does. Decorators are the exception: tsc accepts them, but Node can't run them, so the series doesn't use them. Finally, always use import type for types, and import local files with their .ts extension.

Check that it works

There is no application yet, so let's write a throwaway entry point just to try the four scripts. We'll replace it in the next chapter.

// src/server.ts — temporary: we replace it in the next chapter
const port: number = Number(process.env.PORT ?? 3000);

console.log(`Setup works. The server will listen on port ${port}.`);
Enter fullscreen mode Exit fullscreen mode
npm run typecheck   # prints nothing: no type errors
npm run dev         # Setup works. The server will listen on port 3000.
Enter fullscreen mode Exit fullscreen mode

npm run dev stays alive waiting for changes: edit the message, save, and it runs again. Stop it with Ctrl+C, then try the production path:

npm run build       # creates dist/server.js (plus .d.ts and source map)
npm start           # same message, this time from the compiled JavaScript
Enter fullscreen mode Exit fullscreen mode

One last experiment, to see erasableSyntaxOnly earn its place. Add this line at the end of src/server.ts:

enum Color { Red }
Enter fullscreen mode Exit fullscreen mode

npm run typecheck now fails with This syntax is not allowed when 'erasableSyntaxOnly' is enabled, and Node itself refuses to run the file (TypeScript enum is not supported in strip-only mode). Remove the line before going on.

Recommended project structure

This is where the project is heading over the next chapters:

src/
  app.ts               # builds the Fastify instance (no listen() here)
  server.ts            # entry point: imports app.ts and starts the server
  config.ts            # environment variables validated against a schema
  plugins/             # shared plugins (database, auth, security...)
  users/               # one folder per module, with everything that module needs
    users.route.ts       # the route plugin: routes + handlers
    users.schema.ts      # TypeBox schemas
    users.service.ts     # business logic and domain errors (chapter 13)
    users.repository.ts  # data access (chapter 13)
  auth/
    auth.route.ts
    auth.schema.ts
    auth.service.ts      # login rules (chapter 13)
test/
  helper.ts
  users.test.ts
  users.service.test.ts
Enter fullscreen mode Exit fullscreen mode

The code is grouped by module, not by technical layer: there is no top-level routes/, services/ or repositories/ folder, and no modules/ wrapper either. Each module is a folder directly under src/: everything about users lives in src/users/, so working on a feature means working in one folder, and removing a feature means deleting one. plugins/ is the only folder that isn't a module: it holds the infrastructure shared by all of them.

Separating app.ts from server.ts is a very common convention in the Fastify ecosystem: app.ts exports a factory function that builds and configures the Fastify instance (routes, plugins, hooks) without ever binding to a network port; server.ts is the only file responsible for starting the listener. The main benefit is that in your tests you can import buildApp() from app.ts and use inject() without opening a TCP port (we'll cover this in the testing chapter).


⬅️ Previous chapter: Fastify core concepts · ➡️ Next chapter: Your first server (app.ts, server.ts, config.ts)

This article is part of the "Fastify with TypeScript" series — chapter 3 of 18.

Top comments (0)