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:
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 theCUSTOM_DOMAIN
variable if it exists. - In all other cases, default to
http://localhost:3000
.