|
| 1 | +import { createHash } from 'node:crypto'; |
| 2 | +import { getClientIpFromHeaders } from '@openpanel/common/server/get-client-ip'; |
| 3 | +// adding .js next/script import fixes an issues |
| 4 | +// with esm and nextjs (when using pages dir) |
| 5 | +import { NextResponse } from 'next/server.js'; |
| 6 | + |
| 7 | +type CreateNextRouteHandlerOptions = { |
| 8 | + apiUrl?: string; |
| 9 | +}; |
| 10 | + |
| 11 | +function createNextRouteHandler(options: CreateNextRouteHandlerOptions) { |
| 12 | + return async function POST(req: Request) { |
| 13 | + const apiUrl = options.apiUrl ?? 'https://api.openpanel.dev'; |
| 14 | + const headers = new Headers(req.headers); |
| 15 | + const clientIp = getClientIpFromHeaders(headers); |
| 16 | + console.log('debug', { |
| 17 | + clientIp, |
| 18 | + userAgent: req.headers.get('user-agent'), |
| 19 | + }); |
| 20 | + try { |
| 21 | + const res = await fetch(`${apiUrl}/track`, { |
| 22 | + method: 'POST', |
| 23 | + headers, |
| 24 | + body: JSON.stringify(await req.json()), |
| 25 | + }); |
| 26 | + return NextResponse.json(await res.text(), { status: res.status }); |
| 27 | + } catch (e) { |
| 28 | + return NextResponse.json(e); |
| 29 | + } |
| 30 | + }; |
| 31 | +} |
| 32 | + |
| 33 | +function createScriptHandler() { |
| 34 | + return async function GET(req: Request) { |
| 35 | + if (!req.url.endsWith('op1.js')) { |
| 36 | + return NextResponse.json({ error: 'Not found' }, { status: 404 }); |
| 37 | + } |
| 38 | + |
| 39 | + const scriptUrl = 'https://openpanel.dev/op1.js'; |
| 40 | + try { |
| 41 | + const res = await fetch(scriptUrl, { |
| 42 | + next: { revalidate: 86400 }, |
| 43 | + }); |
| 44 | + const text = await res.text(); |
| 45 | + const etag = `"${createHash('md5').update(text).digest('hex')}"`; |
| 46 | + return new NextResponse(text, { |
| 47 | + headers: { |
| 48 | + 'Content-Type': 'text/javascript', |
| 49 | + 'Cache-Control': |
| 50 | + 'public, max-age=86400, stale-while-revalidate=86400', |
| 51 | + ETag: etag, |
| 52 | + }, |
| 53 | + }); |
| 54 | + } catch (e) { |
| 55 | + return NextResponse.json( |
| 56 | + { |
| 57 | + error: 'Failed to fetch script', |
| 58 | + message: e instanceof Error ? e.message : String(e), |
| 59 | + }, |
| 60 | + { status: 500 }, |
| 61 | + ); |
| 62 | + } |
| 63 | + }; |
| 64 | +} |
| 65 | + |
| 66 | +export const POST = createNextRouteHandler({}); |
| 67 | +export const GET = createScriptHandler(); |
0 commit comments