forked from SigNoz/signoz.io
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
99 lines (85 loc) · 2.91 KB
/
middleware.ts
File metadata and controls
99 lines (85 loc) · 2.91 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { waitUntil } from '@vercel/functions'
import { v4 as uuidv4 } from 'uuid'
import { detectBotFromUserAgent, logEventServerSide } from './utils/logEvent'
// Extract OS from user agent (server-side version)
const getOSFromUserAgent = (userAgent: string): string => {
if (!userAgent) return 'unknown'
const ua = userAgent.toLowerCase()
if (ua.includes('windows')) return 'Windows'
if (ua.includes('ipad')) return 'iPad'
if (ua.includes('iphone') || ua.includes('like mac')) return 'iOS'
if (ua.includes('mac')) return 'MacOS'
if (ua.includes('android')) return 'Android'
if (ua.includes('linux')) return 'Linux'
return 'unknown'
}
export function middleware(req: NextRequest) {
// Get or generate anonymous ID
let anonymousId = req.cookies.get('gb_anonymous_id')?.value
const shouldSetCookie = !anonymousId
if (!anonymousId) {
anonymousId = uuidv4()
}
// Get user agent and detect bot
const userAgent = req.headers.get('user-agent') || ''
const { isBot, botType } = detectBotFromUserAgent(userAgent)
// Get request details
const pathname = req.nextUrl.pathname
const referer = req.headers.get('referer') || req.headers.get('referrer') || 'direct'
const ip =
req.ip || req.headers.get('x-forwarded-for') || req.headers.get('x-real-ip') || 'unknown'
// Log bot requests
if (isBot) {
// Use waitUntil to ensure logging completes before function termination
waitUntil(
logEventServerSide({
eventName: 'Bot Page Request',
eventType: 'track',
attributes: {
pageLocation: pathname,
custom_user_agent: userAgent,
custom_bot_type: botType,
custom_os: getOSFromUserAgent(userAgent),
custom_referrer: referer,
custom_ip: ip,
custom_source: 'server',
custom_is_bot: true,
custom_request_method: req.method,
custom_has_javascript: false,
},
anonymousId,
})
)
}
// Prepare response
const res = NextResponse.next()
// Set cookie if it wasn't already set
if (shouldSetCookie && anonymousId) {
res.cookies.set('gb_anonymous_id', anonymousId, {
path: '/',
maxAge: 60 * 60 * 24 * 365, // one year
sameSite: 'lax',
})
}
// Add custom headers for debugging (optional - remove in production if not needed)
if (isBot) {
res.headers.set('x-bot-detected', 'true')
res.headers.set('x-bot-type', botType || 'unknown')
}
return res
}
// Run this middleware on all routes to catch all bot requests
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - api (API routes)
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
*/
'/((?!api|_next/static|_next/image|favicon.ico).*)',
],
}