Learn Astro · 15/15

Going Live: Deployment & CI/CD

7 min read

Going Live: Deployment & CI/CD 🚀

Welcome to the grand finale of the initial development lifecycle!

Right now, your Astro site lives on localhost:4321. This is the digital equivalent of singing in the shower. You sound amazing, the acoustics are perfect, but nobody else can hear you.

It is time to move the concert to a stadium. It is time to deploy.

In this guide, we will transform your raw code into a production-ready asset, push it to the cloud, and set up an army of robots (CI/CD) to update it automatically whenever you save a file.


1. Building for Production: The astro build Command 🏗️

Before we move files to a server, we must prepare them.

Definition

Building is the process of converting your framework-specific code (Astro components, TypeScript, SASS) into standard static assets (HTML, CSS, and optimized JavaScript) that any browser can understand.

The Problem

You cannot upload your .astro files directly to the internet.

  1. Browsers do not know how to render an .astro file.
  2. Your development server (Vite) is designed for "hot reloading" (fast updates while coding), not for performance efficiency. It is heavy and slow for a real user.

The Solution: npm run build

When you run the build command, Astro reads your source code and compiles it ahead of time (AOT). It removes unused CSS, minifies JavaScript (makes it smaller/unreadable to humans but faster for robots), and generates physical .html files for every route.

Hands-on Practice

Open your terminal and run:

bash
npm run build

What just happened?
If you look at your project folder, you will see a new directory called dist/ (short for distribution).

  • src/: This is for you (human-readable code).
  • dist/: This is for the browser (machine-optimized code).

Under the Hood:
Astro uses Vite to bundle your assets. It fingerprints filenames (e.g., index.a8b2c.css) so that when you update your site, visitors don't get stuck with old cached versions.

Fun Fact: The dist folder is ephemeral. You should never manually edit files inside dist/ because the next time you run build, your changes will be overwritten. It's like building a sandcastle; the tide (the build command) will wash it away and rebuild it new.


2. Deploying a Static Site (GitHub Pages / Netlify) 🌐

If your site is Static (default in Astro), you have the easiest deployment path. You don't need a server running 24/7; you just need a place to store files.

The Problem

You have a dist folder on your laptop. You need those files to be accessible via a URL like mysite.com.

Option A: GitHub Pages (The Developer Standard)

GitHub Pages is free and integrates directly with your code repository.

Step 1: Configure Astro
To host on GitHub Pages, Astro needs to know your repository name to generate the correct links for CSS and Images.

Open astro.config.mjs:

javascript
import { defineConfig } from 'astro/config';

export default defineConfig({
  // Your public domain, e.g.: https://my-name.github.io
  site: 'https://username.github.io',
  // Your repository name (if not a custom domain)
  base: '/my-repo-name',
});

Step 2: Push the build
Traditionally, you would install a package called gh-pages to push your dist folder to a specific branch. However, the modern standard is using GitHub Actions (we will cover this in section 4).

Option B: Netlify (The "It Just Works" Method)

Netlify is a favorite because it offers drag-and-drop simplicity and powerful global CDNs.

The Manual Way (Good for testing):

  1. Run npm run build.
  2. Log in to Netlify.
  3. Drag your dist folder onto the browser window.
  4. You are live. Seriously, that's it.

The Industry Way (Git Connect):

  1. Push your code to GitHub/GitLab.
  2. Log in to Netlify -> "Add new site" -> "Import an existing project".
  3. Select your repo.
  4. Netlify detects Astro automatically.
    • Build Command: astro build
    • Publish Directory: dist
  5. Click "Deploy".

Funny Imagination: Imagine if moving houses was like Netlify. You just drag your house onto a map, and poof, it's there, plumbing and electricity connected instantly.


3. Deploying an SSR Application (Vercel / Cloudflare) ⚡

Definition

SSR (Server-Side Rendering) means the HTML is generated on the server at the moment the user requests it, rather than months ago when you ran the build command.

The Problem

If you used output: 'server' or 'hybrid' in your Astro config (perhaps for a login system, a dynamic dashboard, or checking live inventory), a static host like GitHub Pages will not work. GitHub Pages cannot execute code; it only serves files.

The Solution: Adapters

Astro uses Adapters to translate your code into the specific language of your hosting provider (Vercel, Cloudflare, Node, etc.).

Option A: Vercel

Vercel is the creators of Next.js but they love Astro. It offers "Serverless functions".

1. Install the Adapter:
Astro has a CLI wizard to handle this.

bash
npx astro add vercel

This command automatically:

  1. Installs @astrojs/vercel.
  2. Updates astro.config.mjs to import the adapter.
  3. Sets output: 'server' (if you verify the prompt).

2. Deploy:
Install the Vercel CLI or connect via the Vercel Dashboard (similar to Netlify). Vercel will now treat your dynamic routes as Serverless Functions.

Option B: Cloudflare Pages

Cloudflare runs your code on the "Edge"—servers physically located very close to the user.

1. Install the Adapter:

bash
npx astro add cloudflare

2. Configuration:
Your astro.config.mjs will look like this:

javascript
import { defineConfig } from 'astro/config';
import cloudflare from '@astrojs/cloudflare';

export default defineConfig({
  output: 'server',
  adapter: cloudflare()
});

Industry Note: Cloudflare Workers/Pages are extremely fast but have a strict runtime environment (not a full Node.js environment). Some heavy Node libraries might not work there. It's like driving a Formula 1 car—insanely fast, but you can't attach a trailer to it.


4. Setting up Continuous Integration (GitHub Actions) 🤖

Definition

CI/CD (Continuous Integration / Continuous Deployment) is the practice of automating the build and deploy process.

The Problem

Manually running npm run build and dragging folders or running CLI commands every time you fix a typo is:

  1. Boring.
  2. Prone to error (what if you forget to build?).
  3. Slow.

The Solution: GitHub Actions

We write a recipe (a .yml file) that tells GitHub: "Every time I push code to the main branch, wake up a robot, have it install dependencies, build the site, and upload it."

Hands-on: Deploying to GitHub Pages

Create a file in your project at this exact path: .github/workflows/deploy.yml.

Paste this industry-standard workflow for Astro:

yaml
name: Deploy to GitHub Pages

on:
  # Trigger the workflow every time you push to the `main` branch
  push:
    branches: [ main ]
  # Allows you to run this workflow manually from the Actions tab on GitHub
  workflow_dispatch:

# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages
permissions:
  contents: read
  pages: write
  id-token: write

# Allow one concurrent deployment
concurrency:
  group: "pages"
  cancel-in-progress: true

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout your repository using git
        uses: actions/checkout@v4

      - name: Install, build, and upload your site
        uses: withastro/action@v2
        # withastro/action is a magic wrapper that detects package manager (npm/pnpm/yarn)
        # and runs the build command automatically.

  deploy:
    needs: build
    runs-on: ubuntu-latest
    environment:
      name: github-pages
      url: ${{ steps.deployment.outputs.page_url }}
    steps:
      - name: Deploy to GitHub Pages
        id: deployment
        uses: actions/deploy-pages@v4

What to do next?

  1. Commit this file and push it to GitHub.
  2. Go to your Repository Settings on GitHub -> Pages.
  3. Under "Build and deployment", change the Source to GitHub Actions.

Now, whenever you push code, you can watch the "Actions" tab in your repo. You'll see green checks appear as the robots do your bidding.

Analogy: Without CI/CD, you are a chef who cooks the food and also runs it to the table. With CI/CD, you cook the food (code), ring a bell (git push), and a waiter (GitHub Actions) instantly delivers it to the customer.


Summary

  1. astro build: Turns your code into a website.
  2. Static: Use Netlify or GitHub Pages for blogs/portfolios.
  3. SSR: Use Vercel or Cloudflare Adapters for apps with logins/databases.
  4. CI/CD: Automate everything so you can focus on coding, not copying files.

You are now live. The world can see your creation. Don't forget to update your LinkedIn. 😉


📚 References & Further Reading

Challenge

Write a JavaScript function named processUserData that takes a single argument: a JSON string representing a list of users.

Your function must perform the following operations in order:

  1. Parse the input JSON string into a JavaScript array of objects.
  2. Filter the array to include only users who are isActive.
  3. For each of the active users, transform their data into a new object with the following structure:
    • fullName: A string combining the user's firstName and lastName, separated by a space.
    • companyEmail: A string created by taking the user's email and replacing the domain @example.com with @techcorp.io.
  4. After transforming all active users, sort the resulting array alphabetically by the fullName property.
  5. Finally, convert the sorted array of transformed objects back into a JSON string. This string should be 'prettified', using an indentation of 4 spaces.
  6. The function must return this final, prettified JSON string.

Expected result

The function must return a single JSON string. This string should represent an array containing two objects (for the active users Anna and Zoe), sorted alphabetically by their full names.

The JSON string must be formatted with an indentation of 4 spaces.

The structure of each object inside the final array should be:

json
{
    "fullName": "...",
    "companyEmail": "..."
}

Specifically, the returned string should look exactly like this:

json
[
    {
        "fullName": "Anna Smith",
        "companyEmail": "[email protected]"
    },
    {
        "fullName": "Zoe Washington",
        "companyEmail": "[email protected]"
    }
]
javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.