0
0
AstroHow-ToBeginner ยท 4 min read

How to Deploy Astro to Cloudflare: Step-by-Step Guide

To deploy an Astro project to Cloudflare Pages, first build your site locally using npm run build. Then, connect your GitHub repository to Cloudflare Pages and set the build command to npm run build with the output directory as dist. Cloudflare will automatically deploy your site on each push.
๐Ÿ“

Syntax

Deploying Astro to Cloudflare Pages involves these key steps:

  • Build command: npm run build - compiles your Astro project into static files.
  • Output directory: dist - the folder where Astro puts the built files.
  • GitHub repository: Connect your project repo to Cloudflare Pages for automatic deployment.
bash
npm run build
# Output folder: dist/
๐Ÿ’ป

Example

This example shows how to deploy an Astro project to Cloudflare Pages using GitHub integration.

  1. Push your Astro project to GitHub.
  2. Go to Cloudflare Pages dashboard and create a new project.
  3. Connect your GitHub repo.
  4. Set the build command to npm run build and the output directory to dist.
  5. Click deploy and wait for Cloudflare to build and publish your site.
json/bash
{
  "scripts": {
    "build": "astro build"
  }
}

# Terminal commands
npm install
npm run build

# Cloudflare Pages settings
Build command: npm run build
Build output directory: dist
Output
โœ” Build completed โœ” Site deployed at https://your-project.pages.dev
โš ๏ธ

Common Pitfalls

Common mistakes when deploying Astro to Cloudflare include:

  • Not setting the output directory to dist, causing deployment to fail.
  • Forgetting to add npm install in the build step if dependencies are missing.
  • Not pushing the latest code to GitHub before deployment.
  • Using an older Astro version without support for static builds.
bash
Wrong build command:
npm run start

Right build command:
npm run build
๐Ÿ“Š

Quick Reference

Summary tips for deploying Astro to Cloudflare Pages:

  • Use npm run build to build your site.
  • Set output directory to dist.
  • Connect your GitHub repo to Cloudflare Pages.
  • Ensure your package.json has the correct build script.
  • Push changes to GitHub to trigger deployment.
โœ…

Key Takeaways

Always set the build command to 'npm run build' and output directory to 'dist' in Cloudflare Pages.
Connect your GitHub repository to Cloudflare Pages for automatic deployments on code push.
Make sure your Astro project has a proper build script in package.json.
Push your latest code to GitHub before deploying to avoid outdated builds.
Check Cloudflare Pages logs if deployment fails to catch build errors.