Skip to content

adamchal/astro-cloudflare-preview-allowedhosts

Repository files navigation

server.allowedHosts ignored by @astrojs/cloudflare preview

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.

Reproduce

npm install
npm run build
npm run preview
# In another terminal:
curl -H "Host: foo.example.com" http://localhost:4010/

Expected

200 response (.example.com is in server.allowedHosts).

Actual

< 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.

Root cause

Two issues:

  1. astro core does not pass server.allowedHosts to adapter preview entrypoints. In packages/astro/src/core/preview/index.ts, the call to previewModule.default() includes host, port, headers, etc. but omits allowedHosts.

  2. @astrojs/cloudflare preview entrypoint hardcodes allowedHosts: []. In packages/cloudflare/src/entrypoints/preview.ts, the Vite preview config sets allowedHosts: [], ignoring any user configuration.

Workaround

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'))\""

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages