1 import { notFound } from "next/navigation"
2 import { after, NextRequest, NextResponse } from "next/server"
3 import path from "path"
4 import { PostHog } from "posthog-node"
5 import { fetchAssetResponse } from "../../../utils/fetch-asset-response"
6
7 const ALLOWED_FILES = new Set(["llms.txt", "llms-full.txt"])
8
9 type Params = {
10 params: Promise<{ file: string }>
11 }
12
13 export async function GET(req: NextRequest, { params }: Params) {
14 const { file } = await params
15
16 if (!ALLOWED_FILES.has(file)) {
17 return notFound()
18 }
19
20 const origin = new URL(req.url).origin
21 const assetRes = await fetchAssetResponse(`${origin}/${file}`)
22
23 let body: BodyInit | null = assetRes?.body ?? null
24
25 if (!assetRes) {
26 try {
27 const { promises: fs } = await import("fs")
28 body = await fs.readFile(
29 path.join(process.cwd(), "public", file),
30 "utf-8"
31 )
32 } catch {
33 return notFound()
34 }
35 }
36
37 after(async () => {
38 const client = new PostHog(process.env.NEXT_PUBLIC_POSTHOG_KEY!, {
39 host: process.env.NEXT_PUBLIC_POSTHOG_HOST,
40 })
41
42 client.capture({
43 distinctId: "anonymous",
44 event: "llms_txt_requested",
45 properties: {
46 $current_url: `${process.env.NEXT_PUBLIC_BASE_URL || origin}/${file}`,
47 $raw_user_agent: req.headers.get("user-agent") || undefined,
48 $ip:
49 req.headers.get("cf-connecting-ip") ||
50 req.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ||
51 undefined,
52 file,
53 referrer: req.headers.get("referer") || undefined,
54 },
55 })
56
57 await client.shutdown()
58 })
59
60 return new NextResponse(body, {
61 headers: {
62 "content-type": "text/plain; charset=utf-8",
63 "cache-control": "public, max-age=3600, must-revalidate",
64 },
65 status: 200,
66 })
67 }