# Errors with CORS and preflight request - API Gateway + Lambda

**URL:** <https://forum.serverless.com/t/errors-with-cors-and-preflight-request-api-gateway-lambda/20718>\
**Category:** Serverless Framework\
**Tags:** aws, lambda, api-gateway\
**Created:** [October 29, 2024, 2:10pm UTC](https://forum.serverless.com/t/errors-with-cors-and-preflight-request-api-gateway-lambda/20718 "2024-10-29T14:10:56Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![lucas1068](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.serverless.com/lucas1068/32/8063_2.png) [@lucas1068](https://forum.serverless.com/u/lucas1068)\
**Post date:** [October 29, 2024, 2:10pm UTC](https://forum.serverless.com/t/errors-with-cors-and-preflight-request-api-gateway-lambda/20718/1 "2024-10-29T14:10:56Z")

</div>

This error occurs using `API Gateway v1` with `lambda-proxy`.  
Browser client is doing a preflight request (option): 502 error

 ![2024-10-29_11h02_20](https://canada1.discourse-cdn.com/flex036/uploads/serverless/original/2X/0/0d430c4dcfb48ad42f316b5b6460cabb56d6f3aa.png)

Then the actual request (post): CORS error

 ![2024-10-29_11h03_23](https://canada1.discourse-cdn.com/flex036/uploads/serverless/original/2X/4/44afa890adf8fe513f61dc5e11e0115dd806de5b.png)

My `serverless.yaml` is configured this way:

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

```

And my lambda function has this code:

```ts
import { InternalUserCognitoService } from './../services/InternalUserCognitoService';
import { InternalUserPrismaService } from './../services/InternalUserPrismaService'
import { APIGatewayEvent, Context } from 'aws-lambda';
import { cognitoGroupNameZodSchema } from '../../../shared/zod/modules/Auth/Auth.zod'
import { ZodError } from 'zod';
import { IBodyHttpResponse, Empty } from '../../../shared/types/RequestResponse/api.types'

export const handler = async (event: APIGatewayEvent, context: Context /*, callback: Function*/) => {
    const { email, username, fullname, group } = JSON.parse(event.body || '')
    const headers = {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Headers': 'Content-Type,Authorization',
        'Access-Control-Allow-Methods': 'GET,POST,PUT,OPTIONS',
        'Access-Control-Allow-Credentials': true,
    };

    if (event.httpMethod === 'OPTIONS') {
        // Handle preflight request
        return {
            statusCode: 200,
            headers,
            body: null,
        };
    }
    try {
        cognitoGroupNameZodSchema.parse(group)
    } catch (e) {
        if (e instanceof ZodError) {
            const body: IBodyHttpResponse<Empty> = {
                status: 'error',
                message: e.message,
                data: {}
            }
            return {
                statusCode: 400,
                headers,
                body: JSON.stringify(body)
            }
        }
    }
    try {
        await InternalUserCognitoService.createUserFromAdmin(username, email, fullname, group) // Se crea el usuario con el servicio de AWS Cognito.
        await InternalUserPrismaService.createUserFromAdmin(username, email, fullname, group) // Se crea un row en la db con información del usuario.

        // Return success message
        const body: IBodyHttpResponse<Empty> = {
            status: 'success',
            message: 'Usuario creado satisfactoriamente y agregado al grupo',
            data: {}
        }

        return {
            statusCode: 201,
            headers,
            body: JSON.stringify(body)
        }
    } catch (error) {
        console.error('Error creating user or adding to group:', error);
        const body: IBodyHttpResponse<Empty> = {
            status: 'error',
            message: 'Error al crear el usuario o agregarlo al grupo.',
            data: {
                error
            }
        }
        return {
            statusCode: 500,
            headers,
            body: JSON.stringify(body)
        };
    }
}

```

I wonder why I’m getting CORS error. From the browser’s console:

```bash
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: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

```

```bash
POST https://zgrciu0uce.execute-api.us-east1.amazonaws.com/dev/auth/createUserFromAdmin net::ERR_FAILED

```

My client is an SPA with Vue that is running locally ([http://localhost:5173/](http://localhost:5173/)). I don’t know if the error is because I’m running locally, or I have some misconfiguration. Any help?

---

<div class="post-metadata">

**Author:** ![TomC](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.serverless.com/tomc/32/4002_2.png) [@TomC](https://forum.serverless.com/u/TomC)\
**Post date:** [November 1, 2024, 3:48pm UTC](https://forum.serverless.com/t/errors-with-cors-and-preflight-request-api-gateway-lambda/20718/2 "2024-11-01T15:48:41Z")

</div>

Can you find and show us the OPTIONS HTTP call request and response ?

---

<div class="post-metadata">

**Author:** ![beenmeckel](https://avatars.discourse-cdn.com/v4/letter/b/8dc957/32.png) [@beenmeckel](https://forum.serverless.com/u/beenmeckel)\
**Post date:** [March 17, 2026, 12:11am UTC](https://forum.serverless.com/t/errors-with-cors-and-preflight-request-api-gateway-lambda/20718/3 "2026-03-17T00:11:49Z")

</div>

CORS and preflight errors with API Gateway and Lambda usually stem from missing or misconfigured response headers on either the API Gateway level (for the OPTIONS preflight request) or within the Lambda function itself (for the actual request). The specific fix depends on whether you are using a REST API or an HTTP API and whether you are using a proxy or non-proxy integration.

[snaptube](https://snaptube.cam/)[vidmate](https://vidmate.bid/)
