ELEVATE YOUR BUSINESS WITH

Limitless customization options & Elementor compatibility let anyone create a beautiful website with Valiance.

Redirecting Routes in NextJS

SELECT * FROM `itio_tutorial_master` WHERE `tutorial_menu`='21' AND `tutorial_submenu`='1747' AND `tutorial_status`=1 LIMIT 1

Redirecting Routes in NextJS

🔀 Redirecting Routes in Next.js

Next.js provides built-in route redirection using both static and dynamic redirects. You can define redirects in the next.config.js file or inside API routes and components.


📌 1. Static Redirects (next.config.js)

Use permanent or temporary redirects inside next.config.js.

🔹 Example: Permanent Redirect (301)

javascript

<button onClick={() => router.push("/dashboard")}> Go to Dashboard </button> );}

✅ Redirects to /dashboard on button click


📌 3. Redirects in getServerSideProps() (SSR)

Redirect a user on the server-side before rendering.

🔹 Example: Redirect Unauthorized Users

javascript

export async function getServerSideProps(context) { const isLoggedIn = false; // Replace with actual authentication check if (!isLoggedIn) { return { redirect: { destination: "/login", permanent: false, }, }; } return { props: {} };}

✅ If the user is not logged in, they are redirected to /login


📌 4. Redirects in API Routes (pages/api/)

Redirect inside an API route using res.writeHead().

🔹 Example: API Redirect

javascript

export default function handler(req, res) { res.writeHead(302, { Location: "/new-api-route" }); res.end();}

✅ Redirects the API request to another route


📌 5. Middleware Redirects

Use middleware for condition-based redirection.

🔹 Example: Redirect Non-Authenticated Users

javascript

import { NextResponse } from "next/server";export function middleware(req) { const isLoggedIn = false; // Replace with actual auth check if (!isLoggedIn) { return NextResponse.redirect(new URL("/login", req.url)); }}

✅ Middleware runs before rendering & redirects users accordingly


🚀 Summary: When to Use Each Redirect?

MethodBest ForRedirect Type
next.config.jsPermanent or temporary static redirects301 / 302
useRouter()Client-side navigationPush/Replace
getServerSideProps()Server-side authentication redirects302
API Route (res.writeHead())Redirecting from API responses302
Middleware (NextResponse.redirect())Redirecting before rendering302

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql