loading...
Cover image for Enable CORS For AWS Lambda Function
Lambda Store

Enable CORS For AWS Lambda Function

svenanderson profile image Sven Anderson ・2 min read

The problem:

While fetching data from my AWS Lambda function I am getting the following error:

Access to fetch at 'https://abcde.execute-api.us-east-1.amazonaws.com/Prod/' from origin 'http://serverless-hackernews.s3-website-us-east-1.amazonaws.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
abcde.execute-api.us-east-1.amazonaws.com/Prod/:1 Failed to load resource: net::ERR_FAILED

You have to enable CORS to fix this.

What is CORS?

By default, the servers do not respond AJAX requests from domains other than the domain from which the first resource was served. CORS (Cross Origin Resource Sharing) is the mechanism to allow that.

Should I enable CORS for AWS Lambda Function?

If you will use your serverless functions as a web API backend, yes, you should. Without CORS, your client will not be able fetch data from your function.

How to enable CORS for my AWS Lambda Function?

Two steps:
Step 1- Configure your AWS API Gateway:
If you are using AWS SAM then the following configuration to your template file:

Globals:
  Api:
    Cors:
      AllowMethods: "'OPTIONS,POST,GET'"
      AllowHeaders: "'Content-Type'"
      AllowOrigin: "'*'"

If you are using Serverless framework, check here
If you want to configure the API Gateway manually, check here

Step 2- Configure your response of your function:
In your lambda function add the headers to your response as follows:

       response = {
            statusCode: 200,
            headers: {
                "Access-Control-Allow-Origin": "*",
                "Access-Control-Allow-Headers": "Content-Type",
                "Access-Control-Allow-Methods": "OPTIONS,GET"
            },
            body: JSON.stringify(result)
        };

Note-1: You should add those headers to all functions which are web api backends.
Note-2: In the above example (in both steps), I used * as allowed origin. This means the backend will trust any domain. Ideally it should only allow the domain that is permitted to communicate with the backend.

Posted on by:

svenanderson profile

Sven Anderson

@svenanderson

Making the world serverless

Lambda Store

Lambda Store is the first the `serverless Redis` service. In this blog, Lambda Store engineering team shares their experiences on Cloud, AWS, Kubernetes, Redis and of course Lambda Store.

Discussion

markdown guide