rhondamuse.com

Mastering Server-Side Development with Fastify: A Guide

Written on

Introduction to Fastify

Fastify is a lightweight framework for Node.js designed for building backend web applications. In this guide, we'll explore the various ways to handle responses effectively using Fastify.

Handling Not Found Responses

To manage not found scenarios, you can utilize the callNotFound method to trigger a custom handler. Below is a sample implementation:

const fastify = require('fastify')({});

fastify.setNotFoundHandler({

preValidation: (req, reply, done) => {

done();

},

preHandler: (req, reply, done) => {

done();

}

}, function (request, reply) {

reply.send('not found');

});

fastify.get('/', function(req, reply) {

reply.callNotFound();

});

const start = async () => {

try {

await fastify.listen(3000, '0.0.0.0');

} catch (err) {

fastify.log.error(err);

process.exit(1);

}

};

start();

In this code, we set up a handler for not found responses and call reply.callNotFound in our route to direct to this handler.

Response Time Measurement

To measure the response time, Fastify provides the getResponseTime method:

const fastify = require('fastify')({});

fastify.get('/', function(req, reply) {

const milliseconds = reply.getResponseTime();

reply.send(milliseconds);

});

const start = async () => {

try {

await fastify.listen(3000, '0.0.0.0');

} catch (err) {

fastify.log.error(err);

process.exit(1);

}

};

start();

By invoking this method within our handler, we can easily track how long it takes to respond.

Setting the Content-Type Header

You can control the Content-Type of the response using the reply.type method:

const fastify = require('fastify')({});

fastify.get('/', function(req, reply) {

reply.type('text/html').send();

});

const start = async () => {

try {

await fastify.listen(3000, '0.0.0.0');

} catch (err) {

fastify.log.error(err);

process.exit(1);

}

};

start();

This method allows you to specify the appropriate Content-Type for your responses.

Sending Raw Responses

Fastify also enables sending raw responses with the reply.raw property:

const fastify = require('fastify')({});

fastify.get('/', function(req, reply) {

reply.setCookie('session', 'value', { secure: false });

reply.raw.writeHead(200, { 'Content-Type': 'text/plain' });

reply.raw.write('ok');

reply.raw.end();

});

const start = async () => {

try {

await fastify.listen(3000, '0.0.0.0');

} catch (err) {

fastify.log.error(err);

process.exit(1);

}

};

start();

Here, we set a cookie, write headers, and finalize the response.

Tracking If a Response is Sent

Fastify allows you to check if a response has already been sent by using the sent property:

const fastify = require('fastify')({});

fastify.get('/', function(req, reply) {

reply.sent = true;

reply.raw.end('hello world');

return Promise.resolve('this will be skipped');

});

const start = async () => {

try {

await fastify.listen(3000, '0.0.0.0');

} catch (err) {

fastify.log.error(err);

process.exit(1);

}

};

start();

Setting reply.sent to true indicates that the response is complete.

Sending a Response

The reply.send method is used to send a structured response:

const fastify = require('fastify')({});

fastify.get('/', function(req, reply) {

reply.send({ hello: 'world' });

});

const start = async () => {

try {

await fastify.listen(3000, '0.0.0.0');

} catch (err) {

fastify.log.error(err);

process.exit(1);

}

};

start();

This method allows you to return a JSON object as the response.

Conclusion

With Fastify, you have the tools to customize various aspects of your server responses, making it a powerful choice for backend development.

Chapter 1: Building a Fullstack Chat Application

In this chapter, we will explore how to create a complete chat application using the MERN stack.

The first video provides a step-by-step guide to building a chat app using MongoDB, Express, React, and Node.js.

Chapter 2: Developing a Simple Game Server

This chapter will cover the creation of a straightforward game server utilizing Unity and Node.js.

The second video discusses how to set up a game server, offering valuable insights into the process.

Share the page:

Twitter Facebook Reddit LinkIn

-----------------------

Recent Post:

Understanding Sudden Relationship Breaks: Insights and Reflections

Explore the reasons behind abrupt relationship endings and their emotional impact, along with insights for personal growth.

Elevate Your Team’s Spirit in Just 5 Minutes: A Management Guide

Discover how a simple five-minute gesture can significantly uplift your team's morale and enhance productivity.

A Unique Therapy Session with a Canine Companion

Discover the unexpected comfort found in a furry friend during a challenging time.