umami/middleware.js

48 lines
1.0 KiB
JavaScript
Raw Normal View History

import { NextResponse } from 'next/server';
2022-07-07 18:24:32 +02:00
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/collect';
return NextResponse.rewrite(url);
}
}
}
function customScriptName(req) {
const scriptName = process.env.TRACKER_SCRIPT_NAME;
if (scriptName) {
const url = req.nextUrl.clone();
const { pathname } = url;
2022-04-27 12:05:24 +02:00
const names = scriptName.split(',').map(name => name.trim() + '.js');
if (names.find(name => pathname.endsWith(name))) {
url.pathname = '/umami.js';
return NextResponse.rewrite(url);
}
}
}
2022-07-07 18:24:32 +02:00
export default function middleware(req) {
const fns = [customCollectEndpoint, customScriptName];
for (const fn of fns) {
const res = fn(req);
if (res) {
return res;
}
}
2022-08-01 08:29:47 +02:00
return NextResponse.next();
}