How to redirect user or page in a Next.js Application
Published on:
You may want to redirect a user after a certain action is performed or based on whether the user is authenticated. Here are two simple ways to do it in Next.js.
- Redirection using useRouter (client side redirect)
- Redirection using redirect (server side redirect)
Some of the sample codes have type declarations for TypeScript, but you can omit the type declarations if you are using plain JavaScript.
Client side redirection using useRouter in Next.js
Follow the steps be below:
import {useRouter} from “next/navigation”;
In your function component, add:
const router = useRouter();
Then simply add ‘router.push(“/dashboard”)’ in the relevant part of your code. Eg:
if(isAuthenticated){
router.push(“/dashboard”)
}
How to do server side redirection in Next.js
Redirect was introduced in Next.js 13, and it is my favorite method of redirecting. It seems faster since the code is executed on the server side, and the user barely notices.
The following example would only work in a server component so if you are using it in a client component (with “use client” directive), it wouldn’t work. If you want to use redirect in a client component, you can use it through a server action which I will show you in a bit.
To use redirect directly in a server component, add:
Import {redirect} from “next/navigation”
Then simply invoke ‘redirect(“/dashboard”)’ in the relevant part of your code(not that "/dashboard" is just an example. Change it to the necessary page). Eg:
At the top of your function component, add:
const token = await checkToken();
if (token) {
redirect(“/dashboard”)
}
How to use redirection through a server action in a client component:
Create a server action called redirectAction or any name you want:
// app/actions/redirect-action.ts
“use server”;
import {redirect} from “next/navigation”;
export const redirectAction = async (path: string) => {
redirect(path);
}
Then in your client component, simply import the function (server action) that you just created and use it instead of router. Eg:
import { redirectAction } from @/app/actions/redirect-action/
if(isAuthenticated){
redirect(“/dashboard”)
}
Optionally, you can add a redirect type as a second parameter when using redirect but isn’t necessary in the above examples.
By default, redirect will use push (adds a new entry to the browser history stack) in server actions and replace (replaces the current URL in the browser history stack) elsewhere. You can override this behavior by adding the ‘type’ parameter. Note however that adding the ‘type’ parameter would have no effect in a server component.
To use redirect type, you need to import RedirectType as well. The syntax would look like:
Your import would thus be:
import {redirect, RedirectType} from “next/navigation”;
and the syntax would be. Eg:
redirect(“/dashboard”, RedirectType.replace)