forked from OffchainLabs/arbitrum-docs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
65 lines (56 loc) · 2.03 KB
/
Copy pathmiddleware.ts
File metadata and controls
65 lines (56 loc) · 2.03 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
import { rewrite, next } from '@vercel/edge';
import { pathInfo, buildTrackingPayload } from './lib/llms-tracking';
// PostHog project public key — same as docusaurus.config.js. Public, not a secret.
const POSTHOG_KEY = 'phc_AscFTQ876SsPAVMgxMmLn0EIpxdcRRq0XmJWnpG1SHL';
export const config = {
matcher: [
// Clean URLs — for Accept: text/markdown content negotiation.
'/((?!.*\\.).*)',
// Index files generated by @signalwire/docusaurus-plugin-llms-txt.
'/llms.txt',
'/llms-full.txt',
// Per-page markdown mirrors; exclude auto-generated SDK pages.
'/((?!sdk/).*)\\.md',
],
};
interface MiddlewareContext {
waitUntil: (promise: Promise<unknown>) => void;
}
export default async function middleware(request: Request, context: MiddlewareContext) {
const url = new URL(request.url);
const pathname = url.pathname;
const accept = request.headers.get('accept') ?? '';
const info = pathInfo(pathname, accept);
// Tracking — production only. Never blocks the response.
if (process.env.VERCEL_ENV === 'production' && info.kind !== 'ignored') {
const ua = request.headers.get('user-agent') ?? '';
const referrer = request.headers.get('referer') ?? '';
const ip = request.headers.get('x-forwarded-for')?.split(',')[0]?.trim() ?? '';
context.waitUntil(
buildTrackingPayload({
trackedPath: info.trackedPath,
fileType: info.fileType,
userAgent: ua,
referrer,
ip,
posthogKey: POSTHOG_KEY,
})
.then((payload) =>
fetch('https://app.posthog.com/capture/', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
}),
)
.catch(() => {
// Silent — tracking errors must never break responses.
}),
);
}
// Markdown content-negotiation rewrite — preserved from prior middleware.
if (info.kind === 'markdown-negotiate') {
url.pathname = info.trackedPath;
return rewrite(url);
}
return next();
}