How would you conditionally redirect users based on something dynamic, like whether they are logged in, rather than a fixed rule in next.config.js?
Short answer
Since the redirects function in next.config.js only supports static, build time rules, you use middleware instead for conditional redirects that depend on runtime information like cookies or headers, checking the condition and returning a redirect response only when it applies.
Advertisement
AModel answer
Since the redirects function in next.config.js only supports static, build time rules, you use middleware instead for conditional redirects that depend on runtime information like cookies or headers, checking the condition and returning a redirect response only when it applies.
// middleware.js
import { NextResponse } from 'next/server';
export function middleware(request) {
const isLoggedIn = request.cookies.has('session');
if (!isLoggedIn && request.nextUrl.pathname.startsWith('/dashboard')) {
return NextResponse.redirect(new URL('/login', request.url));
}
}Real-world example
An application redirects visitors trying to access the dashboard to the login page only if they do not have a valid session cookie, a decision that can only be made at request time using middleware.
Likely follow-ups
- Why can't this kind of conditional logic be handled in the static redirects configuration?
- How do you avoid redirect loops when combining middleware with static redirects?
Related topics