0
0
NextJSframework~10 mins

Server-side session access 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 session function from the right package.

NextJS
import { [1] } from '@/auth';
Drag options to blanks, or click blank then click option'
ASessionProvider
BgetSession
CuseSession
Dauth
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'useSession' which is a client-side hook.
Importing 'getSession' which is used differently.
Importing 'SessionProvider' which is a React component.
2fill in blank
medium

Complete the code to get the session inside a Next.js server component.

NextJS
export default async function Page() {
  const session = await [1]();
  return <div>{session ? 'Logged in' : 'Not logged in'}</div>;
}
Drag options to blanks, or click blank then click option'
AgetSession
BuseSession
Cauth
DfetchSession
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to use 'useSession' in server components.
Using 'getSession' which is not imported here.
Calling a non-existent 'fetchSession' function.
3fill in blank
hard

Fix the error in this server action that tries to access the session.

NextJS
import { auth } from '@/auth';

export async function action() {
  const userSession = await [1]();
  if (!userSession) throw new Error('No session');
  return userSession.user.email;
}
Drag options to blanks, or click blank then click option'
Aauth
BfetchSession
CuseSession
DgetSession
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'useSession' which is client-only.
Calling 'getSession' without importing it.
Not awaiting the auth function.
4fill in blank
hard

Fill both blanks to create a server component that shows the user's email if logged in.

NextJS
import { [1] } from '@/auth';

export default async function UserEmail() {
  const session = await [2]();
  return <p>{session ? session.user.email : 'Guest'}</p>;
}
Drag options to blanks, or click blank then click option'
Aauth
BgetSession
CuseSession
DSessionProvider
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing 'getSession' import with 'auth' call.
Using 'useSession' which is client-only.
Importing 'SessionProvider' which is a React component.
5fill in blank
hard

Fill all three blanks to create a server action that returns the user's name or 'Anonymous'.

NextJS
import { [1] } from '@/auth';

export async function getUserName() {
  const sess = await [2]();
  return sess?.user?.[3] ?? 'Anonymous';
}
Drag options to blanks, or click blank then click option'
Aauth
BgetSession
Cname
Demail
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'getSession' without importing it.
Accessing 'email' instead of 'name'.
Not using optional chaining for safe access.