방종민 블로그?
Next13 하루 한 번 재배포 설정(vercel cron job) 본문
배경: SSG를 사용하여 하루에 한 번 업데이트하기 위해 Vercel의 Cron Jobs 기능을 활용
/app/api/cron/route.ts
: 일정 주기마다 반복할 코드를 생성합니다.
deploy hook url 가져오기
deploy hook url: 특정 브랜치를 배포 트리거 URL
vercel의 setting -> Git 메뉴에 있습니다.
아래 코드에서는 환경변수로 입력했기에 vercel(setting -> Environment Variables)에서도 추가해줘야합니다.
code
import fetch from "node-fetch";
import { NextRequest, NextResponse } from "next/server";
export async function POST(req: NextRequest, res: NextResponse) {
const deployHookUrl = process.env.DEPLOY_HOOK_URL;
if (!deployHookUrl) {
console.error("Deploy hook URL is not defined.");
return new NextResponse("Deploy hook URL is not defined.", { status: 500 });
}
try {
const deployResponse = await fetch(deployHookUrl, {
method: "POST",
});
console.log(`Deploy hook called at ${new Date().toISOString()}`);
if (deployResponse.ok) {
return new NextResponse("Deploy triggered successfully!", {
status: 200,
});
} else {
return new NextResponse("Failed to trigger deploy.", {
status: deployResponse.status,
});
}
} catch (error: any) {
console.error("Error triggering deploy:", error.message);
return new NextResponse("Error triggering deploy: " + error.message, {
status: 500,
});
}
}
- app 디렉토리: `get`, `post`등 메서드별로 함수를 정의하고 export
- pages 디렉토리: `default`로 핸들러 함수를 내보냄
- 브라우저 환경에서 실행되지 않기에 node-fetch 사용
/vercel.json
{
"crons": [
{
"path": "/api/cron",
"schedule": "0 3 * * *"
}
]
}
크론 파일의 위치와 스케줄을 정해줍니다.
스케줄은 UTC를 기준으로 아래의 형식을 가집니다.
* * * * *
| | | | |
| | | | +----- 요일 (0 - 7) (0, 7 = 일요일, 1 = 월요일, ..., 6 = 토요일)
| | | +------- 월 (1 - 12)
| | +--------- 일 (1 - 31)
| +----------- 시 (0 - 23)
+------------- 분 (0 - 59)
참조
https://nextjs.org/docs/app/building-your-application/routing/route-handlers
'etc' 카테고리의 다른 글
깃허브 파일명 대소문자 적용 안될 때 (0) | 2023.05.07 |
---|