Skip to content

Simplifying domain handling in Cloudflare Pages for Astro builds

Posted on:April 26, 2023 at 03:33 AM

When using Astro, you can access the website’s absolute path with the import.meta.env.SITE variable, defined in astro.config.mjs.

However, when deploying a static site with Cloudflare Pages, a new subdomain is generated for each deployment. To make Astro adapt automatically, you must obtain the domain name during the build phase and configure it in Astro.

Try the following code for a similar setup:

import { defineConfig } from "astro/config";

import { loadEnv } from "vite";
const { CF_PAGES_URL, CF_PAGES, CF_PAGES_BRANCH, CUSTOM_DOMAIN } = loadEnv(
  import.meta.env.MODE,
  process.cwd(),
  ""
);

const getSite = () => {
  if (CUSTOM_DOMAIN) {
    return CUSTOM_DOMAIN;
  } else if (CF_PAGES && !["master", "main"].includes(CF_PAGES_BRANCH)) {
    return CF_PAGES_URL;
  } else {
    return "http://localhost:3000";
  }
};

// https://astro.build/config
export default defineConfig({
  site: getSite(),
});

By adding this code, you can implement the following strategy:

Reference