Skip to content

Instantly share code, notes, and snippets.

@ShilpiMaurya
Last active Sep 11, 2021
Embed
What would you like to do?

Redirects

What is a redirect?

  • A url redirect is a process that navigates a user from one url to another
  • Sometimes we need to redirect a user to a different page in our website without them clicking on a link

Types of redirecting :

Redirecting through history api (Client-side redirect)

  • We can use javascript to navigate through the history
  • For going back and forward in history we can use following method
history.back();
history.forward();
history.go(+1); // to go forward in history by 1 step
history.go(-1); // to go back in history by 1 step
  • Manipulate history with pushState()
// add entries to the browser's session history stack
// Will take three arguments (state, title, url)

history.pushState(null, null, "about")

// This will take you to about page

Redirecting in SPA's (Client-side redirect)

  • In nextjs we can redirect throught 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 the user to home page after 3 sec

Redirecting through status code (Server-side redirect)

  • In server-side with can redirect a user to a url through response
res.redirect(statusCode, "url")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment