Cors in serverless function

how can i change Cross-Origin Resource Sharing policy for serverless functions

Have you tried on your server function response to add the CORS headers like

Access-Control-Allow-Origin

and any others you might need for your app?

Hi,
I stumbled over this issue, too. And am not able to get it to work.

2024-12-05T07:50:13.817620421Z {"level":50,"time":1733385013817,"msg":"Access to myFunction was denied"}
2024-12-05T07:50:13.818040148Z {"level":30,"time":1733385013817,"reqId":"req-20","res":{"statusCode":401},"responseTime":0.8335704803466797,"msg":"request completed"}

I think serverless functions need a bit more documentation or examples. I only found out about this now, too. I would like to know how I can restrict to client referer, so it should be something like
'Access-Control-Allow-Origin': process.env.URL === event.headers.Referer ? process.env.URL : ''

Furthermore I just asked in the discord about the return values of serverless functions. The function itself has a promise type that needs statusCode, but when i try to write it out like return { stat... } there is no type recommendation. So it is really bothersome to work with serverless functions. fastify normally provides res.status(200).send(…) as convenience function. There is also fastify/sensible which provides more helpers. I think the cors functionality should be provided, too. It is quite annoying to write it in each return statement, if there are different status codes used.

Furthermore I think the documentation could use some client side explanation, too. Since i.e. the use of RWJS_API_URL is not much documented and necessary in this case. I am not yet even sure, if this would example would work for authentication because of cookies:

fetch(window.RWJS_API_URL + '/myFunction' {
    method: 'PUT',
    headers: {
      'Content-Type': 'text/plain',
    },
    body,
  }).then((response) => {
    if (!response.ok) {
      throw new Error(response.statusText)
    } else {
      return response.text()
    }
  })
``
1 Like

Ok I think CORS works in my case, but authentication is still not working. Going to have a closer look at it. Anything I need to consider to send authentication in headers?