Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Session Management in Next.js
📖 Scenario: You are building a simple Next.js app that needs to remember if a user is logged in or not during their visit. This is like when you log into a website and it keeps you logged in as you browse pages.
🎯 Goal: Create a Next.js app that manages a user session using React state and cookies. The app will let the user log in and log out, and remember their session across page reloads.
📋 What You'll Learn
Create a React state variable to hold the session status
Use a cookie to store the session token
Read the cookie on page load to restore session
Provide buttons to log in and log out that update session state and cookie
💡 Why This Matters
🌍 Real World
Session management is essential for websites that require users to log in and keep their login status while browsing or refreshing pages.
💼 Career
Understanding session management is important for frontend and full-stack developers to build secure and user-friendly web applications.
Progress0 / 4 steps
1
Set up session state
In the page.tsx file, create a React state variable called isLoggedIn using useState and set its initial value to false.
NextJS
Hint
Use const [isLoggedIn, setIsLoggedIn] = useState(false) inside the component.
2
Add cookie helper functions
Below the imports, add two helper functions: setSessionCookie that sets a cookie named session with value 'active', and removeSessionCookie that deletes the session cookie.
NextJS
Hint
Use document.cookie to set and remove cookies with proper path and max-age.
3
Implement login and logout logic
Inside the Page component, add two functions: handleLogin that sets isLoggedIn to true and calls setSessionCookie, and handleLogout that sets isLoggedIn to false and calls removeSessionCookie.
NextJS
Hint
Define handleLogin and handleLogout inside the component to update state and cookies.
4
Restore session on page load and add buttons
Use useEffect inside Page to check if the session cookie exists on page load. If yes, set isLoggedIn to true. Then, add two buttons: one with onClick calling handleLogin labeled "Log In", and another with onClick calling handleLogout labeled "Log Out". Also display a message: "Logged in" if isLoggedIn is true, otherwise "Logged out".
NextJS
Hint
Use useEffect with an empty dependency array to run once on load. Parse document.cookie to find the session cookie. Add buttons with onClick calling your handlers and show login status in a paragraph.
Practice
(1/5)
1. What is the main purpose of session management in Next.js applications?
easy
A. To remember user information between page visits
B. To style components dynamically
C. To optimize image loading
D. To handle API request routing
Solution
Step 1: Understand session management concept
Session management is about keeping track of user data across different pages or visits.
Step 2: Identify the main purpose in Next.js
Next.js uses session management to remember users, so they don't have to log in repeatedly or lose their data.
Final Answer:
To remember user information between page visits -> Option A
Quick Check:
Session management = Remember user info [OK]
Hint: Sessions keep user info across pages and visits [OK]
Common Mistakes:
Confusing session management with styling or routing
Thinking sessions optimize images
Believing sessions handle API routing only
2. Which of the following is the correct way to get the session on the server side in Next.js?
A. Returning props instead of redirect is incorrect
B. Using await without async function
C. Redirect destination should be '/home' not '/login'
D. Missing passing context to getServerSession
Solution
Step 1: Check getServerSession usage
The function getServerSession requires the request context to access cookies and headers, so it needs context.req and context.res or the full context passed.
Step 2: Identify missing argument
The code calls getServerSession() without arguments, which causes it to fail to read session data.
Final Answer:
Missing passing context to getServerSession -> Option D
Quick Check:
getServerSession needs context argument [OK]
Hint: Always pass context to getServerSession on server [OK]
Common Mistakes:
Forgetting to pass context to getServerSession
Confusing async/await usage
Incorrect redirect destination assumptions
5. You want to protect a Next.js page so only logged-in users can access it. Which approach correctly combines server and client session checks?
hard
A. Use getServerSession in the component to check session and redirect if missing.
B. Only use useSession in the component to check if user is logged in and redirect if not.
C. Use getServerSession in getServerSideProps to redirect unauthenticated users, and use useSession in the component to show loading or user info.
D. Use useSession in getServerSideProps to fetch session and redirect unauthenticated users.
Solution
Step 1: Understand server-side protection
Using getServerSession in getServerSideProps allows redirecting users before the page loads if they are not logged in.
Step 2: Understand client-side session usage
Using useSession in the component helps show loading states or user info once the page is loaded.
Step 3: Evaluate options
Use getServerSession in getServerSideProps to redirect unauthenticated users, and use useSession in the component to show loading or user info. correctly combines server-side redirect and client-side session display. The other options misuse server/client functions or locations.
Final Answer:
Use getServerSession in getServerSideProps to redirect unauthenticated users, and use useSession in the component to show loading or user info. -> Option C
Quick Check:
Server redirect + client session hook = Use getServerSession in getServerSideProps to redirect unauthenticated users, and use useSession in the component to show loading or user info. [OK]
Hint: Protect server-side, then show session client-side [OK]