Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

isUrlReachable

Checks whether a given URL is reachable (responds with a successful status).

TypeScript
Copied!
1/**
2 * Checks whether a given URL is reachable (responds with a successful status).
3 *
4 * @param url - The URL to check.
5 * @param timeoutMs - Optional timeout in milliseconds (default: 5000).
6 * @returns Promise resolving to true if reachable, false otherwise.
7 */
8export async function isUrlReachable(url: string, timeoutMs = 5000): Promise<boolean> {
9  try {
10    const controller = new AbortController();
11    const timeout = setTimeout(() => controller.abort(), timeoutMs);
12
13    const response = await fetch(url, {
14      method: 'HEAD',
15      signal: controller.signal,
16    });
17
18    clearTimeout(timeout);
19    return response.ok;
20  } catch {
21    return false;
22  }
23}
  • Non-Intrusive Check

    Uses the HEAD method, which is lightweight and avoids downloading response bodies unnecessarily.

  • Built-In Timeout Support

    Supports a custom timeout via AbortController, preventing long hangs on unresponsive endpoints.

  • Graceful Failure Handling

    Returns false on any error (network failure, timeout, CORS issue), avoiding uncaught exceptions.

  • Promise-Based API

    Designed for asynchronous workflows, making it easy to integrate with await or .then() chains.

Tests | Examples

TypeScript
Copied!
1beforeEach(() => {
2  jest.resetAllMocks();
3  global.fetch = jest.fn();
4});
5
6test('isUrlReachable - resolves true for 200 status', async () => {
7  (fetch as jest.Mock).mockResolvedValue({ ok: true });
8
9  const result = await isUrlReachable('https://example.com');
10  expect(result).toBe(true);
11  expect(fetch).toHaveBeenCalledWith('https://example.com', expect.any(Object));
12});
13
14test('isUrlReachable - resolves false for non-ok response', async () => {
15  (fetch as jest.Mock).mockResolvedValue({ ok: false });
16
17  const result = await isUrlReachable('https://example.com');
18  expect(result).toBe(false);
19});
20
21test('isUrlReachable - resolves false on fetch error', async () => {
22  (fetch as jest.Mock).mockRejectedValue(new Error('Network error'));
23
24  const result = await isUrlReachable('https://example.com');
25  expect(result).toBe(false);
26});
27
28test('isUrlReachable - aborts on timeout', async () => {
29  const abortError = new DOMException('Aborted', 'AbortError');
30  (fetch as jest.Mock).mockImplementation(() =>
31    new Promise((_, reject) => setTimeout(() => reject(abortError), 100))
32  );
33
34  const result = await isUrlReachable('https://example.com', 50);
35  expect(result).toBe(false);
36});

Common Use Cases

  • Validate External Links

    Ensure third-party URLs (e.g., image sources or API endpoints) are reachable before using them.

  • Pre-Fetch Availability Check

    Test server availability before making a full GET or POST request.

  • Monitoring or Health Checks

    Periodically check if a service or page is still online and responsive.

  • Graceful Degradation in UI

    Conditionally render fallback UI when a resource is not available.

Codebase: Utilities -> Network -> isUrlReachable | Yevhen Klymentiev