umami/docker/middleware.js

48 lines
1.0 KiB
JavaScript
Raw Normal View History

2023-04-19 17:49:16 +02:00
import { NextResponse } from 'next/server';
export const config = {
matcher: '/:path*',
};
function customCollectEndpoint(req) {
const collectEndpoint = process.env.COLLECT_API_ENDPOINT;
if (collectEndpoint) {
const url = req.nextUrl.clone();
const { pathname } = url;
if (pathname.endsWith(collectEndpoint)) {
url.pathname = '/api/send';
return NextResponse.rewrite(url);
}
}
}
function customScriptName(req) {
const scriptName = process.env.TRACKER_SCRIPT_NAME;
if (scriptName) {
const url = req.nextUrl.clone();
const { pathname } = url;
2023-04-20 10:52:49 +02:00
const names = scriptName.split(',').map(name => name.trim().replace(/^\/+/, ''));
2023-04-19 17:49:16 +02:00
2023-04-20 10:12:43 +02:00
if (names.find(name => pathname.endsWith(name))) {
2023-04-19 17:49:16 +02:00
url.pathname = '/script.js';
return NextResponse.rewrite(url);
}
}
}
export default function middleware(req) {
const fns = [customCollectEndpoint, customScriptName];
for (const fn of fns) {
const res = fn(req);
if (res) {
return res;
}
}
return NextResponse.next();
}