Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to import the Next.js authentication hook.
NextJS
import { [1] } from 'next-auth/react';
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'useAuth' which is not a Next.js hook.
Confusing 'signIn' with a hook.
✗ Incorrect
The useSession hook is used to access authentication status in Next.js apps.
2fill in blank
mediumComplete the code to check if a user is authenticated.
NextJS
const { data: session } = [1]();
if (session) {
// user is authenticated
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'getSession' which is async and not a hook.
Using 'signIn' which is a function to start login.
✗ Incorrect
useSession() returns session data and status for authentication.
3fill in blank
hardFix the error in the code to redirect unauthenticated users.
NextJS
if (!session) { [1]('/api/auth/signin'); }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'navigate' which is React Router specific.
Using 'push' without router context.
✗ Incorrect
In Next.js server components, redirect() is used to send users to login.
4fill in blank
hardFill both blanks to create a protected page that redirects unauthenticated users.
NextJS
"use client"; import { [1] } from 'next-auth/react'; import { [2] } from 'next/navigation'; export default function Page() { const { data: session } = [1](); if (!session) [2]('/api/auth/signin'); return <main>Welcome, authenticated user!</main>; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Importing 'useRouter' instead of 'redirect'.
Using 'signIn' as a redirect function.
✗ Incorrect
useSession gets the session data, and redirect sends unauthenticated users to sign in.
5fill in blank
hardFill all three blanks to implement a client component that shows login status and a sign out button.
NextJS
"use client"; import { [1], [2], [3] } from 'next-auth/react'; export default function AuthStatus() { const { data: session } = [1](); if (!session) return <button onClick={() => [3]()}>Sign In</button>; return ( <> <p>Signed in as {session.user.email}</p> <button onClick={() => [2]()}>Sign Out</button> </> ); }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Confusing
signIn and signOut functions.Using
getSession in client component.✗ Incorrect
useSession accesses session data, signOut logs out, and signIn starts login.