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
useRouter to access routing methods like push for redirects.useEffect runs side effects, useRouter is needed to actually change routes.isLoggedIn is false?import { useRouter } from 'next/router';
import { useEffect } from 'react';
export default function Dashboard() {
const router = useRouter();
const isLoggedIn = false;
useEffect(() => {
if (!isLoggedIn) {
router.push('/login');
}
}, [isLoggedIn]);
return <h1>Dashboard</h1>;
}isLoggedIn is false, then calls router.push('/login').import { useRouter } from 'next/router';
import { useEffect } from 'react';
export default function Profile() {
const router = useRouter();
const isAuthorized = false;
if (!isAuthorized) {
router.push('/unauthorized');
}
return <h1>Profile</h1>;
}1. UseWhich combination correctly applies conditional routing best practice?useRouteranduseEffectto check login and redirect client-side.
2. Use Next.js middleware to check authentication before rendering.
3. Render a loading state while checking login status.
4. Avoid rendering protected content until login is confirmed.
Pass the test and this pattern moves unknown