Search code examples
reactjsjsonhttp-headershealth-check

How to make simple health check page for a reactJS app?


I'd like to make a simple healthcheck url for my reactJs application. So simple that I'd just like to make a page that returns status OK, which is hardcoded, since the goal is to just load a simple page with no other styles or scripts to load the page as fast as possible. So far I have achieved that, but what intrigues me is that healthcheck page should return a json output, like {healthcheck: ok} or {status:200}, and if I check the headers content type it should be application/json. Can anyone please give me idea to achieve that in reactJS?

This is how I simply display a status message. If this simple page loads then of course the server is working right?

const HealthCheck = () => {
  return (
    <>
      status: 200
      <br />
      environment: {process.env.NODE_ENV}
    </>
  )
}

export default HealthCheck

Then I have another way like this, to attempt to change the content-type in the headers to content type application/json instead of text/html. But it did not work, it's still text/html.

const HealthCheck = () => {

  var response = {}
  response['status'] = 200
  response['environment'] = process.env.NODE_ENV

  return JSON.stringify(response)
}

export default HealthCheck

Making this page returns status 200 and as application/json in the content type in the network tab is what I need to achieve. A the same time also display the json string in the healthcheck page itself.


Solution

  • You can't achieve this using React DOM on the client alone, because this renderer requires an HTML DOM, which only works if your client is responding with an HTML MIME type.

    The solution would be to have a server with an API endpoint that responds with JSON, which you could then use with or without React. Here are some examples of approaches using different servers:

    Node

    import http from "http"
    
    http
      .createServer((req, res) =>
        res
          .writeHead(200, { "Content-Type": "application/json" })
          .end(JSON.stringify(process.env.NODE_ENV)),
      )
      .listen()
    

    Remix and Node

    import { json } from "@remix-run/node"
    
    export function loader() {
      return json(process.env.NODE_ENV, 200)
    }
    

    Next

    export default function handler(req, res) {
      res.status(200).json(process.env.NODE_ENV)
    }