
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)
<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
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
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
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?
Method | Best For | Redirect Type |
---|---|---|
next.config.js | Permanent or temporary static redirects | 301 / 302 |
useRouter() | Client-side navigation | Push/Replace |
getServerSideProps() | Server-side authentication redirects | 302 |
API Route (res.writeHead() ) | Redirecting from API responses | 302 |
Middleware (NextResponse.redirect() ) | Redirecting before rendering | 302 |