-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
31 lines (24 loc) · 823 Bytes
/
middleware.ts
File metadata and controls
31 lines (24 loc) · 823 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export function middleware(request: NextRequest) {
const authToken = process.env.API_AUTH_TOKEN
// If no auth token configured, allow all requests (local dev mode)
if (!authToken) {
return NextResponse.next()
}
const authorization = request.headers.get('authorization')
const apiKey = request.headers.get('x-api-key')
const providedToken = authorization?.startsWith('Bearer ')
? authorization.slice(7)
: apiKey
if (!providedToken || providedToken !== authToken) {
return NextResponse.json(
{ error: 'Unauthorized. Set Authorization: Bearer <token> or x-api-key header.' },
{ status: 401 }
)
}
return NextResponse.next()
}
export const config = {
matcher: '/api/:path*',
}