Search code examples
amazon-web-servicesamazon-s3aws-lambdacorsserverless

ERROR: has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource


I made an app, I hosted it with Serverless AWS... I am new to AWS and I don't know why I am getting this error: "has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource."... When I run my backend locally with the command sls offline it's working fine with my localhost:4000... but when I try to use my deployed backend it doesn't work..

My backend is in Nest.js and frontend on Next.js, using typescript.

this is my serverles.ts file:

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import * as cors from 'cors';
import serverlessExpress from '@vendia/serverless-express';
import { Callback, Context, Handler } from 'aws-lambda';

let server: Handler;

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  const cors = require('cors');
  app.use(
    cors({
      origin: 'http://localhost:3000', // Allow your frontend server
      credentials: true, // Allow credentials (cookies) to be sent with requests
    }),
  );

  await app.init();

  const expressApp = app.getHttpAdapter().getInstance();
  return serverlessExpress({ app: expressApp });
}

export const handler: Handler = async (
  event: any,
  context: Context,
  calback: Callback,
) => {
  server = server ?? (await bootstrap());
  return server(event, context, calback);
};

and this is my serverless.yaml :

service: <value>

useDotenv: true

plugins:
  - serverless-offline
  - serverless-plugin-common-excludes 
  - serverless-plugin-include-dependencies

provider:
  name: aws
  runtime: nodejs18.x
  region: eu-west-1
  memorySize: 1024
  stage: ${opt:stage, 'dev'}
  httpApi:
    cors: true
    
  environment:
    JWT_SECRET: ${env:JWT_SECRET}
    JWT_EXPIRE: ${env:JWT_EXPIRE}

    DB_URI: ${env:DB_URI}

    TZ: ${env:TZ}

    AWS_S3_REGION: ${env:AWS_S3_REGION}

    UPLOAD_RATE_TTL: ${env:UPLOAD_RATE_TTL}
    UPLOAD_RATE_LIMIT: ${env:UPLOAD_RATE_LIMIT}

functions:
  main:
    handler: dist/serverless.handler
    timeout: 30
    role: <value>
    events:
      - http:
          path: /
          method: ANY
          cors: true
      - http:
          path: "{proxy+}"
          method: ANY
          cors: true
custom:
 serverless-offline:
   httpPort: 4000

I also enabled cors in my aws console as you can see in the photo bellow: enter image description here


Solution

  • I found the solution, actually it was very easy. All I had to do was to add the headers manually in my handler

      const response = await server(event, context, callback);
    
      // Add CORS headers to the response
      response.headers = {
        ...response.headers,
        'Access-Control-Allow-Origin': '*', // Replace with your frontend domain
        'Access-Control-Allow-Credentials': 'true',
      };