Discover how to keep your app secure and smooth without messy code everywhere!
Why Conditional routes in NextJS? - Purpose & Use Cases
Imagine building a website where some pages should only be seen by logged-in users, and others by guests. You try to check user status on every page manually and redirect them yourself.
Manually checking user status and redirecting on every page is tiring and easy to forget. It leads to bugs where users see pages they shouldn't or get stuck in loops. It also clutters your code with repeated checks everywhere.
Conditional routes let you define rules once that control who can see which pages. The framework handles the checks and redirects automatically, keeping your code clean and your app secure.
if (!user) { router.push('/login') } // on every page
export const routes = [{ path: '/dashboard', authRequired: true }]; // centralized rulesConditional routes make it easy to control access and navigation based on user state, improving security and user experience.
A shopping site shows the cart page only to logged-in users and redirects guests to sign in automatically.
Manual route checks are repetitive and error-prone.
Conditional routes centralize access control logic.
This leads to cleaner code and safer navigation.
Practice
Solution
Step 1: Understand conditional routes concept
Conditional routes let you decide which users can see certain pages or redirect them elsewhere.Step 2: Identify the purpose in Next.js
Next.js uses conditional routes mainly to protect pages or redirect users based on login or roles.Final Answer:
To control access and redirect users based on conditions -> Option DQuick Check:
Conditional routes = control access [OK]
- Confusing conditional routes with styling or data fetching
- Thinking conditional routes create static pages
- Believing conditional routes only fetch data
Solution
Step 1: Identify hooks for routing
Next.js providesuseRouterto access routing methods likepushfor redirects.Step 2: Confirm redirect usage
WhileuseEffectruns side effects,useRouteris needed to actually change routes.Final Answer:
useRouter -> Option CQuick Check:
Redirects use useRouter [OK]
- Using useState to redirect (it manages state only)
- Confusing useEffect as the hook that changes routes
- Thinking useContext handles routing
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>;
}Solution
Step 1: Analyze the useEffect condition
The effect checks ifisLoggedInis false, then callsrouter.push('/login').Step 2: Understand router.push behavior
This causes a client-side redirect to the login page when not logged in.Final Answer:
The user is redirected to the /login page -> Option AQuick Check:
False login triggers redirect [OK]
- Thinking the user stays on Dashboard despite redirect
- Assuming an error occurs without redirect
- Believing infinite reload happens here
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>;
}Solution
Step 1: Check where router.push is called
router.push is called directly inside the component body, which runs on every render and is not allowed.Step 2: Correct usage with useEffect
Redirects should be inside useEffect to avoid infinite loops or errors.Final Answer:
Calling router.push inside the component body causes an error -> Option AQuick Check:
Redirects must be inside useEffect [OK]
- Calling router.push directly in component body
- Ignoring useEffect for side effects
- Assuming missing import causes error here
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.
Solution
Step 1: Understand client-side and server-side checks
Client-side redirect with useRouter/useEffect (1) is common, but middleware (2) adds server-side protection.Step 2: Consider user experience
Showing a loading state (3) and avoiding rendering protected content before login confirmation (4) improve UX and prevent flicker.Step 3: Combine all for best practice
Using all four ensures secure, smooth conditional routing in Next.js.Final Answer:
All 1, 2, 3, and 4 -> Option BQuick Check:
Best practice = all steps combined [OK]
- Relying only on client-side redirects
- Skipping loading states causing flicker
- Ignoring server-side middleware protection
Ready to prove it?
Pass the test and this pattern moves unknown
