AWS CDK 와 hono 에서 CORS 처리하기
3 minute read
2024-08-22
serverless 로 사용하려했지만 v4 로 올라온 이후 알 수 없는 에러가 많아졌기에 다시 hono & cdk 로 눈을 돌렸다.
세팅 순서
hono 공식문서를 참고했다.
프로젝트 생성
mkdir my-app
cd my-app
cdk init app -l typescript
npm i hono
mkdir lambda
touch 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
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/cors 와 cdk-stack 2곳 모두 수정해줘야한다.
import { cors } from 'hono/cors'
app.get(
'/',
cors({
origin: ["http://localhost:3000"],
}),
)// ...
new apigw.LambdaRestApi(this, 'myapi', {
handler: fn,
defaultCorsPreflightOptions: {
allowOrigins: ["http://localhost:3000"],
},
});
})그리고 cdk 업데이트하기 위한 cdk deploy 만 호출하면 끝.