Oscar
Oscar

Reputation: 590

Can I be sure that the application/json header is only set on ajax requests?

I need to distinguish browser requests from ajax requests and can see that when making a request via a form submission in regular HTML, I get the following value for the accept header:

text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7

Whereas with my ajax request I get:

application/json

Here is the code for my ajax request:

fetch("/auth/login", {
    method: "POST",
    headers: {
        "Accept": "application/json",
        "Content-Type": "application/json",
    },
    body: JSON.stringify({
        email: emailInput.value,
        pword: pwordInput.value,
    }),
});

This means that on my server I can do a check like:

if (!req.headers.accept.includes("application/json")) {
    req.flash("loginError", "Please enable JavaScript or use a browser that supports JavaScript to continue.");
    return res.redirect("/auth/login");
}

However, my question is if this a reliable strategy accross all browsers/versions to distinguish ajax requests from javascript and browser requests or if i should do something else? Is it consistent what the accept header will look like for all browser requests or could it be that a browser will include the application/json inside the accept header as well making my strategy not work?

Upvotes: 0

Views: 35

Answers (0)

Related Questions