#Can I use env schema with Cloudflare vars?
4 messages · Page 1 of 1 (latest)
Hi @placid summit. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
Yes, you can use the Astro env schema with Cloudflare variables defined in wrangler.toml. The Cloudflare adapter for Astro provides support for accessing environment variables and Cloudflare bindings through the Cloudflare runtime.
Here's how you can set this up:
- Define your variables in
wrangler.toml:
[vars]
MY_VARIABLE = "test"
- Set up your env schema in
astro.config.mjs:
import { defineConfig, envField } from "astro/config";
import cloudflare from '@astrojs/cloudflare';
export default defineConfig({
adapter: cloudflare(),
output: 'server',
env: {
schema: {
MY_VARIABLE: envField.string({ context: "server", access: "public" }),
}
}
});
- Access the variables in your Astro components or API routes:
---
const { env } = Astro.locals.runtime;
const myVariable = env.MY_VARIABLE;
---
The Cloudflare adapter uses bindings found in the wrangler and .dev.vars configuration files as mentioned in the Astro documentation (https://docs.astro.build/en/guides/integrations-guide/cloudflare/#cloudflare-runtime).
It's important to note that when using the Cloudflare adapter, environment variables are scoped to the request, unlike in Node.js where they're global. This means you always need to use secrets inside the request scope as explained in the Astro documentation (https://docs.astro.build/en/guides/environment-variables/#limitations).
Remember to enable the Cloudflare runtime in your Astro config if you want to use these variables during development:
export default defineConfig({
adapter: cloudflare({
platformProxy: {
enabled: true,
},
}),
});