To handle server redirects after a jQuery AJAX request ($.ajax() / $.get() / $.post()), understand first that browser XMLHttpRequest / fetch automatically follows 301 / 302 / 307 / 308 HTTP redirects to the final destination URL before jQuery’s .done() / success callback runs—so client-side JavaScript cannot read intermediate 30x status codes or Location headers directly during an automatic redirect. When your server / API wants the client to navigate or redirect after an AJAX call (such as session expiry, checkout completion, or auth flows), have the server return a JSON payload (e.g., 200 or 401 with { redirectUrl: "/login" }) or a custom response header (e.g., X-Redirect-Url), and perform window.location.as(redirectUrl) (or window.location.replace(redirectUrl)) inside the jQuery handler.
1. Handling JSON or Header-Driven Redirects in jQuery AJAX
Because XHR follows HTTP 302 redirects transparently and can return HTML (such as a login page) with a final 200 status, explicitly instruct the client via JSON or a custom header whenever an AJAX request should trigger browser navigation:
// Handle an explicit redirect instruction returned by a JSON API in jQuery AJAX
function requestWithRedirectSupport(ajaxOptions) {
if (!ajaxOptions || typeof ajaxOptions !== "object") {
throw new TypeError("Expected ajaxOptions to be a plain configuration object.");
}
if (typeof $ === "undefined" || typeof $.ajax !== "function") {
throw new Error("jQuery $.ajax is not available.");
}
const navigateTo = (rawUrl) => {
if (typeof rawUrl !== "string" || rawUrl.trim().length === 0) {
throw new TypeError("Invalid redirect URL received from server.");
}
const resolvedUrl = new URL(rawUrl.trim(), window.location.origin);
if (resolvedUrl.protocol !== "http:" && resolvedUrl.protocol !== "https:") {
throw new Error(`Blocked unsafe redirect protocol: ${resolvedUrl.protocol}`);
}
window.location.assign(resolvedUrl.href);
};
return $.ajax(ajaxOptions)
.done((data, _textStatus, jqXHR) => {
try {
const headerRedirect = jqXHR?.getResponseHeader?.("X-Redirect-Url");
const bodyRedirect = data && typeof data === "object" ? data.redirectUrl : null;
const targetUrl = headerRedirect || bodyRedirect;
if (targetUrl) {
navigateTo(targetUrl);
}
} catch (error) {
console.error(`Failed to process AJAX redirect: ${error.message}`);
}
})
.fail((jqXHR, textStatus, errorThrown) => {
try {
const responseJson = jqXHR?.responseJSON;
if (responseJson && typeof responseJson.redirectUrl === "string") {
navigateTo(responseJson.redirectUrl);
return;
}
console.error(`AJAX request failed (${textStatus}): ${errorThrown || jqXHR?.status}`);
} catch (error) {
console.error(`Error handling AJAX failure redirect: ${error.message}`);
}
});
}
// Example usage:
// requestWithRedirectSupport({
// url: "/api/session/check",
// method: "GET",
// dataType: "json"
// });
- Validate redirect URLs before navigating: Always resolve against
window.location.originand reject non-HTTP(S) schemes likejavascript:ordata:. - Use
window.location.as(url)to keep history orwindow.location.replace(url)to replace it:replace()prevents users from hitting Back into a stale authenticated/expired state.
2. Detecting Unintended HTML Login Redirects on Session Expiry
A classic pitfall with server-side redirects + AJAX is when an expired session cookie causes the backend/auth middleware to 302-redirect an AJAX call to /login (returning HTML with HTTP 200 after following the redirect), causing dataType: "json" parsing to fail:
// Guard against unexpected HTML login responses when expecting JSON from $.ajax
function fetchJsonOrRedirectOnAuth(url, loginUrl = "/login") {
if (typeof url !== "string" || url.trim().length === 0) {
throw new TypeError("Expected url to be a non-empty string.");
}
if (typeof $ === "undefined" || typeof $.ajax !== "function") {
throw new Error("jQuery $.ajax is not available.");
}
return $.ajax({
url: url.trim(),
method: "GET",
dataType: "json"
}).fail((jqXHR) => {
try {
if (jqXHR && jqXHR.status === 401) {
window.location.assign(loginUrl);
return;
}
const contentType = jqXHR?.getResponseHeader?.("Content-Type") || "";
const looksLikeHtml = contentType.includes("text/html") ||
(typeof jqXHR?.responseText === "string" && jqXHR.responseText.trim().startsWith("<!DOCTYPE"));
if (looksLikeHtml) {
window.location.assign(loginUrl);
}
} catch (error) {
console.error(`Auth redirect check failed: ${error.message}`);
}
});
}
// Example usage:
// fetchJsonOrRedirectOnAuth("/api/account/profile", "/login");
- Return
401/403JSON for API routes instead of302HTML redirects: Gives AJAX clients clear status codes rather than unexpected HTML payloads. - Avoid
dataType: "json"blind assumptions on auth-protected endpoints: CheckjqXHR.statusand responseContent-Typewhen session expiration can occur.
3. CORS and Same-Origin Constraints on Redirect Targets
When an AJAX request triggers a cross-origin redirect (for example, from https://app.example.com to https://auth.example.com or a CDN/storage URL), every hop in the redirect chain must satisfy CORS (Access-Control-Allow-Origin, Access-Control-Allow-Credentials), or the browser blocks the response:
- Cross-origin
302chains fail if any target origin lacks CORS headers: Even if the initial request URL allows CORS, a redirected destination that omitsAccess-Control-Allow-Origintriggers a CORS error in the browser. - Prefer same-origin redirect instructions (
{ "redirectUrl": "/dashboard" }) for full-page navigation: Let the browser perform a standard top-level navigation after receiving the JSON response rather than chaining cross-origin XHR redirects. - Never trust arbitrary open redirects from untrusted parameters: Ensure server-side
redirectUrlvalues are allow-listed or relative paths on your own domain.
