AWS CDK 와 hono 에서 CORS 처리하기

3 minute read
2024-08-22

serverless 로 사용하려했지만 v4 로 올라온 이후 알 수 없는 에러가 많아졌기에 다시 hono & cdk 로 눈을 돌렸다.


세팅 순서

hono 공식문서를 참고했다.


프로젝트 생성

project init
mkdir my-app
cd my-app
 
cdk init app -l typescript
 
npm i hono
mkdir lambda
touch lambda/index.ts


디렉토리를 알아서 생성해주고 의존성과 파일도 모두 직접 만들어준다.


함수 작성

lambda/index.ts
import { Hono } from 'hono';
import { handle } from 'hono/aws-lambda';
import { cors } from 'hono/cors';
 
const app = new Hono();
 
app.get(
  '/',
  cors({
    origin: "*",
  }),
  (c) => c.text('Hello Hono!')
);
 
export const handler = handle(app);
 
export default app;
 


cross origin 에 모든 출처를 허용하기 위해 (간단하게) 별표로 추가해주었다.


  cors({
    origin: "*",
  }),


cdk stack

lib/hono-getstarted-stack.ts
import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import * as apigw from 'aws-cdk-lib/aws-apigateway';
import { NodejsFunction } from 'aws-cdk-lib/aws-lambda-nodejs';
 
export class HonoGetstartedStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);
 
    // ref) https://hono.dev/docs/getting-started/aws-lambda
    const fn = new NodejsFunction(this, 'lambda', {
      entry: 'lambda/index.ts',
      handler: 'handler',
      runtime: lambda.Runtime.NODEJS_20_X,
    });
    
    fn.addFunctionUrl({
      authType: lambda.FunctionUrlAuthType.NONE,
    });
    new apigw.LambdaRestApi(this, 'myapi', {
      handler: fn,
      defaultCorsPreflightOptions: {
        allowOrigins: ["*"],
      },
    });
  }
}
 


CORS 특정 출처만 허용하도록 하기

만약 특정 출처만 허용하고 싶다면 아래와 같이 수정하면 된다. 결론적으로 hono/corscdk-stack 2곳 모두 수정해줘야한다.


insert hono/cors
import { cors } from 'hono/cors'
 
app.get(
  '/',
  cors({
    origin: ["http://localhost:3000"],
  }),
)


update cdk-stack
// ...
new apigw.LambdaRestApi(this, 'myapi', {
  handler: fn,
  	defaultCorsPreflightOptions: {
    	allowOrigins: ["http://localhost:3000"],
  	},
  });
})


그리고 cdk 업데이트하기 위한 cdk deploy 만 호출하면 끝.