Meta Refresh and JavaScript Redirect Guide

Contents

Server-side redirects (301/302) are always the right first choice. But sometimes you can't touch the server config, or you need to redirect based on runtime conditions โ€” that's where client-side redirects come in.

HTML meta refresh

<!-- Redirect immediately -->
<meta http-equiv="refresh" content="0; url=/new-page.html">

<!-- Redirect after 3 seconds -->
<meta http-equiv="refresh" content="3; url=https://newdomain.com">

โš ๏ธ Back-button trap

Meta refresh adds the current page to browser history before redirecting. When users hit Back, they land on the redirecting page again and get sent forward immediately. Avoid this pattern whenever possible.

JavaScript redirect methods

window.location.href (most common)

// Adds current page to history โ€” user can go back
window.location.href = 'https://example.com';

location.replace() (no history entry)

// Replaces current history entry โ€” user cannot go back
location.replace('https://example.com');

location.assign() (same as href)

location.assign('https://example.com');

window.open() (new tab)

window.open('https://example.com', '_blank');

Key differences

History entry

Cancellable

When to use each

Use meta refresh when

Use location.href when

if (!user.isLoggedIn) {
    location.href = '/login';
}

Use location.replace() when

if (/Android|iPhone/i.test(navigator.userAgent)) {
    location.replace('/mobile/');
}

SEO impact

๐Ÿšจ Important

For any permanent URL change, always use a server-side 301 redirect. Client-side redirects are for dynamic, runtime scenarios only.

Common pitfalls

Code after redirect still executes

// โŒ Code below still runs
if (needRedirect) { location.href = '/other'; }
doSomethingElse(); // still executes!

// โœ… Use return
if (needRedirect) { location.href = '/other'; return; }
doSomethingElse();

Mobile redirect loop

// โœ… Guard against re-redirecting
if (isMobile && !location.pathname.startsWith('/mobile/')) {
    location.replace('/mobile' + location.pathname);
}

Lost query string

// โŒ Query string dropped
location.href = '/new-page';

// โœ… Preserve it
location.href = '/new-page' + location.search;