Hello, I am Charu from Classmethod. I have recently started using Fastify in my projects so I thought of writing the basic start in a blog.
Introduction
If you got interested in this blog, then I am sure you are familiar with Node.js development, also you know a bit about Express or have worked with it. Well, Fastify is a NodeJS framework used for backend web development. It is mainly know for it's speed, efficiency, and developer experience.
Alongside, we'll explore TypeScript, a superset of JavaScript, renowned for its robust typing system and suitability for large-scale applications.
Prerequisites
Setting Up Your Project
'npm init'
'npm install fastify'
'npm install typescript @types/node --save-dev'
.Getting started with the code
const fastify = require("fastify")({ logger: true });
fastify.get("/", async (request: any, reply: any) => {
return { greeting: "Hello from Fastify and TypeScript!" };
});
const start = async () => {
try {
await fastify.listen({ port: 8888 });
} catch (err) {
fastify.log.error(err);
process.exit(1);
}
};
start();
The code above demonstrates a basic Fastify server with TypeScript that listens on port 8888. It defines a single route that responds to GET requests on the root path with a JSON greeting message. The fastify.listen({ port: 8888 })
call makes the Fastify server listen for incoming connections on port 8888. If there's an error starting the server, the error is logged, and the process exits with a status code of 1. Finally, the start function is called to start the server.
"scripts": {
"build": "tsc",
"start": "node dist/source.js",
}
tsconfig.json
file. It should be 'commonjs'
as shown below,"compilerOptions": {
"target": "es2018",
"module": "commonjs",
"moduleResolution": "node",
"outDir": "./dist",
"esModuleInterop": true,
"strict": true,
"skipLibCheck": true,
},
npm run build
npm run start
This was a basic example for your to start with Fastify. Hope you found it useful.
Thank you for reading!
Happy Learning:)