-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
73 lines (61 loc) · 1.9 KB
/
proxy.ts
File metadata and controls
73 lines (61 loc) · 1.9 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
63
64
65
66
67
68
69
70
71
/**
* Next.js proxy (formerly middleware) for request logging and request ID tracking
* Logs incoming HTTP requests and sets up request context for async operations
*/
import {
createLogger,
generateRequestId,
runWithRequestContext,
sanitizeUrlForLogging,
} from "@/lib/utils/logger"
import type { NextRequest } from "next/server"
import { NextResponse } from "next/server"
const logger = createLogger("HTTP")
/**
* Proxy handler to log HTTP requests and set up request context
*/
export function proxy(request: NextRequest) {
const requestId = generateRequestId()
// Extract user ID from session if available (set by auth callbacks)
let userId: string | undefined
// Run the request within a context
return runWithRequestContext(requestId, userId, () => {
const url = sanitizeUrlForLogging(request.url)
const method = request.method
const userAgent = request.headers.get("user-agent") || "unknown"
const ip =
request.headers.get("x-forwarded-for") ||
request.headers.get("x-real-ip") ||
"unknown"
// Log incoming request
logger.info("Incoming request", {
method,
url,
userAgent,
ip,
pathname: request.nextUrl.pathname,
searchParams: Object.fromEntries(request.nextUrl.searchParams),
})
// Create response
const response = NextResponse.next()
// Add request ID to response headers for tracing
response.headers.set("X-Request-ID", requestId)
return response
})
}
/**
* Configure which routes should be processed by this proxy
*/
export const config = {
matcher: [
/*
* Match all request paths except:
* - api (API routes)
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
* - public files (public folder)
*/
"/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp|ico)).*)",
],
}