0
# Server-Side Session Management
1
2
Server-side utilities for retrieving and managing user sessions in API routes, server components, middleware, and getServerSideProps functions. Essential for protecting server-side resources and implementing authentication checks.
3
4
## Capabilities
5
6
### Get Server Session
7
8
Retrieves the current user session on the server side with support for both Pages Router and App Router patterns.
9
10
```typescript { .api }
11
/**
12
* Retrieves the current user session on the server side
13
* @param args - Request/response objects and options (varies by router type)
14
* @returns Promise resolving to session object or null if not authenticated
15
*/
16
function getServerSession<O extends GetServerSessionOptions, R = any>(
17
...args: GetServerSessionParams<O>
18
): Promise<R | null>;
19
20
type GetServerSessionParams<O extends GetServerSessionOptions> =
21
| [GetServerSidePropsContext["req"], GetServerSidePropsContext["res"], O]
22
| [NextApiRequest, NextApiResponse, O]
23
| [O]
24
| [];
25
26
type GetServerSessionOptions = Partial<Omit<AuthOptions, "callbacks">> & {
27
callbacks?: Omit<AuthOptions["callbacks"], "session"> & {
28
session?: (...args: any[]) => any;
29
};
30
};
31
```
32
33
**Usage Examples:**
34
35
```typescript
36
// App Router (server component or route handler)
37
import { getServerSession } from "next-auth/next";
38
39
export default async function Page() {
40
const session = await getServerSession();
41
42
if (!session) {
43
return <p>You must be signed in to view this page</p>;
44
}
45
46
return <p>Welcome {session.user?.name}</p>;
47
}
48
49
// API Route (pages/api)
50
import { getServerSession } from "next-auth/next";
51
import { authOptions } from "./auth/[...nextauth]";
52
53
export default async function handler(req, res) {
54
const session = await getServerSession(req, res, authOptions);
55
56
if (!session) {
57
res.status(401).json({ message: "You must be logged in." });
58
return;
59
}
60
61
res.json({ message: `Hello ${session.user?.name}` });
62
}
63
64
// getServerSideProps
65
import { getServerSession } from "next-auth/next";
66
import { authOptions } from "../api/auth/[...nextauth]";
67
68
export async function getServerSideProps(context) {
69
const session = await getServerSession(context.req, context.res, authOptions);
70
71
if (!session) {
72
return {
73
redirect: {
74
destination: '/api/auth/signin',
75
permanent: false,
76
},
77
};
78
}
79
80
return {
81
props: { session },
82
};
83
}
84
```
85
86
### Session Object
87
88
The session object structure returned by getServerSession and available on the client side.
89
90
```typescript { .api }
91
/**
92
* User session object containing authentication state and user information
93
*/
94
interface Session extends DefaultSession {
95
/** User information */
96
user?: {
97
name?: string | null;
98
email?: string | null;
99
image?: string | null;
100
/** Additional properties can be added via callbacks */
101
[key: string]: any;
102
};
103
/** Session expiration timestamp */
104
expires: ISODateString;
105
/** Additional session properties can be added via callbacks */
106
[key: string]: any;
107
}
108
109
interface DefaultSession {
110
user?: {
111
name?: string | null;
112
email?: string | null;
113
image?: string | null;
114
};
115
expires: ISODateString;
116
}
117
```
118
119
### Session Strategy Configuration
120
121
Configuration options that affect server-side session behavior.
122
123
```typescript { .api }
124
/**
125
* Session strategy configuration affecting server-side behavior
126
*/
127
interface SessionOptions {
128
/**
129
* Session storage strategy
130
* - "jwt": Stateless sessions stored in encrypted JWT cookies
131
* - "database": Server-side sessions stored in database via adapter
132
*/
133
strategy: "jwt" | "database";
134
/** Maximum session age in seconds (default: 2592000 - 30 days) */
135
maxAge: number;
136
/**
137
* How frequently to update session expiry in seconds
138
* Only applies to database sessions (default: 86400 - 24 hours)
139
*/
140
updateAge: number;
141
/** Custom session token generator function for database sessions */
142
generateSessionToken?: () => Awaitable<string>;
143
}
144
```
145
146
### Server Session Callbacks
147
148
Callbacks that specifically affect server-side session behavior and data transformation.
149
150
```typescript { .api }
151
/**
152
* Session callback for customizing server-side session object
153
*/
154
interface SessionCallback {
155
session: (params: {
156
/** Base session object */
157
session: Session;
158
/** JWT token (when using JWT strategy) */
159
token: JWT;
160
/** User object (when using database strategy) */
161
user: AdapterUser;
162
/** New session data from session.update() */
163
newSession?: any;
164
/** Trigger that caused session callback ("update" or undefined) */
165
trigger?: "update";
166
}) => Awaitable<Session | DefaultSession>;
167
}
168
```
169
170
**Usage Example:**
171
172
```typescript
173
// Customize session object with additional user data
174
export const authOptions: AuthOptions = {
175
providers: [...],
176
callbacks: {
177
async session({ session, token, user }) {
178
// Add user ID to session (JWT strategy)
179
if (token) {
180
session.user.id = token.sub;
181
session.user.role = token.role;
182
}
183
184
// Add user data to session (database strategy)
185
if (user) {
186
session.user.id = user.id;
187
session.user.role = user.role;
188
}
189
190
return session;
191
},
192
},
193
};
194
```
195
196
### Server-Side Session Validation
197
198
Advanced patterns for validating and protecting server-side resources.
199
200
```typescript { .api }
201
/**
202
* Server-side session validation utilities
203
*/
204
interface ServerSessionValidation {
205
/** Validate session exists and optionally check conditions */
206
validateSession: (
207
session: Session | null,
208
requirements?: {
209
requireAuth?: boolean;
210
requireRole?: string;
211
requirePermission?: string;
212
}
213
) => boolean;
214
}
215
```
216
217
**Usage Examples:**
218
219
```typescript
220
// Protect API route with role-based access
221
import { getServerSession } from "next-auth/next";
222
223
export default async function handler(req, res) {
224
const session = await getServerSession(req, res, authOptions);
225
226
if (!session) {
227
return res.status(401).json({ error: "Not authenticated" });
228
}
229
230
if (session.user.role !== "admin") {
231
return res.status(403).json({ error: "Insufficient permissions" });
232
}
233
234
// Handle admin-only logic
235
res.json({ data: "Admin data" });
236
}
237
238
// Server component with authentication check
239
export default async function AdminPage() {
240
const session = await getServerSession();
241
242
if (!session) {
243
redirect('/api/auth/signin');
244
}
245
246
if (!session.user.isAdmin) {
247
redirect('/unauthorized');
248
}
249
250
return <AdminDashboard />;
251
}
252
253
// Conditional rendering based on session
254
export default async function ConditionalContent() {
255
const session = await getServerSession();
256
257
return (
258
<div>
259
{session ? (
260
<UserContent user={session.user} />
261
) : (
262
<PublicContent />
263
)}
264
</div>
265
);
266
}
267
```
268
269
### Database Session Management
270
271
When using database session strategy, sessions are managed through the adapter interface.
272
273
```typescript { .api }
274
/**
275
* Database session management interfaces
276
*/
277
interface AdapterSession {
278
/** Randomly generated session token */
279
sessionToken: string;
280
/** User ID associated with this session */
281
userId: string;
282
/** Session expiration date */
283
expires: Date;
284
}
285
286
interface SessionAdapterMethods {
287
/** Create a new session for the user */
288
createSession?: (session: {
289
sessionToken: string;
290
userId: string;
291
expires: Date;
292
}) => Awaitable<AdapterSession>;
293
294
/** Get session and associated user by session token */
295
getSessionAndUser?: (
296
sessionToken: string
297
) => Awaitable<{ session: AdapterSession; user: AdapterUser } | null>;
298
299
/** Update session expiration or other properties */
300
updateSession?: (
301
session: Partial<AdapterSession> & Pick<AdapterSession, "sessionToken">
302
) => Awaitable<AdapterSession | null | undefined>;
303
304
/** Delete session from database */
305
deleteSession?: (
306
sessionToken: string
307
) => Promise<void> | Awaitable<AdapterSession | null | undefined>;
308
}
309
```
310
311
### JWT Session Management
312
313
When using JWT session strategy, sessions are managed through encrypted JWT tokens.
314
315
```typescript { .api }
316
/**
317
* JWT session token structure
318
*/
319
interface JWT extends Record<string, unknown>, DefaultJWT {
320
/** User identifier (subject) */
321
sub?: string;
322
/** User name */
323
name?: string | null;
324
/** User email */
325
email?: string | null;
326
/** User profile picture */
327
picture?: string | null;
328
/** Token issued at timestamp */
329
iat?: number;
330
/** Token expiration timestamp */
331
exp?: number;
332
/** JWT ID */
333
jti?: string;
334
}
335
336
interface DefaultJWT extends Record<string, unknown> {
337
name?: string | null;
338
email?: string | null;
339
picture?: string | null;
340
sub?: string;
341
}
342
```
343
344
### Session Update
345
346
Method for updating session data on the server side (requires database strategy).
347
348
```typescript { .api }
349
/**
350
* Update session data (database strategy only)
351
* Use session.update() on client side to trigger server-side session callback
352
*/
353
interface SessionUpdate {
354
/** Update session with new data */
355
update: (data?: any) => Promise<Session | null>;
356
}
357
```
358
359
**Usage Example:**
360
361
```typescript
362
// API route to update session data
363
export default async function handler(req, res) {
364
const session = await getServerSession(req, res, authOptions);
365
366
if (!session) {
367
return res.status(401).json({ error: "Not authenticated" });
368
}
369
370
// Update user data in database
371
await updateUserProfile(session.user.id, req.body);
372
373
// Session will be refreshed automatically on next request
374
res.json({ success: true });
375
}
376
377
// Session callback to include updated data
378
export const authOptions: AuthOptions = {
379
callbacks: {
380
async session({ session, token, user, trigger, newSession }) {
381
if (trigger === "update") {
382
// Handle session update trigger
383
return { ...session, ...newSession };
384
}
385
return session;
386
},
387
},
388
};
389
```
390
391
## Types
392
393
### Server Context Types
394
395
```typescript { .api }
396
interface GetServerSidePropsContext {
397
req: IncomingMessage & {
398
cookies: Partial<{ [key: string]: string }>;
399
};
400
res: ServerResponse;
401
query: ParsedUrlQuery;
402
resolvedUrl: string;
403
params?: ParsedUrlQuery;
404
preview?: boolean;
405
previewData?: any;
406
locale?: string;
407
locales?: string[];
408
defaultLocale?: string;
409
}
410
411
interface NextApiRequest extends IncomingMessage {
412
query: Partial<{ [key: string]: string | string[] }>;
413
cookies: Partial<{ [key: string]: string }>;
414
body: any;
415
}
416
417
interface NextApiResponse<T = any> extends ServerResponse {
418
send: (body: T) => void;
419
json: (body: T) => void;
420
status: (statusCode: number) => NextApiResponse<T>;
421
redirect: (statusCode: number, url: string) => NextApiResponse<T>;
422
}
423
```