Skip to content

Domain handling in Cloudflare Pages for Astro builds

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:

  • In Cloudflare Pages Settings, add the CUSTOM_DOMAIN variable to the Production environment to use the custom domain directly.
  • For other branch builds, use the unique domain name provided by Cloudflare Pages.
  • In local development, load the .env file and use the CUSTOM_DOMAIN variable if it exists.
  • In all other cases, default to http://localhost:3000.

Reference