The redirect function helps you send users to a different page automatically. It makes navigation smooth and controls where users go next.
0
0
Redirect function in NextJS
Introduction
After a user logs in, send them to their dashboard.
If a page is moved, redirect visitors to the new page.
Block access to a page and send users to a login page.
After submitting a form, redirect to a thank you page.
Syntax
NextJS
import { redirect } from 'next/navigation'; redirect('/target-path');
Use this inside server components or server actions in Next.js 14+.
The argument is the URL path where you want to send the user.
Examples
This redirects the user immediately to the '/home' page when this component runs.
NextJS
import { redirect } from 'next/navigation'; export default function Page() { redirect('/home'); }
Redirects the user to '/thank-you' after a form is submitted using a server action.
NextJS
import { redirect } from 'next/navigation'; export async function POST() { // After form submission redirect('/thank-you'); }
Sample Program
This page checks if the user is logged in. If not, it sends them to the login page. Otherwise, it shows a welcome message.
NextJS
import { redirect } from 'next/navigation'; export default function Page() { // Redirect to login if user is not authenticated const isAuthenticated = false; if (!isAuthenticated) { redirect('/login'); } return <h1>Welcome to your dashboard</h1>; }
OutputSuccess
Important Notes
The redirect function stops the current page from rendering and sends the user to the new URL immediately.
Use redirect only in server components or server actions, not in client components.
Redirect paths can be absolute URLs or relative paths within your app.
Summary
The redirect function sends users to a different page automatically.
Use it to control navigation after actions like login or form submission.
Works only in server components or server actions in Next.js 14+.