Creating Your First ‘Hello World’ Application with Fastify

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

  • Node.js installed.
  • Basic knowledge of TypeScript and Node.js.
  • An IDE or text editor of your choice (I am using VSCode).
  • Setting Up Your Project

  • Create a new directory for the project and initialize a Node.js project: 'npm init'
  • Install Fastify: 'npm install fastify'
  • Next, install TypeScript and necessary types: 'npm install typescript @types/node --save-dev'.
  • Getting started with the code

  • Make a new directory 'src' and a new file under 'src' directory. I named it as 'source.ts'.
  • Write the following code in source.ts file,
  • 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.

  • Make sure to check you package.json file start script. It should have the location of your js source file. In my case it is,
  • "scripts": {
        "build": "tsc",
        "start": "node dist/source.js",
    }
  • Also, check your Typescript module in 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,
        },
  • Now, to run your application, execute the following two commands-
  • npm run build

    npm run start

  • You can visit your localhost in your browser and check the response. It should display the following response-
  • This was a basic example for your to start with Fastify. Hope you found it useful.

    Thank you for reading!

    Happy Learning:)