middleware.ts32 lines · main
| 1 | import { NextResponse, type NextRequest } from 'next/server'; |
| 2 | |
| 3 | const BRIVEN_API_ORIGIN = process.env.NEXT_PUBLIC_BRIVEN_API_ORIGIN ?? 'https://api.briven.tech'; |
| 4 | const BRIVEN_PROJECT_ID = process.env.NEXT_PUBLIC_BRIVEN_PROJECT_ID!; |
| 5 | const BRIVEN_AUTH_KEY = |
| 6 | process.env.BRIVEN_AUTH_PUBLIC_KEY ?? process.env.NEXT_PUBLIC_BRIVEN_AUTH_KEY!; |
| 7 | |
| 8 | export async function middleware(req: NextRequest) { |
| 9 | if (!req.nextUrl.pathname.startsWith('/api/auth/')) return NextResponse.next(); |
| 10 | |
| 11 | const url = new URL( |
| 12 | req.nextUrl.pathname.replace('/api/auth', '/v1/auth-tenant'), |
| 13 | BRIVEN_API_ORIGIN, |
| 14 | ); |
| 15 | url.search = req.nextUrl.search; |
| 16 | |
| 17 | const headers = new Headers(req.headers); |
| 18 | headers.set('x-briven-project-id', BRIVEN_PROJECT_ID); |
| 19 | headers.set('authorization', `Bearer ${BRIVEN_AUTH_KEY}`); |
| 20 | |
| 21 | return fetch(url, { |
| 22 | method: req.method, |
| 23 | headers, |
| 24 | body: req.body, |
| 25 | // @ts-expect-error — duplex required for streaming bodies in Node 18+ |
| 26 | duplex: 'half', |
| 27 | }); |
| 28 | } |
| 29 | |
| 30 | export const config = { |
| 31 | matcher: ['/api/auth/:path*'], |
| 32 | }; |