Next.js Discord

Discord Forum

Error when doing OPTIONS request in serverless function locally

Unanswered
Briquet Griffon Vendéen posted this in #help-forum
Open in Discord
Briquet Griffon VendéenOP
I have a serverless function locally, and when i make a request with the OPTIONS method, the request fails and returns this error:
<<FIRST IMAGE>>

This only happens when using OPTIONS method, using any other wont cause failure:
<<SECOND IMAGE>>
(that error is the correct behavior)

this is the snippet of code that handles the OPTIONS method, is the standard cors recommendation that vercel gives:
const allowCors = fn => async (req, res) => {
  res.setHeader('Access-Control-Allow-Credentials', true)
  res.setHeader('Access-Control-Allow-Origin', '*')
  // another common pattern
  // res.setHeader('Access-Control-Allow-Origin', req.headers.origin);
  res.setHeader('Access-Control-Allow-Methods', 'GET,OPTIONS,PATCH,DELETE,POST,PUT')
  res.setHeader(
    'Access-Control-Allow-Headers',
    'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Authorization, Date, X-Api-Version'
  )
  if (req.method === 'OPTIONS') {
    console.log('OPTIONS')
    res.status(200).end()
    return
  }

  return await fn(req, res)
}


I already tried running npm i -g vercel@latest, im using node v18.17.1

any ideas?

2 Replies

Briquet Griffon VendéenOP
Fun thing is: This only happens when running the function locally
doesnt happen when the function is deployed