How to edit response information in Fastify

I will show you how to modify the response information with Fastify. I will also post the code on Git Hub, so please refer to it.

overview

Fastify handles requests in handler functions. A request object and a reply object are passed as arguments to the handler function. You use these objects to retrieve data related to requests, generate responses, and so on.

Here’s how to fix response information in Fastify, using the following versions:

Fastify v4.0.0
nodejs v19.7.0

Also, all the code I’ve created so far is listed below. https://github.com/wiblok/Fastify

How to edit response information

A response object is used to construct the response to the client. Used in fastify route handlers to set response headers, status codes, data, etc.

The sample code below is an example for understanding the response object (reply object) in Fastify. It takes GET requests and generates and returns different kinds of responses.

response.js

const fastify = require("fastify")();

fastify.get("/", async (request, reply) => {
  // Generate JSON response
  const jsonResponse = {
    message: "This is a JSON response",
  };
  reply.send(jsonResponse);
  // Generate HTML response
  const htmlResponse = "<h1>This is an HTML response</h1>";
  reply.type("text/html").send(htmlResponse);
  // setting response headers
  reply.header("Custom-Header", "Custom Value");
  // set status code
  reply.status(201).send("Created");
  // perform redirect
  reply.redirect("/new-location");
  // Generate error response
  const errorResponse = {
    error: "An error occurred",
  };
  reply.status(500).send(errorResponse);
});

fastify.listen({ port: 3000 }, (err) => {
  if (err) {
    console.error("Error starting server:", err);
    process.exit(1);
  }
  console.log("Server started on port 3000");
});

Commentary

  • Create a Fastify instance
const fastify = require("fastify")();

Import the Fastify module and create an instance of it.

  • Generate JSON response
fastify.get("/json", async (request, reply) => {
  const jsonResponse = {
    message: "This is a JSON response",
  };
  reply.send(jsonResponse);
});

Handles GET requests to the path /json. When a request comes in, it generates and returns a JSON formatted response.

  • generate HTML response
fastify.get("/html", async (request, reply) => {
  const htmlResponse = "<h1>This is an HTML response</h1>";
  reply.type("text/html").send(htmlResponse);
});

Handles GET requests to the path /html. When a request comes in, it generates and returns an HTML formatted response.

  • Setting response headers
fastify.get("/header", async (request, reply) => {
  reply.header("Custom-Header", "Custom Value").send("Header set");
});

Handles GET requests to the path /header. When a request comes in, set the response headers and return the response.

  • Set status code
fastify.get("/status", async (request, reply) => {
  reply.status(201).send("Created");
});

Handles GET requests to the path /status. When a request comes in, set the status code and return the response.

  • Execute redirect
fastify.get("/redirect", async (request, reply) => {
  reply.redirect("/new-location");
});

Handles GET requests to the path /redirect. When a request comes in, do a redirect.

  • generate error response
fastify.get("/error", async (request, reply) => {
  const errorResponse = {
    error: "An error occurred",
  };
  reply.status(500).send(errorResponse);
});

Handles GET requests to the path /error. When a request comes in, generate and return an error response.

  • Start server
fastify.listen({ port: 3000 }, (err) => {
  if (err) {
    console.error("Error starting server:", err);
    process.exit(1);
  }
  console.log("Server started on port 3000");
});

Start the server with an instance of Fastify listening on port 3000. If any error occurs, print the error message to the console and terminate the process. If there are no errors, print the message “Server started on port 3000” to the console.

test

# test the JSON response
curl -X GET http://localhost:3000/json
# test the HTML response
curl -X GET http://localhost:3000/html
# test response headers
curl -X GET http://localhost:3000/header -I
# test status code
curl -X GET http://localhost:3000/status -I

summary

Using response objects (reply objects) allows you to:

  • You can set or change response headers.
  • You can set the HTTP status code of the response.
  • You can set the body data of the response. It can return data in the form of JSON objects, strings, binary data, etc.
  • You can set response encoding and compression.
  • It is possible to control responses according to specific situations, such as redirects and error handling.

Response objects allow you to perform various operations related to response generation within your Fastify application. Response objects have many properties and methods that allow for a high degree of customization and control.