From 56480f42e1ddcf39c0896ebc366106d39247f0de Mon Sep 17 00:00:00 2001 From: pumbas600 Date: Sun, 29 Oct 2023 11:58:42 +1300 Subject: [PATCH 1/2] feat: :sparkles: Add a middleware for handling CORS --- src/middleware.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 src/middleware.ts diff --git a/src/middleware.ts b/src/middleware.ts new file mode 100644 index 0000000..2aad7b0 --- /dev/null +++ b/src/middleware.ts @@ -0,0 +1,14 @@ +import { NextResponse } from 'next/server'; + +export function middleware(): NextResponse { + const res = NextResponse.next(); + + res.headers.append('Access-Control-Allow-Origin', '*'); + res.headers.append('Access-Control-Allow-Methods', 'GET'); + + return res; +} + +export const config = { + matcher: '/api/:path*', // Match all API routes +}; From 3b86e21cdd71d8a91952d9045b2debc5ecc5b2de Mon Sep 17 00:00:00 2001 From: pumbas600 Date: Sun, 29 Oct 2023 12:07:12 +1300 Subject: [PATCH 2/2] feat: :sparkles: Respond to `OPTIONS` requests in middleware --- src/middleware.ts | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/middleware.ts b/src/middleware.ts index 2aad7b0..7761a86 100644 --- a/src/middleware.ts +++ b/src/middleware.ts @@ -1,11 +1,10 @@ -import { NextResponse } from 'next/server'; +import { NextRequest, NextResponse } from 'next/server'; -export function middleware(): NextResponse { - const res = NextResponse.next(); +export function middleware(req: NextRequest): Response { + const res = req.method === 'OPTIONS' ? new Response(undefined, { status: 204 }) : NextResponse.next(); res.headers.append('Access-Control-Allow-Origin', '*'); res.headers.append('Access-Control-Allow-Methods', 'GET'); - return res; }