Junior
How to redirect a user to a specified URL?
sobes.tech AI
Answer from AI
// The simplest way, completely replaces the current page
window.location.replace('https://example.com');
// Navigate with history preservation (can go back)
window.location.href = 'https://example.com';
// Or equivalent
window.location.assign('https://example.com');
For SPAs (single-page applications), use the History API:
// Change URL without reloading the page (for routing in SPA)
history.pushState(null, '', '/new-url');
// Replace current history state (for routing in SPA)
history.replaceState(null, '', '/another-url');
On server-side code (e.g., Node.js with Express):
// Redirect on server
res.redirect('/new-path');