Trouble Implementing CORS Handling in Next.js Middleware

I’m facing challenges while trying to implement CORS handling within my Next.js middleware. I’ve been following various examples and documentation, but I keep encountering an error that I can’t seem to resolve. I hope someone with experience in Next.js and CORS handling can provide insights.

Here’s my current setup:

I have a middleware.ts file in my Next.js project that includes a middleware function. I want to include CORS handling within this function.

Here’s a simplified version of my middleware function:

import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'

export function middleware(request: NextRequest) {
  const allowedOrigins = ['http://localhost:8888', 'http://example.com']; // Add more origins as needed
  const origin = request.headers.get('origin');

  if (allowedOrigins.includes(origin)) {
    const requestHeaders = new Headers(request.headers)
    requestHeaders.set('Access-Control-Allow-Origin', origin);
    requestHeaders.set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
    requestHeaders.set('Access-Control-Allow-Headers', 'Content-Type');
    requestHeaders.set('Access-Control-Allow-Credentials', 'true');

    if (request.method === 'OPTIONS') {
      // Handle preflight OPTIONS request
      // ...
    }

    return NextResponse.next({
      request: {
        ...request,
        headers: requestHeaders,
      },
    });
  } else {
    return new Response('Forbidden', { status: 403 });
  }
}

However, I keep getting the error:

Argument of type '{ request: { headers: Headers; ... }; }' is not assignable to parameter of type 'ResponseInit'.

I’ve been struggling to understand what’s causing this error and how to resolve it. Could someone provide guidance on how to properly integrate CORS handling within my middleware function in Next.js?

Any help or suggestions would be greatly appreciated.