Cloudflare CLI (Wrangler) Quickstart for Static Sites
Thom Wilson
·
Install and login
npm i -g wrangler
wrangler login
Preview and deploy
wrangler pages dev ./out
wrangler pages deploy ./out
Common tasks
- Set headers or redirects with a Worker in front of Pages.
- Use environment variables for API keys (KV / D1 where needed).
-
Automate deploys via GitHub Actions on push to
main.
Headers and redirects
For simple, build-time managed rules, include
_headers and _redirects files in your
build output directory (e.g., out/) before deploy.
# out/_headers
/*
X-Frame-Options: DENY
X-Content-Type-Options: nosniff
Referrer-Policy: no-referrer-when-downgrade
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
# Cache static assets aggressively
/assets/*
Cache-Control: public, max-age=31536000, immutable
# out/_redirects
/old-path /new-path 301
/legacy/* /docs/:splat 302
If you need runtime control, place a Worker in front of Pages and forward requests.
export default {
async fetch(request, env) {
const url = new URL(request.url);
// Example redirect
if (url.pathname === "/old-path") {
return Response.redirect(url.origin + "/new-path", 301);
}
// Forward to Pages origin
const origin = `https://YOUR_PAGES_DOMAIN.pages.dev${url.pathname}${url.search}`;
const res = await fetch(origin, request);
// Add security headers
const hdrs = new Headers(res.headers);
hdrs.set("X-Frame-Options", "DENY");
hdrs.set("X-Content-Type-Options", "nosniff");
return new Response(res.body, { status: res.status, headers: hdrs });
}
};
Environment variables and secrets
For Pages, define variables in the Cloudflare dashboard or via CLI. Use Environment variables for build-time config and Secrets for sensitive values.
# Set a Pages project secret interactively
wrangler pages project secret put API_KEY
# Set a variable from CI (non-interactive)
echo MY_VALUE | wrangler pages project secret put PUBLIC_BASE_URL --project-name=your-project
If you use a Worker/Functions at runtime, access with
env.MY_SECRET inside your handler.
GitHub Actions deploy
Use the official Pages action or Wrangler. Example using the Pages action:
name: Deploy to Cloudflare Pages
on:
push:
branches: [ main ]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
- run: npm ci
- run: npm run build
- name: Publish
uses: cloudflare/pages-action@v1
with:
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
projectName: your-project
directory: out
gitHubToken: ${{ secrets.GITHUB_TOKEN }}