
How to Deploy an Astro Website for Free
Architect, configure, and automate the deployment of an Astro application to production-grade, zero-cost edge infrastructure using Cloudflare Pages and...
Enterprise software engineering is defined by pragmatic trade-offs: performance, operational overhead, resilience, and total cost of ownership (TCO). While enterprise infrastructure budgets are substantial, deploying internal tools, architectural proof-of-concepts (PoCs), documentation hubs, and greenfield microsites should not require provisioning dedicated Kubernetes clusters, orchestrating complex AWS ECS tasks, or paying exorbitant egress fees.
Astro has established itself as a premier web framework for content-dense, performance-critical web applications. Its default zero-JavaScript output, paired with partial hydration via the Islands Architecture, produces exceptionally lean static assets.
When paired with modern edge networks—specifically Cloudflare Pages, GitHub Pages, or Vercel—you can deploy high-traffic, globally distributed, enterprise-grade Astro applications with sub-50ms Time-to-First-Byte (TTFB) on a permanent $0 infrastructure budget.
This guide explores the architectural blueprints, automation patterns, and edge configurations necessary to run Astro in production on zero-cost edge infrastructure without compromising enterprise governance, security, or reliability.
The Edge Runtime Matrix: Evaluating Zero-Cost Targets
Before writing configuration code, we must evaluate the underlying execution models of leading edge providers. The phrase “free tier” in an enterprise context demands rigorous scrutiny regarding compute limits, edge execution, bandwidth thresholds, and vendor lock-in.
| Technical Vector | Cloudflare Pages | Vercel (Hobby) | GitHub Pages |
|---|---|---|---|
| Execution Model | V8 Isolates (Workers) | Node.js Serverless / V8 Edge | Pure Static (No Compute) |
| Bandwidth Limits | Unlimited (Fair Use) | 100 GB / month | 100 GB / month |
| Dynamic Compute | 100k requests/day | 100k requests/day | None |
| Max Payload Size | 25 MB per asset | 100 MB total deployment | 1 GB total deployment |
| Edge Cold Starts | < 5ms (Isolate startup) | 50ms - 250ms (Node/V8) | N/A (Static Only) |
| Commercial Use | Allowed | Heavily Restricted | Allowed (Non-monetized) |
The Strategic Recommendation: Cloudflare Pages
For enterprise engineering teams, Cloudflare Pages is the target platform of choice.
Unlike Vercel’s Hobby tier—which legally restricts commercial use and aggressively throttles bandwidth—Cloudflare Pages permits commercial applications on its free tier, imposes zero egress fees, provides unlimited static asset bandwidth, and executes server-rendered dynamic logic via Cloudflare Workers (V8 Isolates).
[ DNS Query via Route53 / Cloudflare ]
│
▼
[ Anycast Global Edge Network ]
│
┌───────────────────────────┴───────────────────────────┐
│ │
Static Asset Requested Dynamic Route / API Hit
│ │
▼ ▼
[ Cloudflare CDN Cache ] [ V8 Isolate Worker ]
(Immutable Asset Storage) (Edge SSR via Astro Engine)
│ │
Cache Hit │ Cache Miss │
▼ ▼
Serve to Client [ Upstream Enterprise API ]
(Datadog, CRM, DB via HTTPS)
Architectural Topology: SSG vs. Edge SSR
Astro supports two primary operational modes: Static Site Generation (SSG) and Server-Side Rendering (SSR) via Edge Adapters.
-
Static Site Generation (
output: 'static'): Pages are pre-rendered into static HTML, CSS, and client-side JavaScript bundles at build time. This provides the highest security posture (no runtime server execution), virtually zero compute overhead, and instant worldwide edge distribution. -
Server-Side Rendering (
output: 'server'or'hybrid'): Pages are executed on demand at the edge. Astro compiles your components into edge-compatible JavaScript that executes within a V8 Isolate sandbox upon every HTTP request. This mode is mandatory for personalized dashboards, authenticated sessions, dynamic API proxies, and A/B split-testing.
To demonstrate enterprise versatility, we will build for Hybrid Rendering, leveraging static compilation for public pages while offloading secure, dynamic routes to edge runtime workers.
Step 1: Adapter and Project Configuration
Initialize or update your Astro project to target Cloudflare’s edge runtime.
Install the official Cloudflare adapter:
npm install --save-dev @astrojs/cloudflare
Configure astro.config.mjs to enable the Cloudflare adapter with hybrid rendering capabilities and granular routing rules:
// astro.config.mjs
import { defineConfig } from 'astro/config';
import cloudflare from '@astrojs/cloudflare';
import tailwind from '@astrojs/tailwind';
export default defineConfig({
// 'hybrid' enables static by default, dynamic when 'export const prerender = false'
output: 'hybrid',
adapter: cloudflare({
imageService: 'compile',
platformProxy: {
enabled: true, // Enables local emulation of Cloudflare bindings (KV, D1, Queues)
},
routes: {
extend: {
include: [{ pattern: '/api/*' }, { pattern: '/dashboard/*' }],
exclude: [{ pattern: '/assets/*' }, { pattern: '/_astro/*' }]
}
}
}),
integrations: [tailwind()],
build: {
inlineStylesheets: 'auto',
},
vite: {
build: {
cssMinify: 'lightningcss',
}
}
});
Understanding _routes.json Optimization
By default, edge providers attempt to proxy all incoming requests through an edge function unless explicitly instructed otherwise. Cloudflare manages this via an auto-generated _routes.json file.
The configuration above ensures that static assets (/_astro/*, images, fonts) bypass the worker entirely and are resolved directly by Cloudflare’s high-performance static cache layer. Only dynamic application paths (/api/*, /dashboard/*) invoke V8 worker compute, conserving your 100,000 free daily worker invocations.
Step 2: Hybrid Route Implementation
To observe dynamic compute in action without losing SSG efficiency, define an API route executing at the edge.
Create a hybrid endpoint at src/pages/api/edge-telemetry.ts:
// src/pages/api/edge-telemetry.ts
import type { APIRoute } from 'astro';
// Force dynamic execution at the edge; bypass build-time prerendering
export const prerender = false;
interface EdgeMetadata {
colo: string;
country: string;
city: string;
clientIp: string;
asn: number;
}
export const GET: APIRoute = async ({ request }) => {
// Extract Cloudflare-specific request headers injected at the edge
const colo = request.headers.get('cf-ray')?.split('-')[1] || 'UNKNOWN';
const country = request.headers.get('cf-ipcountry') || 'US';
const city = request.headers.get('cf-ipcity') || 'Edge';
const clientIp = request.headers.get('cf-connecting-ip') || '127.0.0.1';
const asn = Number(request.headers.get('cf-asn') || '0');
const telemetry: EdgeMetadata = {
colo,
country,
city,
clientIp: clientIp.replace(/(\d+)\.(\d+)\.(\d+)\.(\d+)/, '$1.$2.***.***'), // Anonymize IP
asn
};
return new Response(JSON.stringify({
timestamp: new Date().toISOString(),
status: 'HEALTHY',
edge: telemetry,
runtime: 'Cloudflare-V8-Isolate'
}), {
status: 200,
headers: {
'Content-Type': 'application/json',
'Cache-Control': 'no-store, no-cache, must-revalidate',
'Strict-Transport-Security': 'max-age=63072000; includeSubDomains; preload'
}
});
};
This endpoint demonstrates zero-latency edge introspection: extracting geographically localized data points directly from incoming network packets at the nearest Point of Presence (PoP) without executing downstream origin database calls.
Step 3: Enterprise Hardening and Custom Headers
Security is a primary friction point when deploying outside traditional enterprise VPC networks. Free edge platforms default to permissive security policies. We must enforce enterprise-grade HTTP security headers, including a rigid Content Security Policy (CSP) and HTTP Strict Transport Security (HSTS).
Cloudflare Pages processes static routing and header definitions through flat configuration files located within the public/ directory.
Create public/_headers:
/*
X-Frame-Options: DENY
X-Content-Type-Options: nosniff
Referrer-Policy: strict-origin-when-cross-origin
Permissions-Policy: accelerometer=(), camera=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), payment=(), usb=()
Strict-Transport-Security: max-age=63072000; includeSubDomains; preload
Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self'; connect-src 'self' https://api.enterprise.domain; frame-ancestors 'none';
/_astro/*
Cache-Control: public, max-age=31536000, immutable
Header Analysis
Content-Security-Policy: Restricts the origin of scripts, styles, and XHR connections. It prevents Cross-Site Scripting (XSS) and data injection attacks.Strict-Transport-Security: Sets the HSTS lifetime to two years and submits the domain to the browser preload list, enforcing HTTPS exclusively.- Cache-Control for
/_astro/*: Astro generates content-hashed assets (client.[hash].js,style.[hash].css). Settingmax-age=31536000, immutabletells global browser caches and CDN nodes that these files will never mutate, eliminating revalidation roundtrips.
Step 4: Enterprise CI/CD Pipeline via GitHub Actions
Connecting your production platform via third-party web dashboard authorizations (like giving a vendor OAuth read/write access to your entire GitHub enterprise organization) violates the principle of least privilege.
Instead, construct a headless, fully auditable Continuous Integration and Continuous Deployment (CI/CD) pipeline using GitHub Actions and Cloudflare’s command-line interface, Wrangler.
┌──────────────┐ ┌──────────────────────┐ ┌──────────────────────┐
│ Git Push to │ ──> │ GitHub Actions Node: │ ──> │ Cloudflare Pages: │
│ main branch │ │ Build & Audit │ │ Direct Asset Upload │
└──────────────┘ └──────────────────────┘ └──────────────────────┘
│ │
▼ ▼
[ Lint, Test, Bundle ] [ Deploy Edge Workers ]
[ Run Security Audits] [ Purge Edge Caches ]
1. Provision IAM Credentials
- Navigate to the Cloudflare Dashboard -> My Profile -> API Tokens.
- Create a token with the Cloudflare Pages: Edit permission.
- Extract your Account ID from the Cloudflare Pages overview page.
- Add these credentials to your GitHub repository under Settings -> Secrets and variables -> Actions:
CLOUDFLARE_API_TOKENCLOUDFLARE_ACCOUNT_ID
2. Configure the GitHub Actions Workflow
Create .github/workflows/deploy.yml:
name: Production Edge Pipeline
on:
push:
branches:
- main
pull_request:
branches:
- main
permissions:
contents: read
deployments: write
pull-requests: write
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
audit-and-build:
name: Build & Verify
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: Checkout Repository
uses: actions/checkout@v4
- name: Setup Node.js Runtime
uses: actions/setup-node@v4
with:
node-version: 20
cache: 'npm'
- name: Install Dependencies
run: npm ci
- name: Typecheck Application
run: npx astro check
- name: Production Compilation
run: npm run build
env:
NODE_ENV: production
- name: Upload Build Artifacts
uses: actions/upload-artifact@v4
with:
name: compiled-astro-bundle
path: dist/
retention-days: 1
deploy-to-edge:
name: Deploy to Edge Infrastructure
needs: audit-and-build
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- name: Checkout Source
uses: actions/checkout@v4
- name: Download Build Artifacts
uses: actions/download-artifact@v4
with:
name: compiled-astro-bundle
path: dist
- name: Publish to Cloudflare Pages (Production)
if: github.ref == 'refs/heads/main'
uses: cloudflare/wrangler-action@v3
with:
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
command: pages deploy dist --project-name=enterprise-astro-web --branch=main
- name: Publish to Cloudflare Pages (Preview)
if: github.event_name == 'pull_request'
id: deploy-preview
uses: cloudflare/wrangler-action@v3
with:
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
command: pages deploy dist --project-name=enterprise-astro-web --branch=${{ github.head_ref }}
Architectural Safeguards in This Pipeline
concurrencywithcancel-in-progress: true: Cancels outdated runs when new commits are pushed in rapid succession, preventing race conditions during deployments and saving continuous integration credits.- Deterministic Installs (
npm ci): Enforces absolute integrity using thepackage-lock.jsonmanifest. - Artifact Isolation: Builds the production package within an isolated container, passing the compiled
dist/directory across jobs via ephemeral GitHub artifacts. The deployment step never compiles source files; it simply deploys the verified bundle. - Ephemerality of Preview Environments: Pull requests trigger dynamic preview deployments associated with the specific Git branch, accessible via dedicated preview URLs for QA and security reviews prior to merging into production.
Step 5: Custom Domains and SSL/TLS Termination
A high-integrity enterprise deployment requires custom domain mapping with zero-downtime certificate rotation.
1. Cloudflare DNS Integration (Zero-Downtime)
If your enterprise DNS is already managed by Cloudflare, adding your custom domain to your deployment requires only an alias pointing to the Pages project:
- In the Pages Project Console, click Custom Domains -> Set up a domain.
- Enter
internal-docs.enterprise.com. - Cloudflare will automatically provision a CNAME record resolving internally to
enterprise-astro-web.pages.devand terminate SSL/TLS at the closest Anycast PoP.
2. External DNS Integration (AWS Route 53 / Azure DNS)
If your DNS is managed outside Cloudflare (e.g., via AWS Route 53), configure your authoritative nameserver with the following records:
; Custom Domain DNS Configuration for AWS Route 53 or BIND
internal-docs.enterprise.com. IN CNAME enterprise-astro-web.pages.dev.
To validate ownership and issue automated certificates through Cloudflare’s Let’s Encrypt / DigiCert pipeline, deploy an HTTP validation record or DNS challenge TXT record as prompted by the Cloudflare Pages control panel.
Enforcing Strict TLS 1.3
Under the Cloudflare SSL/TLS configuration tab:
- Set encryption mode to Full (Strict).
- Enable TLS 1.3 Only.
- Enable Automatic HTTPS Rewrites.
This ensures unencrypted HTTP traffic is rejected at the physical network edge before touching your application code or computing assets.
Step 6: Edge Performance Verification
Once deployed, validate your edge-rendered Astro application using curl to inspect the response headers, protocol negotiation, and edge routing behavior:
curl -svo /dev/null https://internal-docs.enterprise.com/api/edge-telemetry
Expected Response Output Analysis
* Connected to internal-docs.enterprise.com (104.21.42.12) port 443
* ALPN: offers h2, http/1.1
* TLSv1.3 (IN), TLS handshake, [Continuous Handshake...]
* SSL connection using TLSv1.3 / AEAD-CHACHA20-POLY1305-SHA256
< HTTP/2 200
< date: Mon, 24 Feb 2025 14:30:00 GMT
< content-type: application/json
< strict-transport-security: max-age=63072000; includeSubDomains; preload
< x-content-type-options: nosniff
< x-frame-options: DENY
< cf-cache-status: DYNAMIC
< cf-ray: 855d0e2e987a412b-IAD
< server: cloudflare
Key verifications:
ALPN: offers h2: Confirms multiplexed HTTP/2 protocol negotiation.cf-ray: ...-IAD: Confirms execution took place at the Washington D.C. (IAD) Anycast edge data center closest to the client.cf-cache-status: DYNAMIC: Verifies that the hybrid edge runtime evaluated dynamic logic without failing over to an error page.
Now, verify static caching by curling a static stylesheet or script:
curl -svo /dev/null https://internal-docs.enterprise.com/_astro/client.D1e45x9z.js
< HTTP/2 200
< cache-control: public, max-age=31536000, immutable
< cf-cache-status: HIT
< age: 41203
< server: cloudflare
cf-cache-status: HIT: The edge worker was completely bypassed; the asset was served directly from edge RAM caches in under 10 milliseconds.
Operational Guardrails: Navigating Free Tier Boundaries
While this architecture costs $0, enterprise systems require clear operational boundaries. You must design around the platform’s constraints rather than discovering them during a traffic surge.
[ Client Request Spikes ]
│
▼
[ Cloudflare Edge Layer ]
│
┌───────────┴───────────┐
▼ ▼
Static Asset? Dynamic Request?
(Unlimited) │
▼
[ Check Daily Quota ]
│
┌───────────────┴───────────────┐
▼ ▼
Under 100k Calls? Exceeded 100k Calls?
│ │
▼ ▼
Execute Worker HTTP 429 Rate Limit
(V8 Compute Sandbox) (Mitigate via Static Fallback)
Mitigation Strategies for Edge Compute Limits
- Maximize Static Hybrid Partitioning: Never make an entire site server-rendered unless strictly necessary. Mark content pages with
export const prerender = true. - Scale Inbound Traffic via Edge Caching: Use the
Cache-Controlheader inside SSR responses (s-maxage=60, stale-while-revalidate=300). This ensures that Cloudflare’s edge cache caches even dynamic routes for a limited period, converting 10,000 downstream hits into a single worker invocation. - Graceful Fallbacks for External APIs: Edge workers on the free tier feature a 10ms CPU execution cap (wall-clock time waiting on network calls does not count against this limit, but CPU processing does). Avoid heavy cryptographic hashing, unoptimized regular expressions, or massive array transformations within the worker context.
Conclusion
Building on free edge infrastructure is not merely an exercise in corporate frugality; it is an architectural pattern that optimizes speed, security, and developer productivity. By combining Astro’s content-optimized compilation with Cloudflare’s Anycast edge network, you eliminate infrastructure maintenance, remove patch-cycle overhead, and mitigate network egress costs.
With declarative CI/CD pipelines, strict HTTP security headers, and an intelligent hybrid rendering model, this architecture delivers an enterprise-grade web application that costs nothing to maintain, scales indefinitely to match sudden traffic spikes, and maintains sub-50ms latency across the globe.