forked from NVIDIA/NeMo-Agent-Toolkit-UI
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
62 lines (54 loc) · 1.82 KB
/
middleware.ts
File metadata and controls
62 lines (54 loc) · 1.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { SESSION_COOKIE_NAME } from './constants/constants';
export default function middleware(req: NextRequest) {
// Skip middleware for static files and auth routes
if (
req.nextUrl.pathname.startsWith('/_next/') ||
req.nextUrl.pathname.startsWith('/api/auth/') ||
req.nextUrl.pathname.startsWith('/favicon.ico') ||
req.nextUrl.pathname.startsWith('/public/')
) {
return NextResponse.next();
}
const response = NextResponse.next();
// Check if session cookie exists
const sessionCookie = req.cookies.get(SESSION_COOKIE_NAME);
if (!sessionCookie) {
// Generate a new session ID for visitors without one
const sessionId = `session_${Date.now()}_${Math.random()
.toString(36)
.substr(2, 9)}`;
// Set the session cookie
response.cookies.set(SESSION_COOKIE_NAME, sessionId, {
httpOnly: false,
sameSite: 'lax',
path: '/',
secure: process.env.NODE_ENV === 'production',
maxAge: 30 * 24 * 60 * 60, // 30 days
});
// Add session ID to headers for API routes
if (req.nextUrl.pathname.startsWith('/api/')) {
response.headers.set('x-session-id', sessionId);
}
} else {
// Add existing session ID to headers for API routes
if (req.nextUrl.pathname.startsWith('/api/')) {
response.headers.set('x-session-id', sessionCookie.value);
}
}
return response;
}
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - api/auth (NextAuth API routes)
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
* - public folder
*/
'/((?!api/auth|_next/static|_next/image|favicon.ico|public).*)',
],
};