you want a custom subdomain for your cloudflare pages preview deployment? read on.
this is just a quick n dirty project, let's aim to explain things a bit better and make deployment easier.
you'll create a Worker which calls the Cloudflare API from time to time (defined in the cron pattern) to retrieve the current domain of your latest preview build in Cloudflare Pages. This URL is stored in Cloudflare KV. The Worker will fetch the Cloudflare Pages site then when you hit the configured route.
- get your global api key (unfortunately scoped api tokens are not available for pages yet)
- create a new cloudflare worker
- go to worker settings and add the following environment variables
environment name | value | encrypt it? |
---|---|---|
accountId | your couldflare account id | yes |
apiKey | cloudflare api key | yes |
cloudflare email address | yes | |
projectName | cloudflare pages project NAME | no |
- create a Cloudflare KV namespace (you can do this in the Workers Dashboard)
- add one key to the namespace already. use
route
for the key name and the route you want to use for this worker in thevalue
field, something like that:
key | value |
---|---|
route | https://subdomain.example.com |
- add the Namespace to your Worker (open the Worker > Settings > Variables > KV Namespace Bindings)
- create a cron trigger to execute every hour
- open the cloudflare worker editor and paste the contents of the
index.js
file in this repo in there. - assign a route in the Cloudflare Dashboard to match your Worker, like so:
subdomain.example.com/* => your-worker