Reading Session and User Data
The Descope Next.js SDK provides utilities for retrieving user session data in both the App Router (app/) and Pages Router (pages/).
This guide covers:
- Accessing session data on the client
- Retrieving session data on the server
- Differences between App Router and Pages Router
- When to use
session()vs.getSession(req) - Using
createSdk()for backend authentication
Client Side
The Descope SDK provides hooks to access session/user data in client components. For more details, visit our Auth Helpers page.
Displaying Logged-in User Information
Server Side
Session data can be retrieved inside API routes, Middleware, and Server Components using session() or getSession(req).
Comparison of Methods
| Function | Use Case | Works in Middleware? | Works in API Routes? | Works in Server Components? |
|---|---|---|---|---|
session() | App Router, Middleware, Server Components | Yes | Yes | Yes |
getSession(req) | Pages Router API routes | No | Yes | No |
Using session() in Middleware and App Router
The session() function reads session data from cookies and headers.
Protecting a Server Component
- Works in Server Components
- Works in Middleware
- Not dependent on
authMiddleware(), but middleware is recommended
Using getSession(req) in Pages Router API Routes
getSession(req) retrieves session data in Next.js API routes (pages/api/).
Protecting an API Route (Pages Router)
- Works only in Pages Router (
pages/api/) - Do not use in Middleware (use
session()instead)
Using SDK in Server Components/API Routes
For backend API interactions, use createSdk() to access the Descope Management API.
Fetching User Data from the Descope Management SDK
When to Use Each Method
| Use Case | App Router | Pages Router | Middleware | API Routes |
|---|---|---|---|---|
Client Hooks (useSession, useUser) | Yes | Yes | No | No |
Middleware (authMiddleware()) | Yes | Yes | Yes | No |
Session Function (session()) | Yes | No | Yes | Yes |
API Routes (getSession(req)) | No | Yes | No | Yes |
Management API (createSdk()) | Yes | Yes | Yes | Yes |
Additional Considerations
For more details on handling session and authentication events, refer to the Client SDK Auth Helpers documentation.
This includes:
- Session and user event listeners (
onSessionTokenChange,onIsAuthenticatedChange,onUserChange) - Handling session expiration and refresh
- Redirecting users after logout
- Managing authentication state across multiple tabs
By leveraging these utilities, you can ensure a seamless and secure authentication experience for users across your Next.js application.