Creating a TypeScript Fastify API Project
Fastify is a fast and low-overhead web framework for Node.js. It is highly performant and provides a rich plugin ecosystem. When combined with TypeScript, it allows you to build robust and type-safe APIs. In this blog post, we’ll walk through the steps to set up a Fastify API project with TypeScript.
Prerequisites
Before you begin, ensure you have the following installed on your machine:
- Node.js (v14 or later)
- npm (v6 or later)
Step 1: Set Up the Project
First, create a new directory for your project and initialize a new Node.js project:
mkdir fastify-typescript-api
cd fastify-typescript-api
npm init -y
This will create a package.json
file in your project directory.
Step 2: Install Dependencies
Next, install Fastify and TypeScript along with their respective type definitions:
npm install fastify
npm install -D typescript @types/node ts-node
Step 3: Configure TypeScript
Create a tsconfig.json
file in the root of your project with the following content:
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"outDir": "./dist"
},
"include": ["src/**/*.ts"],
"exclude": ["node_modules"]
}
Step 4: Set Up the Project Structure
Create a src
directory and add an index.ts
file inside it:
mkdir src
touch src/index.ts
Step 5: Write the Fastify Server Code
Open src/index.ts
and add the following code:
import fastify from 'fastify';
const server = fastify({ logger: true });
server.get('/', async (request, reply) => {
return { message: 'Hello, Fastify with TypeScript!' };
});
const start = async () => {
try {
await server.listen(3000, '0.0.0.0');
server.log.info(`Server listening on http://localhost:3000`);
} catch (err) {
server.log.error(err);
process.exit(1);
}
};
start();
This code sets up a simple Fastify server with a single route (/
) that returns a JSON response.
Step 6: Add Scripts to package.json
Update the scripts
section of your package.json
to include the following scripts:
"scripts": {
"build": "tsc",
"start": "node dist/index.js",
"dev": "ts-node src/index.ts"
}
build
: Compiles the TypeScript code to JavaScript.start
: Runs the compiled JavaScript code.dev
: Runs the TypeScript code directly usingts-node
for development.
Step 7: Run the Server
To start the development server, run:
npm run dev
You should see output indicating that the server is running. Open your browser and navigate to http://localhost:3000
. You should see the message {"message":"Hello, Fastify with TypeScript!"}
.