|
| 1 | +import { type NextRequest, NextResponse } from 'next/server'; |
| 2 | + |
| 3 | +export const config = { |
| 4 | + matcher: '/:path*', |
| 5 | +}; |
| 6 | + |
| 7 | +const TRACKER_PATH = '/script.js'; |
| 8 | +const COLLECT_PATH = '/api/send'; |
| 9 | +const LOGIN_PATH = '/login'; |
| 10 | + |
| 11 | +const apiHeaders = { |
| 12 | + 'Access-Control-Allow-Origin': '*', |
| 13 | + 'Access-Control-Allow-Headers': '*', |
| 14 | + 'Access-Control-Allow-Methods': 'GET, DELETE, POST, PUT', |
| 15 | + 'Access-Control-Max-Age': process.env.CORS_MAX_AGE || '86400', |
| 16 | + 'Cache-Control': 'no-cache', |
| 17 | +}; |
| 18 | + |
| 19 | +const trackerHeaders = { |
| 20 | + 'Access-Control-Allow-Origin': '*', |
| 21 | + 'Cache-Control': 'public, max-age=86400, must-revalidate', |
| 22 | +}; |
| 23 | + |
| 24 | +function customCollectEndpoint(request: NextRequest) { |
| 25 | + const collectEndpoint = process.env.COLLECT_API_ENDPOINT; |
| 26 | + |
| 27 | + if (collectEndpoint) { |
| 28 | + const url = request.nextUrl.clone(); |
| 29 | + |
| 30 | + if (url.pathname.endsWith(collectEndpoint)) { |
| 31 | + url.pathname = COLLECT_PATH; |
| 32 | + return NextResponse.rewrite(url, { headers: apiHeaders }); |
| 33 | + } |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +function customScriptName(request: NextRequest) { |
| 38 | + const scriptName = process.env.TRACKER_SCRIPT_NAME; |
| 39 | + |
| 40 | + if (scriptName) { |
| 41 | + const url = request.nextUrl.clone(); |
| 42 | + const names = scriptName.split(',').map(name => name.trim().replace(/^\/+/, '')); |
| 43 | + |
| 44 | + if (names.find(name => url.pathname.endsWith(name))) { |
| 45 | + url.pathname = TRACKER_PATH; |
| 46 | + return NextResponse.rewrite(url, { headers: trackerHeaders }); |
| 47 | + } |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +function customScriptUrl(request: NextRequest) { |
| 52 | + const scriptUrl = process.env.TRACKER_SCRIPT_URL; |
| 53 | + |
| 54 | + if (scriptUrl && request.nextUrl.pathname.endsWith(TRACKER_PATH)) { |
| 55 | + return NextResponse.rewrite(scriptUrl, { headers: trackerHeaders }); |
| 56 | + } |
| 57 | +} |
| 58 | + |
| 59 | +function disableLogin(request: NextRequest) { |
| 60 | + const loginDisabled = process.env.DISABLE_LOGIN; |
| 61 | + |
| 62 | + if (loginDisabled && request.nextUrl.pathname.endsWith(LOGIN_PATH)) { |
| 63 | + return new NextResponse('Access denied', { status: 403 }); |
| 64 | + } |
| 65 | +} |
| 66 | + |
| 67 | +export default function middleware(req: NextRequest) { |
| 68 | + const fns = [customCollectEndpoint, customScriptName, customScriptUrl, disableLogin]; |
| 69 | + |
| 70 | + for (const fn of fns) { |
| 71 | + const res = fn(req); |
| 72 | + if (res) { |
| 73 | + return res; |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + return NextResponse.next(); |
| 78 | +} |
0 commit comments