Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set up an endpoint for Health check on Next.js?

I have an application deployed on Kubernetes (Google cloud). For the deployment to function, it needs to return a 200 status response to "/healthz" and "/". I have this set up on my Express server as a route returning a response like so:

app.use('/healthz', ((_req, res) => {
      logGeneral.info("Health Status check called.");
      res.sendStatus(200);
    }));

But I don't know how to do the same for my frontend which is running on Next.js / React. Commands such as res.send are not supported.

Anyone know?

Thanks.

like image 753
BURGERFLIPPER101 Avatar asked Sep 06 '25 03:09

BURGERFLIPPER101


2 Answers

Using an API route is the correct answer. Create a new file in /pages/api called healthcheck.js with this content:

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

The endpoint will be at (hostname)/api/healthcheck

like image 84
Steve Conrad Avatar answered Sep 07 '25 19:09

Steve Conrad


If you have to use the root path of /healthz, you can add an API route as others here suggested;

// ./pages/api/health.js
export default function handler(req, res) {
  res.send('OK');
}

And additionally you define a rewrite in next.config.js, so /healthz will be handled internally by /api/health;

/** @type {import('next').NextConfig} */
module.exports = {
  rewrites: async () => {
    return [
      {
        source: '/healthz',
        destination: '/api/health',
      },
    ];
  },
};
like image 39
Koen. Avatar answered Sep 07 '25 21:09

Koen.