Search code examples
javascriptcorsnetlifynetlify-function

Troubleshooting CORS Issue with Netlify Background Function on POST Request


I have created a Netlify background function to process POST requests. The goal is to receive a POST request, execute my generateEmbeddings function, and send a response back. However, I am encountering a CORS issue when attempting to make a POST request to my Netlify function. Despite setting the CORS headers in my function, I’m still receiving a Cross-Origin Request Blocked error. I orginally had this set as a serverls function and not a background function, and did not run into any CORS issues. I had to move to a background function due to request taking more then 10 seconds with bigger requests.

The errors I receive are the following

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://my-netlify-site.netlify.app/.netlify/functions/webhooks-background. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 202.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://my-netlify-site.netlify.app/.netlify/functions/webhooks-background. (Reason: CORS request did not succeed). Status code: (null).

Here’s the code for my background function:

exports.handler = async (event) => {
  const headers = {
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Methods": "POST, OPTIONS",
    "Access-Control-Allow-Headers": "Content-Type",
    "Content-Type": "application/json",  
  };
  if (event.httpMethod === "OPTIONS") {
    return {
      statusCode: 204,  
      headers,
      body: '', 
    };
  } else if (event.httpMethod === "POST") {
    try {
      const parsedData = JSON.parse(event.body);
      await generateEmbeddings(parsedData);
      return {
        statusCode: 202,
        headers: headers,
        body: "Webhook data received",
      };
    } catch (error) {
      console.error("Error handling request:", error);
      return {
        statusCode: 500,
        headers: headers,
        body: "Internal Server Error",
      };
    }
  } else {
    return {
      statusCode: 405,  
      headers,
      body: JSON.stringify({ message: "HTTP Method not supported. Use OPTIONS or POST." }),
    };
  }
};

Update

I managed to get my background function working locally, but I'm still hitting roadblocks in production. The main issue seems to be with the headers. They're being set correctly on my local dev, but not in production. I've verified this using curl.

I initially set the headers in a netlify.toml file, but when that didn't work in production, I tried using an _headers file. It's currently placed in the root directory of my project.

Here's the code for my updated background function:

const { generateEmbeddings } = require("../../scripts/embedding");

exports.handler = async (event) => {
  if (event.httpMethod === "OPTIONS") {
    console.log("OPTIONS request received");
    return; 
  } 
  if (event.httpMethod === "POST") {
    try {
      const parsedData = JSON.parse(event.body);
      await generateEmbeddings(parsedData);
      console.log("Webhook data processed in the background");
    } catch (error) {
      console.error("Error handling request:", error);
    }
  }
};

And here's the content of my _headers file:

/*
  Cache-Control: no-cache
  Access-Control-Allow-Origin: *

/.netlify/functions/*
  Access-Control-Allow-Origin: *
  Access-Control-Allow-Headers: Content-Type, Authorization
  Access-Control-Allow-Methods: GET, POST, OPTIONS

Solution

  • Further research lead to me figuring out that netlify background functions respond automatically with a 202, not allowing you set CORS headers.

    My Workaround for this was invoking Netlify's background function by implementing a serverless function to handle the CORS headers. The serverless function initiates the background function, managing the function call and any required data processing. Since both the serverless and background functions are hosted on the same domain, configuring CORS headers for the background function is unnecessary.