Bird
Raised Fist0
NextJSframework~20 mins

Conditional routes in NextJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Conditional Routing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What will this Next.js route component render when user is not authenticated?

Consider this Next.js page component that conditionally renders content based on authentication status.

import { useState, useEffect } from 'react';

export default function Dashboard() {
  const [isAuthenticated, setIsAuthenticated] = useState(false);

  useEffect(() => {
    // Simulate auth check
    setTimeout(() => setIsAuthenticated(false), 1000);
  }, []);

  if (!isAuthenticated) {
    return <h1>Please log in to access the dashboard.</h1>;
  }

  return <h1>Welcome to your dashboard!</h1>;
}
NextJS
import { useState, useEffect } from 'react';

export default function Dashboard() {
  const [isAuthenticated, setIsAuthenticated] = useState(false);

  useEffect(() => {
    // Simulate auth check
    setTimeout(() => setIsAuthenticated(false), 1000);
  }, []);

  if (!isAuthenticated) {
    return <h1>Please log in to access the dashboard.</h1>;
  }

  return <h1>Welcome to your dashboard!</h1>;
}
AIt first renders nothing, then after 1 second renders 'Please log in to access the dashboard.'.
BIt renders 'Welcome to your dashboard!' immediately and stays that way.
CIt first renders 'Please log in to access the dashboard.', then after 1 second stays the same.
DIt renders 'Please log in to access the dashboard.' immediately and stays that way.
Attempts:
2 left
💡 Hint

Think about the initial state and what the useEffect does after 1 second.

📝 Syntax
intermediate
2:00remaining
Which option correctly implements a conditional redirect in Next.js 14 App Router?

You want to redirect users to '/login' if they are not authenticated inside a server component using Next.js 14 App Router. Which code snippet is correct?

NextJS
import { redirect } from 'next/navigation';

export default function Page() {
  const isAuthenticated = false;

  // Conditional redirect here
}
A
if (!isAuthenticated) {
  redirect('/login');
}
return &lt;h1&gt;Dashboard&lt;/h1&gt;;
B
if (!isAuthenticated) {
  router.push('/login');
}
return &lt;h1&gt;Dashboard&lt;/h1&gt;;
C
if (!isAuthenticated) {
  return redirect('/login');
}
return &lt;h1&gt;Dashboard&lt;/h1&gt;;
D
if (!isAuthenticated) {
  window.location.href = '/login';
}
return &lt;h1&gt;Dashboard&lt;/h1&gt;;
Attempts:
2 left
💡 Hint

Remember that redirect is a function that causes a server-side redirect and does not return JSX.

🔧 Debug
advanced
2:00remaining
Why does this conditional route cause a hydration error in Next.js?

Examine this Next.js page component:

import { useState, useEffect } from 'react';

export default function Profile() {
  const [isLoggedIn, setIsLoggedIn] = useState(null);

  useEffect(() => {
    setIsLoggedIn(true);
  }, []);

  if (isLoggedIn === null) {
    return <div>Loading...</div>;
  }

  if (!isLoggedIn) {
    return <div>Please log in.</div>;
  }

  return <div>Welcome back!</div>;
}

Why might this cause a hydration mismatch error?

NextJS
import { useState, useEffect } from 'react';

export default function Profile() {
  const [isLoggedIn, setIsLoggedIn] = useState(null);

  useEffect(() => {
    setIsLoggedIn(true);
  }, []);

  if (isLoggedIn === null) {
    return <div>Loading...</div>;
  }

  if (!isLoggedIn) {
    return <div>Please log in.</div>;
  }

  return <div>Welcome back!</div>;
}
ABecause conditional rendering inside useEffect is not allowed.
BBecause useEffect runs on server causing state to change before hydration.
CBecause useState cannot be initialized with null in Next.js components.
DBecause the initial render on server is 'Loading...' but client immediately changes to 'Welcome back!', causing mismatch.
Attempts:
2 left
💡 Hint

Think about what the server renders vs what the client renders initially.

❓ state_output
advanced
2:00remaining
What is the output of this Next.js client component with conditional route logic?

Given this component, what will be displayed after 2 seconds?

import { useState, useEffect } from 'react';

export default function Home() {
  const [user, setUser] = useState(null);

  useEffect(() => {
    setTimeout(() => setUser({ name: 'Alice' }), 2000);
  }, []);

  if (!user) {
    return <h2>Redirecting to login...</h2>;
  }

  return <h2>Hello, {user.name}!</h2>;
}
NextJS
import { useState, useEffect } from 'react';

export default function Home() {
  const [user, setUser] = useState(null);

  useEffect(() => {
    setTimeout(() => setUser({ name: 'Alice' }), 2000);
  }, []);

  if (!user) {
    return <h2>Redirecting to login...</h2>;
  }

  return <h2>Hello, {user.name}!</h2>;
}
AImmediately shows 'Hello, Alice!' and never changes.
BImmediately shows 'Redirecting to login...', then after 2 seconds shows 'Hello, Alice!'.
CImmediately shows nothing, then after 2 seconds shows 'Redirecting to login...'.
DImmediately shows 'Redirecting to login...' and stays that way.
Attempts:
2 left
💡 Hint

Consider the initial state and when setUser updates the state.

🧠 Conceptual
expert
2:00remaining
Which statement about conditional routing in Next.js 14 App Router is TRUE?

Choose the correct statement about how conditional routing works in Next.js 14 App Router.

AYou can use the <code>redirect()</code> function inside server components to perform immediate server-side redirects based on conditions.
BClient components can use <code>redirect()</code> to navigate users without page reloads.
CConditional routing must always be handled in middleware, not in components.
DNext.js 14 App Router does not support conditional rendering based on user authentication.
Attempts:
2 left
💡 Hint

Think about where redirect() can be used and what it does.

Practice

(1/5)
1. What is the main purpose of conditional routes in Next.js?
easy
A. To create static pages only
B. To style pages differently
C. To fetch data from an API
D. To control access and redirect users based on conditions

Solution

  1. Step 1: Understand conditional routes concept

    Conditional routes let you decide which users can see certain pages or redirect them elsewhere.
  2. 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.
  3. Final Answer:

    To control access and redirect users based on conditions -> Option D
  4. Quick Check:

    Conditional routes = control access [OK]
Hint: Think: Who should see this page? Redirect if no permission. [OK]
Common Mistakes:
  • Confusing conditional routes with styling or data fetching
  • Thinking conditional routes create static pages
  • Believing conditional routes only fetch data
2. Which Next.js hook is commonly used to perform client-side redirects in conditional routes?
easy
A. useState
B. useEffect
C. useRouter
D. useContext

Solution

  1. Step 1: Identify hooks for routing

    Next.js provides useRouter to access routing methods like push for redirects.
  2. Step 2: Confirm redirect usage

    While useEffect runs side effects, useRouter is needed to actually change routes.
  3. Final Answer:

    useRouter -> Option C
  4. Quick Check:

    Redirects use useRouter [OK]
Hint: Redirects need router methods, so useRouter is key. [OK]
Common Mistakes:
  • Using useState to redirect (it manages state only)
  • Confusing useEffect as the hook that changes routes
  • Thinking useContext handles routing
3. Given this Next.js component, what will happen if 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>;
}
medium
A. The user is redirected to the /login page
B. The page reloads infinitely
C. The page shows an error
D. The user stays on the Dashboard page

Solution

  1. Step 1: Analyze the useEffect condition

    The effect checks if isLoggedIn is false, then calls router.push('/login').
  2. Step 2: Understand router.push behavior

    This causes a client-side redirect to the login page when not logged in.
  3. Final Answer:

    The user is redirected to the /login page -> Option A
  4. Quick Check:

    False login triggers redirect [OK]
Hint: False login triggers router.push to /login. [OK]
Common Mistakes:
  • Thinking the user stays on Dashboard despite redirect
  • Assuming an error occurs without redirect
  • Believing infinite reload happens here
4. Identify the error in this Next.js conditional route code:
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>;
}
medium
A. Calling router.push inside the component body causes an error
B. Missing dependency array in useEffect
C. useRouter is not imported correctly
D. The component returns invalid JSX

Solution

  1. 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.
  2. Step 2: Correct usage with useEffect

    Redirects should be inside useEffect to avoid infinite loops or errors.
  3. Final Answer:

    Calling router.push inside the component body causes an error -> Option A
  4. Quick Check:

    Redirects must be inside useEffect [OK]
Hint: Put router.push inside useEffect, not directly in component body. [OK]
Common Mistakes:
  • Calling router.push directly in component body
  • Ignoring useEffect for side effects
  • Assuming missing import causes error here
5. You want to create a Next.js page that only logged-in users can access. If the user is not logged in, redirect them to '/login'. Which is the best approach?
1. Use useRouter and useEffect to 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.
Which combination correctly applies conditional routing best practice?
hard
A. Only 1 and 2
B. All 1, 2, 3, and 4
C. Only 2 and 4
D. Only 1, 3, and 4

Solution

  1. 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.
  2. Step 2: Consider user experience

    Showing a loading state (3) and avoiding rendering protected content before login confirmation (4) improve UX and prevent flicker.
  3. Step 3: Combine all for best practice

    Using all four ensures secure, smooth conditional routing in Next.js.
  4. Final Answer:

    All 1, 2, 3, and 4 -> Option B
  5. Quick Check:

    Best practice = all steps combined [OK]
Hint: Combine client, server checks and loading states for best routing. [OK]
Common Mistakes:
  • Relying only on client-side redirects
  • Skipping loading states causing flicker
  • Ignoring server-side middleware protection
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard