0
0
NextJSframework~10 mins

Conditional routes in NextJS - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to import the Next.js router hook.

NextJS
import { [1] } from 'next/navigation';
Drag options to blanks, or click blank then click option'
AuseRouter
BuseRoute
CrouterHook
DuseNavigate
Attempts:
3 left
💡 Hint
Common Mistakes
Using useRoute or useNavigate which are from other frameworks.
2fill in blank
medium

Complete the code to redirect unauthenticated users to the login page.

NextJS
if (!user) {
  router.[1]('/login');
}
Drag options to blanks, or click blank then click option'
Apush
Bredirect
Cnavigate
Dgo
Attempts:
3 left
💡 Hint
Common Mistakes
Using redirect which is a server function, not a router method.
3fill in blank
hard

Fix the error in the conditional route check to correctly protect the page.

NextJS
export default function Page() {
  const router = useRouter();
  const user = getUser();
  if ([1]) {
    router.push('/login');
  }
  return <main>Welcome!</main>;
}
Drag options to blanks, or click blank then click option'
Auser == true
Buser === null
Cuser !== undefined
D!user
Attempts:
3 left
💡 Hint
Common Mistakes
Checking user !== undefined which is true when user exists.
4fill in blank
hard

Fill both blanks to create a conditional rendering that shows login or dashboard links.

NextJS
return (
  <nav>
    {user ? <a href=[1]>Dashboard</a> : <a href=[2]>Login</a>}
  </nav>
);
Drag options to blanks, or click blank then click option'
A"/dashboard"
B"/login"
C"/home"
D"/profile"
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping the URLs or missing quotes around href values.
5fill in blank
hard

Fill all three blanks to create a server component that redirects unauthenticated users and shows content otherwise.

NextJS
import { [1] } from 'next/navigation';

export default function ProtectedPage() {
  const user = getUser();
  if (!user) {
    [2]('/login');
  }
  return <main>Welcome, [3]!</main>;
}
Drag options to blanks, or click blank then click option'
Aredirect
BuseRouter
Cuser.name
Drouter.push
Attempts:
3 left
💡 Hint
Common Mistakes
Using router.push in server components, which is client-only.