server.allowedHosts (and vite.preview.allowedHosts) are ignored when using astro preview with the @astrojs/cloudflare adapter. Requests with non-localhost Host headers are blocked with a 403.
This was fixed for the static preview server in withastro/astro#16104, but the @astrojs/cloudflare adapter has its own preview entrypoint that is not covered by that fix.
npm install
npm run build
npm run preview
# In another terminal:
curl -H "Host: foo.example.com" http://localhost:4010/200 response (.example.com is in server.allowedHosts).
< HTTP/1.1 403 Forbidden
Blocked request. This host ("foo.example.com") is not allowed.
To allow this host, add "foo.example.com" to `preview.allowedHosts` in vite.config.js.
Two issues:
-
astrocore does not passserver.allowedHoststo adapter preview entrypoints. Inpackages/astro/src/core/preview/index.ts, the call topreviewModule.default()includeshost,port,headers, etc. but omitsallowedHosts. -
@astrojs/cloudflarepreview entrypoint hardcodesallowedHosts: []. Inpackages/cloudflare/src/entrypoints/preview.ts, the Vite preview config setsallowedHosts: [], ignoring any user configuration.
Patch the adapter's preview entrypoint via a postinstall script in package.json:
"postinstall": "node -e \"let f=require('node:fs'),p='node_modules/@astrojs/cloudflare/dist/entrypoints/preview.js';f.existsSync(p)&&f.writeFileSync(p,f.readFileSync(p,'utf8').replace('allowedHosts: []','allowedHosts: true'))\""