We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Custom Handlers

In the previous exercise, we used the express.static middleware, which serves static files using a built-in handler.

An HTTP handler in Express is typically a function with the following signature:

(req: Request, res: Response) => Promise<void>;

To handle an incoming HTTP request, all a handler function requires is the request object and a response object in order to communicate back to the client.

Assignment

Let's add a readiness endpoint to the Chirpy server! Readiness endpoints are used by external systems to check if our server is ready to receive traffic.

The endpoint should be accessible at the /healthz path.

The endpoint should simply return a 200 OK status code indicating that it has started up successfully and is listening for traffic. The endpoint should return a Content-Type: text/plain; charset=utf-8 header, and the body will contain a message that simply says "OK" (the text associated with the 200 status code).

1. Add the Readiness Endpoint

The Express app object has methods matching the HTTP methods. The parameters are the path and the handler function. Use the .get method to add a handler for the /healthz path.

Import the Express types explicitly: import { Request, Response } from "express";
These are Express's Request/Response objects, which differ from the Fetch API's Response

app.get("/healthz", handlerReadiness);

Your handler should use various methods of the response object to do the following:

Express automatically sets the status code to 200. If you want to change it, you can use the .status method.

2. Update the Static Files Path

Now that we've added a new handler, we don't want potential conflicts with the static files handler. Update the static file serving to use the /app/ path instead of /.

To do this:

app.use("/app", express.static("./src/app"));

Ensure the server handles requests for both the readiness endpoint and static files correctly.

Run and submit the CLI tests.