Verify the HTTP status of a website from the frontend using JavaScript

Problem Overview

I am developing a web app that requires users to enter URLs in a text box. My goal is to check the HTTP status codes for these URLs directly from the frontend.

Concerns

I’m uncertain about the feasibility of this task due to cross-origin resource sharing (CORS) policies and potential security issues in browsers that might prevent me from accessing the data.

Sample Code

function assessWebsiteStatus(inputUrl) {
    // This represents my intended functionality
    fetch(inputUrl)
        .then(res => {
            console.log('HTTP Status:', res.status);
            return res.status;
        })
        .catch(err => {
            console.log('An error occurred:', err);
        });
}

// Handling user input
document.getElementById('urlInput').addEventListener('blur', function() {
    const enteredUrl = this.value;
    if (enteredUrl) {
        assessWebsiteStatus(enteredUrl);
    }
});

Queries

  • Is it possible to fetch HTTP status codes from websites using pure JavaScript or jQuery?
  • What are the possible solutions to bypass CORS issues when checking if a site is reachable?
  • How can I best ensure that the URL entered by a user is accessible?

Any advice or other approaches would be greatly appreciated. Thank you!

You’re hitting CORS restrictions - browsers block cross-origin requests to random domains. I ran into this same problem when building URL validation. Best solution I found: create a backend proxy. Your frontend sends the URL to your server, your server checks the target site and sends back the status code. No more CORS issues since servers don’t have those browser restrictions. You could use a third-party service instead, but watch out for reliability and rate limits. For basic format checking, just use regex on the frontend before hitting your backend.

have you thought about using a service like cors-anywhere? also, what would happen if a site blocks your requests? and how are you managing timeouts, just checking the status codes?

cors-anywhere is dead - don’t use it anymore. I’ve tried allorigins.win for quick tests, but you really need your own backend. Also heads up - some sites return 200 but block you with JavaScript, so status codes won’t tell you if the site’s actually accessible.