Pages API
Cloudflare Pages API를 사용하면 프로젝트와 배포를 프로그래밍 방식으로 관리할 수 있습니다. CI/CD 파이프라인 통합, 자동화된 배포, 프로젝트 관리 등에 활용할 수 있습니다.
인증
API 토큰 생성
- Cloudflare 대시보드에서 My Profile > API Tokens 이동
- Create Token 클릭
- 다음 중 하나 선택:
- Edit Cloudflare Workers 템플릿 사용
- 커스텀 토큰 생성 시 Cloudflare Pages 권한을 Edit으로 설정
필요한 권한
| 권한 | 설명 |
|---|---|
Pages:Read | 프로젝트 및 배포 정보 조회 |
Pages:Edit | 프로젝트 생성, 배포, 삭제 |
인증 헤더
모든 API 요청에 Bearer 토큰을 포함합니다:
Authorization: Bearer $CLOUDFLARE_API_TOKEN기본 엔드포인트
Base URL
https://api.cloudflare.com/client/v4/accounts/{account_id}/pages/projects필수 정보
- account_id: Cloudflare 계정 ID (대시보드 URL 또는 Overview 페이지에서 확인)
- project_name: Pages 프로젝트 이름
프로젝트 관리
모든 프로젝트 조회
curl -X GET "https://api.cloudflare.com/client/v4/accounts/{account_id}/pages/projects" \ -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \ -H "Content-Type: application/json"특정 프로젝트 조회
curl -X GET "https://api.cloudflare.com/client/v4/accounts/{account_id}/pages/projects/{project_name}" \ -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \ -H "Content-Type: application/json"프로젝트 생성
curl -X POST "https://api.cloudflare.com/client/v4/accounts/{account_id}/pages/projects" \ -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \ -H "Content-Type: application/json" \ --data '{ "name": "my-project", "production_branch": "main" }'프로젝트 삭제
curl -X DELETE "https://api.cloudflare.com/client/v4/accounts/{account_id}/pages/projects/{project_name}" \ -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"배포 관리
모든 배포 조회
curl -X GET "https://api.cloudflare.com/client/v4/accounts/{account_id}/pages/projects/{project_name}/deployments" \ -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \ -H "Content-Type: application/json"특정 배포 조회
curl -X GET "https://api.cloudflare.com/client/v4/accounts/{account_id}/pages/projects/{project_name}/deployments/{deployment_id}" \ -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \ -H "Content-Type: application/json"배포 삭제
curl -X DELETE "https://api.cloudflare.com/client/v4/accounts/{account_id}/pages/projects/{project_name}/deployments/{deployment_id}" \ -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"참고: 각 브랜치의 최신 배포는 삭제할 수 없습니다.
배포 재시도
curl -X POST "https://api.cloudflare.com/client/v4/accounts/{account_id}/pages/projects/{project_name}/deployments/{deployment_id}/retry" \ -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"배포 롤백
curl -X POST "https://api.cloudflare.com/client/v4/accounts/{account_id}/pages/projects/{project_name}/deployments/{deployment_id}/rollback" \ -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"Direct Upload
Git 연동 없이 빌드된 에셋을 직접 업로드하여 배포할 수 있습니다.
1. 업로드 토큰 받기
curl -X POST "https://api.cloudflare.com/client/v4/accounts/{account_id}/pages/projects/{project_name}/deployments" \ -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \ -H "Content-Type: application/json" \ --data '{ "branch": "main" }'2. 파일 업로드
curl -X POST "https://api.cloudflare.com/client/v4/accounts/{account_id}/pages/projects/{project_name}/deployments/{deployment_id}/files" \ -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \ -F "files=@dist/index.html" \ -F "files=@dist/style.css"Wrangler 사용 (권장)
Direct Upload는 Wrangler CLI를 사용하는 것이 더 간편합니다:
# 빌드 후 직접 배포npm run buildnpx wrangler pages deploy dist환경 변수 관리
환경 변수 조회
curl -X GET "https://api.cloudflare.com/client/v4/accounts/{account_id}/pages/projects/{project_name}" \ -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \ -H "Content-Type: application/json"환경 변수 설정
curl -X PATCH "https://api.cloudflare.com/client/v4/accounts/{account_id}/pages/projects/{project_name}" \ -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \ -H "Content-Type: application/json" \ --data '{ "deployment_configs": { "production": { "env_vars": { "API_KEY": { "type": "plain_text", "value": "my-api-key" }, "SECRET": { "type": "secret_text", "value": "my-secret" } } }, "preview": { "env_vars": { "API_KEY": { "type": "plain_text", "value": "preview-api-key" } } } } }'빌드 설정 관리
빌드 설정 업데이트
curl -X PATCH "https://api.cloudflare.com/client/v4/accounts/{account_id}/pages/projects/{project_name}" \ -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \ -H "Content-Type: application/json" \ --data '{ "build_config": { "build_command": "npm run build", "destination_dir": "dist", "root_dir": "/" } }'실전 활용 예시
GitHub Actions에서 배포
name: Deploy to Cloudflare Pages
on: push: branches: [main]
jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4
- name: Setup Node.js uses: actions/setup-node@v4 with: node-version: '20'
- name: Install dependencies run: npm ci
- name: Build run: npm run build
- name: Deploy to Cloudflare Pages run: npx wrangler pages deploy dist --project-name=my-project env: CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}예약된 빌드 (Cron)
Cloudflare Workers의 Cron Trigger를 사용하여 정기적으로 빌드를 실행할 수 있습니다:
export default { async scheduled(event, env, ctx) { const response = await fetch( `https://api.cloudflare.com/client/v4/accounts/${env.ACCOUNT_ID}/pages/projects/${env.PROJECT_NAME}/deployments`, { method: 'POST', headers: { 'Authorization': `Bearer ${env.API_TOKEN}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ branch: 'main', }), } );
const result = await response.json(); console.log('Build triggered:', result); },};name = "scheduled-build"main = "src/index.js"
[triggers]crons = ["0 0 * * *"] # 매일 자정에 실행
[vars]PROJECT_NAME = "my-project"ACCOUNT_ID = "your-account-id"오래된 배포 정리
// 30일 이상 된 프리뷰 배포 삭제async function cleanupOldDeployments(env) { const thirtyDaysAgo = new Date(); thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
const response = await fetch( `https://api.cloudflare.com/client/v4/accounts/${env.ACCOUNT_ID}/pages/projects/${env.PROJECT_NAME}/deployments`, { headers: { 'Authorization': `Bearer ${env.API_TOKEN}`, }, } );
const { result } = await response.json();
for (const deployment of result) { // 프로덕션 배포는 건너뛰기 if (deployment.environment === 'production') continue;
const createdAt = new Date(deployment.created_on); if (createdAt < thirtyDaysAgo) { await fetch( `https://api.cloudflare.com/client/v4/accounts/${env.ACCOUNT_ID}/pages/projects/${env.PROJECT_NAME}/deployments/${deployment.id}`, { method: 'DELETE', headers: { 'Authorization': `Bearer ${env.API_TOKEN}`, }, } ); console.log(`Deleted deployment: ${deployment.id}`); } }}프로젝트 정보 대시보드
// 모든 프로젝트의 최신 배포 상태를 HTML로 출력async function getProjectsDashboard(env) { const response = await fetch( `https://api.cloudflare.com/client/v4/accounts/${env.ACCOUNT_ID}/pages/projects`, { headers: { 'Authorization': `Bearer ${env.API_TOKEN}`, }, } );
const { result } = await response.json();
let html = '<html><body><h1>Pages Projects</h1><ul>';
for (const project of result) { const latestDeployment = project.latest_deployment; const status = latestDeployment?.latest_stage?.status || 'unknown'; const url = `https://${project.subdomain}.pages.dev`;
html += ` <li> <strong>${project.name}</strong> <br>Status: ${status} <br>URL: <a href="${url}">${url}</a> </li> `; }
html += '</ul></body></html>'; return html;}응답 형식
성공 응답
{ "success": true, "errors": [], "messages": [], "result": { "id": "deployment-id", "url": "https://abc123.my-project.pages.dev", "environment": "production", "created_on": "2024-01-01T00:00:00Z", "latest_stage": { "name": "deploy", "status": "success" } }}에러 응답
{ "success": false, "errors": [ { "code": 1000, "message": "Authentication error" } ], "messages": [], "result": null}제한 사항
Rate Limits
- API 요청은 Cloudflare의 일반적인 rate limit이 적용됩니다
- 대량의 배포 삭제 시 적절한 딜레이 추가 권장
배포 삭제 제한
- 각 브랜치의 최신 배포는 삭제할 수 없습니다
- 프로덕션 브랜치의 활성 배포는 삭제할 수 없습니다