DEV Community

damirn
damirn

Posted on

Setting up fastify

Before we dive into creating POST and GET routes, let's set up Fastify in a new Node.js project. Ensure you have Node.js and npm (Node Package Manager) installed on your machine, and follow these steps:

Initialize a new Node.js project:

$ mkdir fastify-app $ cd fastify-app $ npm init -y 
Enter fullscreen mode Exit fullscreen mode

Install Fastify:

$ npm install fastify --save 
Enter fullscreen mode Exit fullscreen mode

Creating a Basic Fastify Server:

Once Fastify is installed, let's create a basic server configuration to handle HTTP requests. Create an index.js file in your project directory and add the following code:

// index.js const fastify = require('fastify')(); fastify.get('/', async (request, reply) => { return { message: 'Welcome to my Fastify app!' }; }); fastify.post('/user', async (request, reply) => { const { name, email } = request.body; return { message: `Hello ${name} (${email})!` }; }); fastify.listen({ port: 3000 }, (err) => { if (err) { console.error(err); process.exit(1); } console.log('Server is running on port 3000'); }); 
Enter fullscreen mode Exit fullscreen mode

In the code snippet above, we created two routes: a GET route ("/") and a POST route ("/user"). The GET route simply returns a welcome message, while the POST route expects a JSON payload containing user data. You can customize these routes according to your application's requirements.

Let's run our server with:

$ node index.js 
Enter fullscreen mode Exit fullscreen mode

and give it a try by running curl:

$ curl http://localhost:3000 {"message":"Welcome to my Fastify app!"} 
Enter fullscreen mode Exit fullscreen mode

or let's post a JSON object to out /user route:

$ curl -X 'POST' \ 'http://localhost:3000/user' \ -H 'accept: application/json' \ -H 'Content-Type: application/json' \ -d '{ "email": "user@example.com", "name": "Foo" }' {"message":"Hello Foo (user@example.com)!"} 
Enter fullscreen mode Exit fullscreen mode

As you can see, it is quite easy and effective to create a Web backend server with node.js and fastify!

In the next post we will take a look at validating the input and output data with JSON schema.

Stay fast!

Top comments (1)

Collapse
 
thomasbnt profile image
Thomas Bnt

Hello ! Don't hesitate to put colors on your codeblock like this example for have to have a better understanding of your code 😎

console.log('Hello world!'); 
Enter fullscreen mode Exit fullscreen mode

Example of how to add colors and syntax in codeblocks