Files
ArchiTools/src/middleware.ts
T
AI Assistant 4b5d3bd498 fix(pdf-compress): bypass middleware body buffering for upload routes
Next.js middleware buffers the entire request body (10MB default limit)
before the route handler runs. middlewareClientMaxBodySize experimental
flag doesn't work reliably with standalone output.

Solution: exclude api/compress-pdf from middleware matcher so the body
streams directly to the route handler. Auth check moved to a shared
helper (auth-check.ts) called at the start of each route.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 19:54:28 +02:00

52 lines
1.6 KiB
TypeScript

import { getToken } from "next-auth/jwt";
import { NextRequest, NextResponse } from "next/server";
export async function middleware(request: NextRequest) {
// In development, skip auth enforcement (dev stub user handles it)
if (process.env.NODE_ENV === "development") {
return NextResponse.next();
}
const token = await getToken({
req: request,
secret: process.env.NEXTAUTH_SECRET,
});
// Authenticated — allow through
if (token) {
return NextResponse.next();
}
const { pathname } = request.nextUrl;
// API routes: return 401 JSON instead of redirect
if (pathname.startsWith("/api/")) {
return NextResponse.json(
{ error: "Authentication required" },
{ status: 401 },
);
}
// Use NEXTAUTH_URL as base (request.url uses container's internal 0.0.0.0:3000)
const baseUrl = process.env.NEXTAUTH_URL || "https://tools.beletage.ro";
const callbackUrl = `${baseUrl}${pathname}${request.nextUrl.search}`;
// Redirect to custom sign-in page (auto-forwards to Authentik)
const signInUrl = new URL("/auth/signin", baseUrl);
signInUrl.searchParams.set("callbackUrl", callbackUrl);
return NextResponse.redirect(signInUrl);
}
export const config = {
matcher: [
/*
* Match all paths EXCEPT:
* - /api/auth/* (NextAuth endpoints — must be public for login flow)
* - /_next/* (Next.js internals: static files, HMR, chunks)
* - /favicon.ico, /robots.txt, /sitemap.xml
* - Files with extensions (images, fonts, etc.)
*/
"/((?!api/auth|api/notifications/digest|api/compress-pdf|auth/signin|_next|favicon\\.ico|robots\\.txt|sitemap\\.xml|.*\\..*).*)",
],
};