examples icon indicating copy to clipboard operation
examples copied to clipboard

Cors example: TypeError: Cannot read properties of undefined (reading 'set')

Open 0xmovses opened this issue 3 years ago • 3 comments

I have added the cors.ts file to our project and added the middleware function to use cors, however when I run yarn dev I the following error

TypeError: Cannot read properties of undefined (reading 'set')

The error comes from the cors function inside cors.ts. We have not modified the code.

We are on NextJS 12.1.0. Any help here is apprecaited.

0xmovses avatar Mar 24 '22 23:03 0xmovses

Hi @rvmelkonian 👋

I just tested the demo locally and it's working for me, I don't know what exactly to look for, can you share more details about the issue? 🙏

Thank you!

lfades avatar Mar 25 '22 22:03 lfades

At a guess you've done what I did, which is to take the example middleware and try to make it not do what the example does.

export function middleware(req: NextRequest) {
  // `cors` also takes care of handling OPTIONS requests
  return cors(
    req,
    new Response(JSON.stringify({ message: 'Hello World!' }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' },
    })
  )
}

But we don't want to return a response directly here, we want to call through to the next thing in the chain - which in my case is my actual API endpoint, but I guess could be another middleware (not tried that yet).

export async function middleware(req: NextRequest) {
  return cors(req, NextResponse.next());
}

That should fix it - at least it has done for me.

Why the TypeError: Cannot read properties of undefined (reading 'set') is because:

https://github.com/vercel/examples/blob/main/edge-functions/cors/lib/cors.ts#L101

Whatever you are passing as the res is not actually a response object... at least, it isn't an object with a Headers object at res.headers at any rate.

To be honest, it's a bit weird that most of the examples in this repo return a response directly from the middleware, as I suspect that's not what most people are after doing.

Still, very appreciative of the code - saved me a job :) thanks

a6software avatar May 16 '22 10:05 a6software

@a6software I see. The cors function in the example expects a response to attach headers to, so not sending it one will end up with an error. You could change the implementation to work on a different way, this is just a general pattern we have for the examples. NextResponse.next() is also returning a Response object.

but I guess could be another middleware (not tried that yet)

Next.js won't allow nested middlewares in the coming future, only a root one.

To be honest, it's a bit weird that most of the examples in this repo return a response directly from the middleware, as I suspect that's not what most people are after doing.

You either return a response (which can be NextResponse.next()) or undefined, the example in the repo do both 👍

lfades avatar May 16 '22 19:05 lfades