umami/pages/_middleware.js

44 lines
1.0 KiB
JavaScript
Raw Normal View History

import { NextResponse } from 'next/server';
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);
}
}
}
function disableLogin(req) {
if (process.env.DISABLE_LOGIN && req.nextUrl.pathname.endsWith('/login')) {
2022-06-10 20:23:00 +02:00
return new Response('Login is disabled', { status: 403 });
}
}
2022-04-05 03:51:31 +02:00
function forceSSL(req, res) {
if (process.env.FORCE_SSL && req.nextUrl.protocol === 'http:') {
res.headers.set('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
}
return res;
}
export function middleware(req) {
2022-04-05 03:51:31 +02:00
const fns = [customScriptName, disableLogin];
for (const fn of fns) {
const res = fn(req);
if (res) {
return res;
}
}
2022-04-05 03:51:31 +02:00
return forceSSL(req, NextResponse.next());
}