2024-08-01

Sometimes after an action is performed we want a user to be automatically redirected to a different webpage.

Blog post by MF Mabala

Redirecting a user to a different webpage: Next.js

In programming there are a lot of languages that can be used when writing code. In this blog I will be showing you how to redirect a user to another web page using JavaScript/ TypeScript.

There are a lot of reasons why we would like to redirect a user for example. We have a signup form that we would like a user to fill in and submit . After they have signed up we want to take them to our login page so that they are able to interact with other features of our app.

Explaining the method we will use in this blog

location.reload()

This method is used to reload the current document. It's part of the window.location object, which represents the current URL of the document that is being displayed in the browser.

window.location.reload()

Above is the syntax we use when utilizing this method. The reason we reload is used is because when we develop an app, blog or web we may want to reload a page after an action. The information may change after certain actions. After a reload the new or changed information will appear.

In the code below I will show you how I redirect users to a new page


import { usePathname, useRouter } from 'next/navigation';

export function AcceptInvite() {
  const router = useRouter();
  const pathname = usePathname();
  const {
  } = ({
    onCompleted: () => {
      const route = '/login';
      if (pathname === route) {
        return window.location.reload();
      }
      return router.push(route);
    },
  });
  
  return ();
}

Lets say when an action completes we want the user to be redirected. Now You will define the onComplete in your hooks accordingly. This is a Component and we start by importing usePathname and useRouter from next-navigation. Our Project is a next.js project. We then declare our constants.

usePathname is a Client Component hook that lets you read the current URL's pathname.

The useRouter hook allows you to programmatically change routes inside client components.

Inside our onComplete we will set our route to where we want the page to be redirected. Then If the pathname equals to the route we want the page to reload meaning it will return the same page the user is on otherwise we want to redirect to our set route. This is how the above code works.

There are a lot lot of ways we can redirect users to other pages and you can explore that on your own there are a lot of resources online.

Thank you for reading my blog