Authentication helps confirm who you are when using a website or app. It keeps your information safe and private.
Why authentication matters in NextJS
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
NextJS
import { useSession, signIn, signOut } from 'next-auth/react'; function Component() { const { data: session } = useSession(); if (session) { return ( <> <p>Welcome, {session.user.name}!</p> <button onClick={() => signOut()}>Sign out</button> </> ); } return <button onClick={() => signIn()}>Sign in</button>; }
This example uses next-auth, a popular authentication library for Next.js.
useSession hook checks if the user is logged in or not.
Examples
NextJS
import { useSession } from 'next-auth/react'; function Greeting() { const { data: session } = useSession(); return <p>{session ? `Hello, ${session.user.email}` : 'Please sign in'}</p>; }
NextJS
import { signIn } from 'next-auth/react'; export default function SignInButton() { return <button onClick={() => signIn('github')}>Sign in with GitHub</button>; }
Sample Program
This component shows a welcome message and sign out button if the user is logged in. Otherwise, it shows a sign in button.
NextJS
import { useSession, signIn, signOut } from 'next-auth/react'; export default function AuthExample() { const { data: session } = useSession(); if (session) { return ( <main> <h1>Welcome, {session.user.name}!</h1> <p>You are signed in.</p> <button onClick={() => signOut()}>Sign out</button> </main> ); } return ( <main> <h1>You are not signed in.</h1> <button onClick={() => signIn()}>Sign in</button> </main> ); }
Important Notes
Always protect sensitive pages by checking authentication on the server or client.
Use secure cookies and HTTPS to keep user data safe.
Make sure to handle loading states when checking if a user is signed in.
Summary
Authentication confirms who a user is and protects their data.
Next.js apps use libraries like next-auth to handle authentication easily.
Always check if a user is signed in before showing private content.
Practice
1. Why is authentication important in a Next.js application?
easy
Solution
Step 1: Understand the purpose of authentication
Authentication is used to confirm who a user is when they access an app.Step 2: Recognize the importance of protecting data
It helps protect private or sensitive data by allowing only authorized users to see it.Final Answer:
It confirms the identity of users and protects private data. -> Option CQuick Check:
Authentication = Confirm identity and protect data [OK]
Hint: Authentication means confirming who the user is [OK]
Common Mistakes:
- Confusing authentication with app speed
- Thinking authentication changes UI colors
- Believing authentication fixes code bugs
2. Which of the following is the correct way to import the NextAuth library in a Next.js app?
easy
Solution
Step 1: Identify the ES module import syntax
Next.js uses ES module syntax withimportto load libraries.Step 2: Match the correct import statement
The correct import isimport NextAuth from 'next-auth';with exact casing and syntax.Final Answer:
import NextAuth from 'next-auth'; -> Option DQuick Check:
Use ES module import syntax for NextAuth [OK]
Hint: Use ES module import, not require or include [OK]
Common Mistakes:
- Using CommonJS require instead of import
- Wrong casing in import statement
- Using include which is not valid in JS
3. Given this Next.js code snippet using next-auth, what will be rendered if the user is not signed in?
import { useSession } from 'next-auth/react';
export default function Profile() {
const { data: session } = useSession();
if (!session) {
return <p>Please sign in to view your profile.</p>;
}
return <p>Welcome, {session.user.name}!</p>;
}medium
Solution
Step 1: Check the session state when user is not signed in
If the user is not signed in,sessionwill benullorundefined.Step 2: Follow the conditional rendering logic
The code returns the message<p>Please sign in to view your profile.</p>when!sessionis true.Final Answer:
Please sign in to view your profile. -> Option AQuick Check:
Not signed in = show sign-in prompt [OK]
Hint: If no session, show sign-in message [OK]
Common Mistakes:
- Assuming user name shows without sign-in
- Expecting loading text instead of sign-in prompt
- Thinking an error will be thrown
4. What is wrong with this Next.js authentication check?
import { useSession } from 'next-auth/react';
export default function Dashboard() {
const session = useSession();
if (!session) {
return <p>Access denied.</p>;
}
return <p>Dashboard content</p>;
}medium
Solution
Step 1: Check how useSession is used
useSession returns an object with adataproperty containing the session info.Step 2: Identify the correct destructuring
The code should useconst { data: session } = useSession();to get the session data.Final Answer:
useSession must be destructured to get data property. -> Option BQuick Check:
Destructure useSession to access session data [OK]
Hint: Destructure useSession to get session data [OK]
Common Mistakes:
- Using useSession without destructuring
- Trying to put return inside useEffect
- Thinking class components are required
- Using var instead of const or let
5. You want to protect a Next.js page so only signed-in users can access it. Which approach correctly enforces this using next-auth?
hard
Solution
Step 1: Understand server-side protection
UsinggetServerSidePropsallows checking the session before rendering the page.Step 2: Redirect unauthorized users
If no session is found, redirecting to sign-in page prevents unauthorized access securely.Final Answer:
Use getServerSideProps to check session and redirect if not signed in. -> Option AQuick Check:
Server-side session check = secure page protection [OK]
Hint: Check session server-side to protect pages [OK]
Common Mistakes:
- Hiding content with CSS does not secure data
- Using client-side delay risks exposing content
- Allowing access and just showing alerts is insecure
