AWS Amplify Serverless Function 403 Error CORS

06/08/20191 Min Read — In DevOps, JavaScript

A CORS Error?

I've set up a serverless function and REST API endpoint to process payments via Stripe.

Every time I try to use the function, I get a POST error with status code 403:

XMLHttpRequest cannot load http://XXXXX.execute-api.us-west-2.amazonaws.com/YYYYY. No 'Access-Control-Allow-Origin' header is present on the requested resource.

This looks like a CORS error.

When you use the Amplify CLI tool to create your function, it delivers a sample Node.js/Express app.

It includes middleware for CORS:

// Enable CORS for all methods
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*')
res.header(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept'
)
next()
})

I was confused about the error, as CORS was enabled for my POST request function.

Solution?

It turned out that the culprit was missing permissions for the serverless function.

I limited the access to the function to authenticated users with Amazon Cognito.

When the Amplify CLI asks:

  • "Restrict API access?" Yes
  • "Who should have access?" > Authenticated Users Only
  • "What kind of access do you want for Authenticated Users" > create + update

Initially, I just gave update permission. And this rule caused the 403 error.

Further Reading