Files
inventory/middleware.js
2026-05-03 13:28:45 -04:00

47 lines
1.3 KiB
JavaScript

import { NextResponse } from 'next/server';
export function middleware(req) {
const basicAuth = req.headers.get('authorization');
const url = req.nextUrl;
// Read credentials from environment variables
const user = process.env.BASIC_AUTH_USER;
const pwd = process.env.BASIC_AUTH_PASSWORD;
if (user && pwd) {
if (basicAuth) {
const authValue = basicAuth.split(' ')[1];
const [providedUser, providedPwd] = atob(authValue).split(':');
if (providedUser === user && providedPwd === pwd) {
return NextResponse.next();
}
}
// Return 401 Unauthorized if credentials don't match or are missing
return new NextResponse('Auth required', {
status: 401,
headers: {
'WWW-Authenticate': 'Basic realm="Secure Area"',
},
});
}
// If no credentials are set in ENV, just allow access
return NextResponse.next();
}
// Ensure the middleware only runs for paths that need protection.
// Exclude static assets, API routes if public (though we probably want API secure too), and Next.js internals.
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
*/
'/((?!_next/static|_next/image|favicon.ico).*)',
],
};