3 min read
ā¢Question 13 of 47easyHow to handle redirects in Next.js?
Configuring redirects and rewrites.
What You'll Learn
- Config redirects
- Programmatic redirects
- Permanent vs temporary
next.config.js Redirects
code.jsJavaScript
// next.config.js
module.exports = {
async redirects() {
return [
{
source: '/old-page',
destination: '/new-page',
permanent: true, // 308 status
},
{
source: '/blog/:slug',
destination: '/posts/:slug',
permanent: false, // 307 status
},
{
// Regex support
source: '/docs/:path((?!api).*)',
destination: '/documentation/:path',
permanent: true,
},
];
},
};Programmatic Redirect
code.txtTSX
// In Server Component
import { redirect } from 'next/navigation';
async function checkAuth() {
const user = await getUser();
if (!user) {
redirect('/login');
}
}
// In Route Handler
import { redirect } from 'next/navigation';
export async function GET() {
redirect('/dashboard');
}Client-Side Redirect
code.txtTSX
'use client';
import { useRouter } from 'next/navigation';
export default function LoginButton() {
const router = useRouter();
const handleLogin = async () => {
await login();
router.push('/dashboard');
// or router.replace('/dashboard');
};
}