0
0
NextJSframework~10 mins

Why authentication matters in NextJS - Test Your Understanding

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 authentication hook.

NextJS
import { [1] } from 'next-auth/react';
Drag options to blanks, or click blank then click option'
AuseSession
BuseAuth
CgetSession
DsignIn
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'useAuth' which is not a Next.js hook.
Confusing 'signIn' with a hook.
2fill in blank
medium

Complete 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'
AuseSession
BgetSession
CsignIn
DuseAuth
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'getSession' which is async and not a hook.
Using 'signIn' which is a function to start login.
3fill in blank
hard

Fix 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'
Anavigate
Bpush
CuseRouter
Dredirect
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'navigate' which is React Router specific.
Using 'push' without router context.
4fill in blank
hard

Fill 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'
AuseSession
Bredirect
CuseRouter
DsignIn
Attempts:
3 left
💡 Hint
Common Mistakes
Importing 'useRouter' instead of 'redirect'.
Using 'signIn' as a redirect function.
5fill in blank
hard

Fill 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'
AuseSession
BsignIn
CsignOut
DgetSession
Attempts:
3 left
💡 Hint
Common Mistakes
Confusing signIn and signOut functions.
Using getSession in client component.