'CORS error with OPTIONS request using AWS CDK

I am using AWS CDK to run a RESTful API and I am getting the following preflight error when calling a POST endpoint:

Access to fetch at 'http://localhost:4000/login' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.

I understand that the message says I should not be using a wildcard for the allow origin header but I don't believe I am. Here is my CDK config for the API:

const api = new RestApi(this, 'frontend-api', {
  restApiName: 'Frontend Service',
  description: 'This service serves the frontend.'
  defaultCorsPreflightOptions: {
    allowOrigins: [process.env.FRONTEND_URL],
    allowCredentials: true
  } 
});

const loginLambda = new NodejsFunction(this, 'loginFunction', {
  entry: 'dist/src/lambda/login.js',
  functionName: 'login',
});

const loginIntegration = new LambdaIntegration(loginLambda);
const loginResource = api.root.addResource('login');
loginResource.addMethod('POST', loginIntegration);

Here is the login lambda resoler

export const handler = async (event: any, context: any) => {
    return {
      statusCode: 200,
      body: JSON.stringify({
        success: true
      }),
      headers: {
        'Access-Control-Allow-Origin': [process.env.FRONTEND_URL],
        'Access-Control-Allow-Credentials': 'true',
        'Set-Cookie': serialize(
          'auth',
          'test',
          {
            httpOnly: true,
            expires: 'Sat, 21 Oct 2023 07:28:00 GMT'
          }
        )
      }
    };
}

As you can see I am not setting the origin to * so I am unsure why it's giving me the above error?

Just as a note I am running my lambda functions locally using sam local start-api - i'm not sure if this could be impacting the OPTIONS response?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source