How to check if server is online with JavaScript?

Sometimes, we want to check if server is online with JavaScript.

In this article, we’ll look at how to check if server is online with JavaScript.

How to check if server is online with JavaScript?

To check if server is online with JavaScript, we can use the AbortController to cancel the request when the request times out.

For instance, we write:

(async () => {
  const url = 'https://example.com'
  const controller = new AbortController();
  const signal = controller.signal;
  const options = {
    mode: 'no-cors',
    signal
  };
  await fetch(url, options)

  setTimeout(() => {
    controller.abort()
  }, 3000)
})()

to call fetch with a url and options.

options has the signal property assigned to the AbortController instance’s signal property.

Then we call controller.abort to cancel the request to url after 3000 milliseconds by calling it in the setTimeout callback.

If the request is done before 3 seconds, then abort will do nothing.

Conclusion

To check if server is online with JavaScript, we can use the AbortController to cancel the request when the request times out.