candle-annotator/src/middleware.ts
Marko Djordjevic 577bb2e56e feat: add API key auth middleware for /api/* routes (task 3.1)
- Create src/middleware.ts with Next.js middleware
- Reads API_KEY env var and checks X-API-Key header on all /api/* routes
- Skips auth for /api/health endpoint
- Fails open (with warning) when API_KEY is not configured
- Returns 401 Unauthorized when key is missing or mismatched
- Mark task 3.1 as complete in tasks.md

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-02-18 11:02:51 +01:00

33 lines
868 B
TypeScript

import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
export function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
// Skip auth check for the health endpoint
if (pathname === "/api/health") {
return NextResponse.next();
}
const apiKey = process.env.API_KEY;
// If API_KEY is not configured, skip auth check (fail-open for development)
if (!apiKey) {
console.warn(
"Warning: API_KEY environment variable is not set. API authentication is disabled."
);
return NextResponse.next();
}
const requestApiKey = request.headers.get("X-API-Key");
if (!requestApiKey || requestApiKey !== apiKey) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
return NextResponse.next();
}
export const config = {
matcher: ["/api/:path*"],
};