0
0
NextJSframework~5 mins

Client-side session access in NextJS

Choose your learning style9 modes available
Introduction

Client-side session access lets your app remember who the user is while they browse. It helps show personalized info without asking them to log in again.

Show user name or profile picture on the page after login
Keep items in a shopping cart while the user moves between pages
Remember user preferences like theme or language
Control what parts of the page a user can see based on their login status
Syntax
NextJS
import { useSession } from 'next-auth/react';

export default function Component() {
  const { data: session, status } = useSession();

  if (status === 'loading') {
    return <p>Loading...</p>;
  }

  if (!session) {
    return <p>You are not logged in.</p>;
  }

  return <p>Welcome, {session.user.name}!</p>;
}

useSession is a React hook from next-auth that gives you session info on the client side.

The status helps you show loading states or check if the user is logged in.

Examples
Get the session data and print it to the console.
NextJS
const { data: session } = useSession();
console.log(session);
Check if a user is logged in and show their email or a message.
NextJS
if (session) {
  console.log(`User email: ${session.user.email}`);
} else {
  console.log('No user logged in');
}
Show a greeting if logged in, or a prompt to log in if not.
NextJS
return session ? <p>Hello, {session.user.name}</p> : <p>Please log in</p>;
Sample Program

This component uses useSession to get the current user session. It shows a loading message while checking, a message if not logged in, or a welcome message with the user's name if logged in.

NextJS
import { useSession } from 'next-auth/react';

export default function UserGreeting() {
  const { data: session, status } = useSession();

  if (status === 'loading') {
    return <p>Loading session...</p>;
  }

  if (!session) {
    return <p>You are not logged in.</p>;
  }

  return <p>Welcome back, {session.user.name}!</p>;
}
OutputSuccess
Important Notes

Make sure next-auth is set up properly with your authentication provider.

Client-side session access is good for showing info but not for protecting sensitive data. Always check permissions on the server too.

Summary

Client-side session access helps your app remember the user while browsing.

Use the useSession hook from next-auth to get session info.

Show loading, logged-in, or logged-out states based on session status.