Concept Flow - Conditional routes
User requests URL
Check route condition
Render route
Display page
When a user visits a URL, Next.js checks if the route condition is met. If yes, it renders the page; if no, it redirects or shows a fallback.
import { useRouter } from 'next/router'; import { useEffect } from 'react'; export default function Page() { const router = useRouter(); const isLoggedIn = false; useEffect(() => { if (!isLoggedIn) { router.push('/login'); } }, [isLoggedIn, router]); if (!isLoggedIn) { return null; } return <div>Protected Content</div>; }
| Step | Action | Condition Checked | Result | Route Rendered or Redirected |
|---|---|---|---|---|
| 1 | User visits /protected | isLoggedIn === false | True | Redirect to /login |
| 2 | Router pushes /login | N/A | N/A | Render /login page |
| 3 | User visits /protected again | isLoggedIn === false | True | Redirect to /login |
| 4 | User logs in and visits /protected | isLoggedIn === false | False | Render /protected page |
| Variable | Start | After Step 1 | After Step 4 |
|---|---|---|---|
| isLoggedIn | false | false | true |
| Current Route | /protected | /login | /protected |
Conditional Routes in Next.js: - Check user or app state in component - If condition fails, use router.push() to redirect - Otherwise, render the protected page - Prevent infinite redirects by guarding router.push - Useful for auth, feature flags, or role-based pages