Report this

What is the reason for this report?

Set CORS headers for OPTIONS method with Serverless Functions

Posted on July 16, 2023
mark

By mark

When calling a Function via HTTP with the OPTIONS method, my Function’s code is not executed. I need to change the Access-Control-Allow-Credentials and Access-Control-Allow-Origin headers for any OPTIONS request.

It seems like the response for an OPTIONS request is static and does not invoke the Function at all. Other methods work.

These Functions are not part of an App.

I have tried with both web: true and web: raw but neither worked.

project.yml:

packages:
  - name: mypackage
    shared: false
    environment: {}
    parameters: {}
    annotations: {}
    functions:
      - name: sessionCreate
        binary: false
        main: ""
        runtime: nodejs:18
        web: raw
        websecure: false
        parameters: {}
        annotations: {}
        limits: {}


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Hi there,

I think DigitalOcean Functions handle OPTIONS requests with a built-in static CORS response, meaning the platform itself replies without invoking your function. That’s probably why you can’t customize headers like Access-Control-Allow-Origin or Access-Control-Allow-Credentials directly inside the function.

If you need custom CORS behavior, you can deploy your functions as part of an App Platform app and configure the CORS policy there:

https://docs.digitalocean.com/products/app-platform/how-to/configure-cors-policies/

Another option would be to place a lightweight proxy in front, such as an NGINX reverse proxy or a Cloudflare Worker, to forward the request and inject the custom CORS headers before returning the response. Not 100% sure if more granular control will come to Functions directly, but this is the best workaround for now.

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.