Serverless Cors Issue Help

I’m facing a persistent CORS issue when trying to make a POST request from my frontend application to an API deployed with the Serverless Framework. My frontend is running on localhost:5173 (dev server) and the backend API endpoint is at https://zgrciu0uce.execute-api.us-east-1.amazonaws.com/dev/auth/createUserFromAdmin.

Error from the browser’s console

Access to XMLHttpRequest at 'https://zgrciu0uce.execute-api.us-east-1.amazonaws.com/dev/auth/createUserFromAdmin' from origin 'http://localhost:5173' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.
POST https://zgrciu0uce.execute-api.us-east-1.amazonaws.com/dev/auth/createUserFromAdmin net::ERR_FAILED

In serverless.yml, I added CORS configuration like this (I’ve just followed official docs):

functions:
  authCreateUserFromAdminHandler:
    handler: src/modules/Auth/handlers/createUserFromAdminHandler.handler
    events:
      - http:
          path: auth/createUserFromAdmin
          method: post
          cors: true

In lambda function authCreateUserFromAdminHandler’s code:

export const handler = async (event: APIGatewayEvent, context: Context, callback: Function) => {
/* ... process information */
  const headers = {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Credentials': true
    }
  const response = {
            statusCode: 201,
            headers,
            body: JSON.stringify({ OK: true })
        }
}

And in my frontend I run requests with Axios. Axios is configured this way:

import axios from 'axios'
import { useAuthStore } from '@/stores/authStore';
const authStore = useAuthStore();

const api = axios.create({
  baseURL: 'https://zgrciu0uce.execute-api.us-east-1.amazonaws.com/dev',
  headers: {
    'Content-Type': 'application/json',
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Headers': 'Content-Type',
   'Authorization': `${authStore.tokenType} ${authStore.accessToken}`
  },
});
export { api }

Then in my .vue components, I just use the axios exported before:

import { api } from '@/libs/axios'

await api.post('/auth/createUserFromAdmin', newUser) // this line throws the error (see beginning of this post).

I wonder how could I fix this?

There could be a number of reasons why CORS error occur. Try the following solutions

Update the Lambda Handler Response Headers

Ensure the handler in your Lambda function returns the correct CORS headers, especially Access-Control-Allow-Origin, Access-Control-Allow-Headers, and Access-Control-Allow-Credentials.

javascript

Copy code

export const handler = async (event, context, callback) => {
  const headers = {
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Credentials': true,
    'Access-Control-Allow-Headers': 'Content-Type, Authorization'
  };
  
  const response = {
    statusCode: 201,
    headers,
    body: JSON.stringify({ OK: true })
  };
  return response;
};

Remove Access-Control-Allow-Origin Header from Axios Configuration

Including Access-Control-Allow-Origin in your Axios headers can cause conflicts, as browsers don’t allow clients to set Access-Control-* headers manually. Remove it from the Axios configuration:

javascript

Copy code

const api = axios.create({
  baseURL: 'https://zgrciu0uce.execute-api.us-east-1.amazonaws.com/dev',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `${authStore.tokenType} ${authStore.accessToken}`
  },
});

Clear Cache and Retry

After deploying these changes, you might want to clear your browser’s cache and try again

Let me know if this helps, if not, it might be the api gateway configuration