Redirecting URL

Shilpi Maurya
Frontend Weekly
Published in
2 min readSep 29, 2021

A url redirect is a mechanism that navigates a user from one url or web page to another without them clicking on a link. The redirected page can be on the same server or on a different server.

Types of redirecting:

In JavaScript, the process of redirecting a url could be done on both client-side and server-side.

Redirecting through history API (client-side redirect)

We can use web API’s history API to navigate through the history. For going back and forward in history we can use the following method:

history.back();
// to go back in history by 1 step
history.forward();
// to go forward in history by 1 step
history.go(+2);
// to go forward in history by 2 steps
history.go(-2);
// to go back in history by 2 steps

Manipulate history with pushState()this method allows to add entries to the browser’s session history stack but these entries won’t refresh the page.

history.pushState(data, title, url)
// takes three arguments

The replaceState() method works in a very similar way to pushState() method but it doesn’t add entry to the history stack.

history.replaceState(data, title, url)

Redirecting in SPA’s (Client-side redirect)

In Next.js we can redirect at client side using a hook called useRouter.

import { useRouter } from 'next/router'
import {useEffect} form "react"

const redirecting = () => {
const router = useRouter();
useEffect(() => {
setTimeout(() => {
router.push("/");
}, 3000);
}, []);
};
// This will redirect to a given URL in 3 seconds.

Redirecting through status code (Server-side redirect)

At server-side one can redirect a user to a url through http response. The res.redirect()method helps achieve that, it takes two arguments first is statusCode, another is the url or location to redirect.

res.redirect(statusCode, "url")

3xx status code is for redirecting, 301 redirect tells that the url have been changed permanently while 302 is for temporary url change.

--

--