| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| // CORS HELPER - Shared CORS headers and OPTIONS preflight handler | |
| // Use this in every API route for cross-origin frontend support | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| export const CORS_HEADERS = { | |
| 'Access-Control-Allow-Origin': '*', | |
| 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, PATCH, OPTIONS', | |
| 'Access-Control-Allow-Headers': | |
| 'Content-Type, Authorization, X-Requested-With, Accept, Origin', | |
| 'Access-Control-Max-Age': '86400', | |
| }; | |
| /** | |
| * Returns a 204 No Content response for OPTIONS preflight requests. | |
| * Add `export { OPTIONS } from '@/lib/cors'` in every route file. | |
| */ | |
| export function OPTIONS() { | |
| return new Response(null, { status: 204, headers: CORS_HEADERS }); | |
| } | |
| /** | |
| * Wraps a NextResponse with CORS headers. | |
| */ | |
| export function withCors(response: Response): Response { | |
| const headers = new Headers(response.headers); | |
| Object.entries(CORS_HEADERS).forEach(([k, v]) => headers.set(k, v)); | |
| return new Response(response.body, { | |
| status: response.status, | |
| statusText: response.statusText, | |
| headers, | |
| }); | |
| } | |