DEV Community 👩‍💻👨‍💻

Hasan Zohdy
Hasan Zohdy

Posted on

5-Nodejs Course 2023: Create Fastify Server

Recap

On our last time in the project, we navigated through the project files and the future structure of the files, now let's create our server handler using fastify.

Create Fastify Server

First, we need to install fastify.

yarn add fastify
Enter fullscreen mode Exit fullscreen mode

Project Entry Point

The project starts from the src/index.ts file, which is created automatically for you now, let's create the server handler in this file.

Create Server Handler

// src/index.ts
import fastify from 'fastify';

const server = Fastify();

server.get('/', async (request, reply) => {
  return { hello: 'world' };
});
Enter fullscreen mode Exit fullscreen mode

Nothing fancy here, we just created a server handler and added a simple route to it.

Start Server

Now, let's start the server.

// src/index.ts
import fastify from 'fastify';

const server = Fastify();

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


async function start() {
  await server.listen({ port: 3000 });

  console.log("Start browsing using http://localhost:3000");
}

start();
Enter fullscreen mode Exit fullscreen mode

We created a start function so we can start the server by calling .listen, which receives an object of properties, in our case, we only need to specify the port.

Run Server

Now, we're done, let's run the server.

yarn start
Enter fullscreen mode Exit fullscreen mode

Open your browser and navigate to http://localhost:3000, you should see the following output.

{
  "hello": "world"
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

In this lesson, we created our server handler using fastify, and we started the server, in the next lesson, we'll create our first route.

🎨 Project Repository

You can find the latest updates of this project on Github

😍 Join our community

Join our community on Discord to get help and support (Node Js 2023 Channel).

Top comments (0)

Let's team up together 🤝

We're Hiring

We're hiring for a Senior Full Stack Engineer to join the DEV team. Want the deets? Head here to learn more about who we're looking for.