How to Set Up an Endpoint for Health Check on Next.js – Next.js

Photo of author
Written By M Ibrahim
googlecloudplatform kubernetes next.js reactjs

Deploying an application on Kubernetes requires it to return a 200 status response to certain routes such as “/healthz” and “/”. While setting up such routes on an Express server is straightforward, it may not be clear how to achieve the same on a frontend application built with Next.js and React.

Solution:

Solution 1: Using an API route in Next.js

To set up a health check endpoint in Next.js, you can create a new file called `healthcheck.js` in the `/pages/api` directory. The file should contain the following code:

export default function handler(req, res) {
  res.status(200).json({ "status": "ok" })
}

This code sets up an API route that returns a JSON response with a status of “ok” and a 200 status code.

Solution 2: Using a different file and URL rewrite

Another option is to create a file called `health.js` in the `/pages/api` directory with the following code:

export default function handler(req, res) {
  res.send('OK');
}

In this case, the response is a simple “OK” string. To handle requests to the `/healthz` URL, you can set up a URL rewrite in the `next.config.js` file:

module.exports = {
  async rewrites() {
    return [
      {
        source: '/healthz',
        destination: '/api/health',
      },
    ]
  },
}

This rewrite rule internally redirects requests from `/healthz` to the `/api/health` API route.

Conclusion:

Setting up an endpoint for health check on Next.js is crucial for ensuring the proper functioning of your application in a Kubernetes environment. By using API routes or URL rewrites, you can easily configure your Next.js application to respond with a 200 status code to the required routes. Follow the solutions provided in this article to set up your health check endpoint and ensure your application’s stability.