Skip to content
subuilds.dev

← logbuild #7 passed64e1a28

Setting Up GitLab CI/CD for Astro Blog Deployment to Cloudflare Pages

A complete guide to deploying your Astro blog automatically with GitLab CI/CD pipelines. It starts from nothing and ends with automatic builds, tests, and deployments.

· 14 min read

This guide automates the build, test, and deploy steps of your Astro blog. It uses GitLab CI/CD and Cloudflare Pages.

In Simple Words#

The problem
Every time you change your blog, you must build it and upload it by hand. This is slow, and a broken build can reach your readers.
The root cause
Nothing runs the build, the tests and the deployment for you. Every step depends on you to remember it and to do it the same way each time.
The solution
Add a .gitlab-ci.yml file to your repo. On every push, GitLab installs, builds and tests the site, then deploys it to Cloudflare Pages. Feature branches get a preview, and main goes to production after one click.
Think of it like this
Think of a kitchen with a fixed recipe. You hand in the ingredients, and the kitchen always cooks, tastes and serves the dish in the same order. A dish that tastes wrong never leaves the kitchen.

What is GitLab CI/CD?#

CI/CD means continuous integration and continuous deployment. A server builds, tests, and deploys your code for you after each change. GitLab has CI/CD built in. For an Astro blog, it gives you:

  • Automated Builds: The site is built on every push
  • Automated Tests: Check that your site builds correctly
  • Automated Deployments: The site goes to Cloudflare Pages with no manual steps
  • Pipeline Visualization: See the build status live
  • Artifact Storage: Keep build outputs for debugging and rollbacks (going back to an older version)

Key Components:#

Component Purpose
Pipeline Full workflow from push to deployment
Jobs Single tasks (build, test, deploy)
Stages Groups of jobs that run in order (build → test → deploy)
Runners Servers that run jobs
Artifacts Job outputs (built site, test reports)
Pipeline Editor Web IDE for .gitlab-ci.yml
Pipeline Schedules Builds that run on a schedule, like cron

Why Use GitLab CI/CD for Your Astro Blog?#

Benefits for Your Blog:#

  1. Zero Manual Deployment: You push, and the rest happens for you
  2. Build Verification: Find errors before they reach production
  3. Consistent Builds: The same environment every time
  4. Fast Rollbacks: Older build artifacts are always available
  5. Team Collaboration: Several authors, no deployment conflicts
  6. Security: Secrets (tokens and passwords) are stored safely in GitLab

Real-World Scenarios:#

  • Typo Fix: Push → build → deploy in 2 minutes
  • New Post: Add post → pipeline runs → live in minutes
  • Dependency Updates: Update Astro → pipeline tests it → safe deploy
  • Several Environments: Staging first, then production

When Should You Use GitLab CI/CD?#

Perfect For:#

  • Many Updates: You publish often

  • Several Contributors: A team writes the content

  • Quality Assurance: The build is checked before each deploy

  • Professional Workflow: Deployment that is good enough for production

  • Complex Builds: MDX, TypeScript, custom processing

  • Scheduled Deployments: Publishing at a set time

Not Needed For:#

  • Static Sites With Few Updates: Monthly updates are not worth the setup

  • One Developer Who Is Learning: Start with simple uploads first

  • No Build Step: Plain HTML/CSS with nothing to compile

How to Set Up GitLab CI/CD#

Prerequisites#

You need:

  • A self-hosted GitLab instance with your Astro blog repo
  • A GitLab Runner that is set up (shared, or for this project only)
  • A Cloudflare Pages project
  • A Cloudflare API token with Pages edit permissions
  • Basic YAML knowledge

Architecture Overview#

This is how one push moves through the pipeline:

  1. You write a post and run git push. The four pipeline stages are waiting.
  2. The push starts a pipeline. The install stage downloads the dependencies.
  3. build creates the site in dist/. test checks that the built files are there.
  4. On a feature branch, deploy_staging runs on its own. You get a preview URL.
  5. On main, deploy_production waits for your click. Then the site is live.
5 / 5

Step 1: Create GitLab CI/CD Configuration#

Create .gitlab-ci.yml in your repo root:

yaml
# .gitlab-ci.yml
# GitLab CI/CD pipeline for Astro blog deployment to Cloudflare Pages

# Define the Docker image to use for all jobs
# Using Node.js 20 as Astro requires Node 18+
image: node:20

# Define pipeline stages (run in order)
stages:
  - install # Install dependencies
  - build # Build the Astro site
  - test # Run tests
  - deploy # Deploy to Cloudflare Pages

# Cache node_modules between pipeline runs
# This speeds up subsequent builds
cache:
  key:
    files:
      - package-lock.json # Cache invalidates when package-lock.json changes
  paths:
    - node_modules/
    - .npm/

# Global variables available to all jobs
variables:
  npm_config_cache: '$CI_PROJECT_DIR/.npm'

# ==========================================
# STAGE 1: Install Dependencies
# ==========================================
install_dependencies:
  stage: install
  script:
    - echo "Installing dependencies..."
    - npm ci --prefer-offline --no-audit
  artifacts:
    expire_in: 1 hour
    paths:
      - node_modules/
  only:
    - branches # Run on all branches

# ==========================================
# STAGE 2: Build Astro Site
# ==========================================
build_site:
  stage: build
  dependencies:
    - install_dependencies
  script:
    - echo "Building Astro site..."
    - npm run build
    - echo "Build completed successfully!"
    - ls -lah dist/
  artifacts:
    expire_in: 1 week
    paths:
      - dist/ # Built site
      - package.json # Needed for deployment
  only:
    - branches

# ==========================================
# STAGE 3: Test (Optional but Recommended)
# ==========================================
test_build:
  stage: test
  dependencies:
    - build_site
  script:
    - echo "Running build verification tests..."
    # Check if dist directory exists and has content
    - test -d dist || (echo "dist directory not found!" && exit 1)
    - test -f dist/index.html || (echo "index.html not found!" && exit 1)
    # Check for required files
    - test -d dist/_astro || (echo "Assets directory missing!" && exit 1)
    - echo "Build verification passed!"
  only:
    - branches

# ==========================================
# STAGE 4: Deploy to Cloudflare Pages
# ==========================================

# Deploy to staging (feature branches)
deploy_staging:
  stage: deploy
  dependencies:
    - build_site
  before_script:
    - npm install -g wrangler
  script:
    - echo "Deploying to Cloudflare Pages (Staging)..."
    - |
      wrangler pages deploy dist \
        --project-name=blog-stack101 \
        --branch=$CI_COMMIT_REF_NAME \
        --commit-hash=$CI_COMMIT_SHORT_SHA \
        --commit-message="$CI_COMMIT_MESSAGE"
    - echo "Staging deployment complete!"
    - echo "Preview URL will be displayed above ⬆️"
  environment:
    name: staging/$CI_COMMIT_REF_NAME
    url: https://$CI_COMMIT_REF_SLUG.blog-stack101.pages.dev
  only:
    - branches
  except:
    - main # Don't deploy staging for main branch

# Deploy to production (main branch only)
deploy_production:
  stage: deploy
  dependencies:
    - build_site
  before_script:
    - npm install -g wrangler
  script:
    - echo "Deploying to Cloudflare Pages (Production)..."
    - |
      wrangler pages deploy dist \
        --project-name=blog-stack101 \
        --branch=main \
        --commit-hash=$CI_COMMIT_SHORT_SHA \
        --commit-message="$CI_COMMIT_MESSAGE"
    - echo "Production deployment complete!"
    - echo "Site is live at https://blog.stack101.dev 🚀"
  environment:
    name: production
    url: https://blog.stack101.dev
  only:
    - main # Only deploy to production from main branch
  when: manual # Require manual approval for production deployments

Step 2: Configure GitLab CI/CD Variables#

Store your credentials safely in GitLab.

  1. Go to your GitLab project
  2. Click Settings → CI/CD
  3. Open the Variables section
  4. Click Add Variable

Add Cloudflare Credentials:#

Variable Name Value Protected Masked Description
CLOUDFLARE_API_TOKEN Your API token ✅ Yes ✅ Yes Pages edit permissions token
CLOUDFLARE_ACCOUNT_ID Your account ID ✅ Yes ❌ No From Cloudflare dashboard URL

How to Get Cloudflare API Token:#

  1. Go to Cloudflare Dashboard
  2. Click My Profile → API Tokens
  3. Click Create Token
  4. Use template: Edit Cloudflare Workers
  5. Or create a custom token with:
    • Account - Cloudflare Pages: Edit
  6. Copy the token at once (it is shown only one time)
  7. Add it to GitLab CI/CD variables

Step 3: Configure GitLab Runner#

Option A: Use Shared Runners (Easier)#

If your instance has shared runners:

  1. Go to Settings → CI/CD → Runners
  2. Enable Shared runners
  3. Done

Option B: Set Up Project Runner (More Control)#

For a runner that only this project uses:

bash
# On your GitLab Runner server (can be same as GitLab host)

# Install GitLab Runner
curl -L "https://packages.gitlab.com/install/repositories/runner/gitlab-runner/script.deb.sh" | sudo bash
sudo apt-get install gitlab-runner

# Register the runner
sudo gitlab-runner register

# Follow the prompts:
# GitLab instance URL: https://your-gitlab.com
# Registration token: (from Settings → CI/CD → Runners)
# Description: blog-stack101-runner
# Tags: docker,astro,nodejs
# Executor: docker
# Default Docker image: node:20

Step 4: Create wrangler.toml Configuration#

Wrangler is Cloudflare’s command-line tool. Add its config file wrangler.toml to your project root:

toml
# wrangler.toml
# Cloudflare Pages configuration

name = "blog-stack101"
compatibility_date = "2024-12-06"

# Pages-specific configuration
pages_build_output_dir = "dist"

# Environment variables (non-sensitive)
[env.production]
NODE_VERSION = "20"

[env.preview]
NODE_VERSION = "20"

Step 5: Test Your Pipeline#

First Pipeline Run:#

  1. Commit and push:

    bash
    git add .gitlab-ci.yml wrangler.toml
    git commit -m "feat: add GitLab CI/CD pipeline for automated deployment"
    git push origin feature/ci-cd
  2. Watch the pipeline: Go to CI/CD → Pipelines, click the running pipeline, and follow each job live.

  3. Read the results:

    • ✅ Green = Success
    • ❌ Red = Failed (click for logs)
    • 🔵 Blue = Running
    • ⏸️ Gray = Manual action needed

Expected Pipeline Flow:#

  1. You push a feature branch. Four jobs wait in line.
  2. install_deps installs the packages. It takes about 30 seconds.
  3. build_site builds the site. It takes about 45 seconds.
  4. test_build checks the build. It takes about 10 seconds.
  5. deploy_staging takes about 20 seconds. Then you get a preview URL for this branch.
5 / 5

Step 6: Configure Pipeline Schedules (Optional)#

Rebuild your blog on a schedule. This helps with posts that have a future publish date. They need a rebuild to go live.

  1. Go to CI/CD → Schedules
  2. Click New schedule
  3. Fill in:
    • Description: Nightly rebuild for scheduled posts
    • Interval pattern: 0 2 * * * (2 AM daily)
    • Cron timezone: Your timezone
    • Target branch: main
    • Variables: (none needed)
  4. Click Save pipeline schedule

Common Cron Patterns:#

Pattern Description
0 2 * * * Daily at 2:00 AM
0 */6 * * * Every 6 hours
0 0 * * 0 Weekly on Sunday at midnight
0 9 * * 1-5 Weekdays at 9:00 AM

Step 7: Understanding Pipeline Artifacts#

What Are Artifacts?#

Artifacts are files that pipeline jobs create. GitLab keeps them for later use:

  • Build artifacts: The dist/ folder with your built site
  • Test reports: Automated test results
  • Logs: Build and deployment logs

Accessing Artifacts:#

  1. Go to CI/CD → Pipelines
  2. Click a successful pipeline
  3. Click Download next to the job
  4. Select artifacts to download

Artifact Benefits:#

  • Debugging: Look at failed builds on your own computer
  • Rollbacks: Deploy an older version again
  • Auditing: See what was deployed and when
  • Testing: Test a build on your computer before it goes to production

Advanced Configuration#

Parallel Jobs for Faster Builds#

Run tests at the same time:

yaml
# Run multiple test jobs simultaneously
test_links:
  stage: test
  script:
    - npm run test:links # Check for broken links

test_a11y:
  stage: test
  script:
    - npm run test:accessibility # Accessibility tests

test_performance:
  stage: test
  script:
    - npm run test:lighthouse # Lighthouse performance tests

Conditional Deployments#

Deploy only when files that matter change:

yaml
deploy_production:
  stage: deploy
  script:
    - wrangler pages deploy dist --project-name=blog-stack101
  only:
    refs:
      - main
    changes:
      - src/**/*
      - public/**/*
      - package.json
      - astro.config.mjs

Notification Integration#

Get a message when a pipeline fails:

yaml
# Add to .gitlab-ci.yml
notify_failure:
  stage: .post # Runs after all other stages
  script:
    - |
      curl -X POST https://api.telegram.org/bot$TELEGRAM_BOT_TOKEN/sendMessage \
        -d chat_id=$TELEGRAM_CHAT_ID \
        -d text="🚨 Pipeline failed for $CI_PROJECT_NAME"
  when: on_failure # Only run when pipeline fails
  only:
    - main

Troubleshooting Common Issues#

Issue 1: Pipeline Fails at Build Stage#

Error: npm ERR! missing script: build

Solution:

bash
# Verify package.json has build script
cat package.json | grep -A 5 "scripts"

# Should contain:
# "scripts": {
#   "build": "astro build"
# }

Issue 2: Cloudflare Deployment Fails#

Error: Error: Authentication error

Solution:

  • Check that CLOUDFLARE_API_TOKEN is set correctly
  • Check that the token has Pages edit permissions
  • Check that the token has not expired

Issue 3: Out of CI/CD Minutes#

Error: Quota exceeded for runner

Solution:

  • Check Settings → Usage Quotas
  • Improve the cache to make builds shorter
  • Use a self-hosted runner for unlimited minutes

Issue 4: Slow Builds#

Symptoms: Builds taking >5 minutes

Solutions:

yaml
# Add cache for faster installs
cache:
  key: ${CI_COMMIT_REF_SLUG}
  paths:
    - node_modules/
    - .npm/

# Use npm ci instead of npm install
script:
  - npm ci --prefer-offline --no-audit

Best Practices#

1. Use Branch Protection#

Require CI to pass before a merge:

  1. Go to Settings → Repository → Branch protection
  2. Add rule for main branch:
    • ✅ Require approval from code owners
    • ✅ Require pipelines to succeed
    • ✅ Prevent force push

2. Tag Production Releases#

Tag each production deploy:

bash
# After successful deployment
git tag -a v1.0.0 -m "Release v1.0.0 - Added CI/CD pipeline"
git push origin v1.0.0

3. Monitor Pipeline Performance#

Check Analytics → CI/CD Analytics for:

  • Pipeline success rate
  • Average duration
  • Jobs that fail most often

4. Use Pipeline Templates#

Move job definitions that you reuse into a template:

yaml
# .gitlab/ci/templates/deploy.yml
.deploy_template:
  before_script:
    - npm install -g wrangler
  script:
    - wrangler pages deploy dist --project-name=$PROJECT_NAME

# Use in main .gitlab-ci.yml
include:
  - local: '.gitlab/ci/templates/deploy.yml'

deploy_prod:
  extends: .deploy_template
  variables:
    PROJECT_NAME: blog-stack101

Pipeline Workflow Example#

Feature Development Workflow:#

bash
# 1. Create feature branch
git checkout -b feature/new-blog-post

# 2. Write your blog post
# Edit src/content/blog/my-new-post.mdx

# 3. Commit and push
git add .
git commit -m "feat: add new blog post about GitLab CI/CD"
git push origin feature/new-blog-post

# 4. Pipeline automatically:
#    ✅ Installs dependencies
#    ✅ Builds site
#    ✅ Runs tests
#    ✅ Deploys to staging preview
#    📧 Sends you preview URL

# 5. Review preview:
# https://feature-new-blog-post.blog-stack101.pages.dev

# 6. Create merge request
# GitLab → Merge Requests → New merge request

# 7. After approval and merge to main:
#    ✅ Pipeline runs again on main branch
#    ⏸️ Waits for manual approval
#    ✅ Click "Deploy to Production"
#    🚀 Live at https://blog.stack101.dev

Monitoring and Maintenance#

Weekly:#

  • Fix failed pipelines
  • Check CI/CD usage quota
  • Fix dependency security alerts
  • Clean up old artifacts

Monthly:#

  • Update GitLab Runner
  • Improve the cache config
  • Check when the Cloudflare API token expires
  • Update the Node.js version if needed

Cost Considerations#

GitLab CI/CD Free Tier:#

  • 400 minutes/month CI/CD minutes
  • 10 GB artifact storage
  • 5 concurrent jobs

Your Blog’s Usage:#

A typical pipeline takes ~2 minutes.

  • 10 posts/month: ~20 min (5% of quota)
  • 50 posts/month: ~100 min (25% of quota)
  • Daily rebuilds: ~60 min (15% of quota)

This is ~40% of the free quota, so it costs $0/month.

If You Exceed Free Tier:#

Option 1: Self-hosted runner (unlimited, free) Option 2: GitLab Premium ($29/user/month, 10,000 min) Option 3: Improve the pipeline so it uses fewer minutes

Conclusion#

Your pipeline now:

  • ✅ Builds on every commit
  • ✅ Tests the build to find errors early
  • ✅ Deploys previews for feature branches
  • ✅ Needs a manual approval for production
  • ✅ Stores artifacts for debugging and rollbacks
  • ✅ Keeps a full deployment history

Every deploy is tested and checked automatically.

Next Steps#

Improve your pipeline with:

  1. Automated Testing: Link checking, accessibility, performance
  2. SEO Validation: Check the meta tags and the sitemap
  3. Image Optimization: Automatic compression during build
  4. Content Validation: Spelling, grammar, broken link checks
  5. Analytics Integration: Track how many deployments succeed

Resources#