📌 Introduction
A redirect in JavaScript means sending the user from one URL to another. 🌐 This is commonly used for navigation, login flows, or when a page has moved to a new location.
⚙️ Redirect with window.location.href
Using href
// Redirect to another page
window.location.href = "https://example.com";This method replaces the current page with the new one. Users can still go back using the browser’s back button. 🔙
⚡ Redirect with window.location.replace()
Using replace
// Redirect to another page without keeping history
window.location.replace("https://example.com");replace() redirects the user but does not save the current page in the browser history. This means the back button won’t take them back. 🚫
⏱️ Redirect with setTimeout
Delayed Redirect
// Redirect after 3 seconds
setTimeout(function() {
window.location.href = "https://example.com";
}, 3000);Useful when you want to show a message (like "Redirecting...") before sending users to a new page. ⏳
🧭 Redirect with window.location.assign()
Using assign
// Redirect using assign
window.location.assign("https://example.com");assign() is similar to href. It saves the current page in the history, allowing users to navigate back. 🔙
📋 Comparison Table
| Method | Back Button Works? | Use Case |
|---|---|---|
| location.href | ✅ Yes | Normal navigation |
| location.replace() | ❌ No | Login/logout flows, security redirects |
| location.assign() | ✅ Yes | Alternative to href with history support |
| setTimeout + href | ✅ Yes | Delayed redirects |
⚠️ Notes
Note
- Never use redirects for sensitive actions (like payments). 🔐
- Search engines may treat client-side redirects differently than server-side ones.
- For SEO-critical pages, use server-side redirects (301/302) instead of JavaScript.
🌟 Conclusion
Redirects in JavaScript can be done using href, replace(),assign(), or even setTimeout. Each method has its own use case depending on whether you want to preserve history or not. 🚀
Learn more on MDN