2022-02-21 08:27:50 +01:00
|
|
|
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-10 07:11:15 +02:00
|
|
|
const names = scriptName.split(',').map(name => (name + '.js').trim());
|
2022-02-21 08:27:50 +01:00
|
|
|
|
2022-04-10 07:11:15 +02:00
|
|
|
if (names.find(name => pathname.endsWith(name))) {
|
2022-02-21 08:27:50 +01:00
|
|
|
url.pathname = '/umami.js';
|
|
|
|
return NextResponse.rewrite(url);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
function disableLogin(req) {
|
|
|
|
if (process.env.DISABLE_LOGIN && req.nextUrl.pathname.endsWith('/login')) {
|
|
|
|
return new Response('403 Forbidden', { 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;
|
|
|
|
}
|
|
|
|
|
2022-02-21 08:27:50 +01:00
|
|
|
export function middleware(req) {
|
2022-04-05 03:51:31 +02:00
|
|
|
const fns = [customScriptName, disableLogin];
|
2022-02-21 08:27:50 +01:00
|
|
|
|
|
|
|
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());
|
2022-02-21 08:27:50 +01:00
|
|
|
}
|