#Can I use env schema with Cloudflare vars?

4 messages · Page 1 of 1 (latest)

placid summit
#

Hello,

Can I use env schema with Cloudflare vars defined in wrangler.toml?

tidal cairnBOT
#

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:

  1. Define your variables in wrangler.toml:
[vars]
MY_VARIABLE = "test"
  1. 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" }),
    }
  }
});
  1. 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,
    },
  }),
});
#

This setup allows you to use the type-safe env schema with your Cloudflare variables, providing better type checking and validation for your environment variables.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: