0
0
NextJSframework~30 mins

Session management in NextJS - Mini Project: Build & Apply

Choose your learning style9 modes available
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
Need a 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
Need a 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
Need a 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
Need a 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.