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: