We use cookies to ensure you get the best experience on our website. Read our privacy policy

Skip to main content
Environment Variables with Cloudflare illustration showing code editor with type hints
Home Blog Astrojs

Environment Variables with AstroJS and Cloudflare

Learn how to use environment variables with AstroJS and Cloudflare. This guide shows you how to properly configure your Cloudflare Pages deployment for optimal security and developer experience.

Published on:
Clock Time to complete: 20 minutes

With Astro 5 environment variables got a huge upgrade in developer experience and safety. Until recently, AstroJS developers using Cloudflare had to use the legacy environment variable handling system. The good news is that Astro’s new environment variable configuration system now works seamlessly with the Cloudflare adapter!

You can always check out the AstroJS docs for the latest information, but this guide focuses specifically on the Cloudflare integration details you need to know.

Let’s quickly review the previous method of handling environment variables with Cloudflare. This context will help you understand why the new approach is such a significant improvement.

With the legacy approach, you had to manually define your environment variables and inject them into the build process:

astro.config.ts
import { defineConfig } from 'astro/config';
import cloudflare from '@astrojs/cloudflare';
const envVars = ['PUBLIC_VARIABLE_1', 'PUBLIC_VARIABLE_2', 'PRIVATE_VARIABLE_3'] as const;
export default defineConfig({
site: 'https://example.com',
output: 'static',
trailingSlash: 'ignore',
integrations: [],
adapter: cloudflare(),
vite: {
ssr: {
target: 'webworker',
},
define: envVars.reduce((acc, key) => {
acc[`process.env.${key}`] = JSON.stringify(process.env[key]);
return acc;
}, {}),
},
});

You also needed to manually define the types for your environment variables:

src/env.d.ts
type Variables = 'PUBLIC_VARIABLE_1' | 'PUBLIC_VARIABLE_2' | 'PRIVATE_VARIABLE_3';
interface ImportMetaEnv extends Record<Variables, string> {}
interface ImportMeta {
readonly env: ImportMetaEnv;
}

Then you could access your variables like this:

import.meta.env.PUBLIC_VARIABLE_1;

This approach had several significant drawbacks:

  1. No security boundary: Private variables could accidentally be exposed to the client
  2. No validation: Missing environment variables wouldn’t cause errors until runtime
  3. Limited type safety: TypeScript couldn’t verify the correct usage of variables
  4. No default values: You couldn’t specify fallbacks for optional variables
  5. Manual maintenance: You had to update multiple files when adding new variables

Limited Time Launch Sale

Skip the configuration headaches! Our AstroJS starter template will save you hours of setup time and potential security issues.

GET 60% OFF!

Astro’s new environment variable system addresses all these limitations with an elegant, type-safe solution that now works perfectly with Cloudflare. Let’s explore the benefits and implementation details.

  • Check Circle

    Runtime validation: Errors if required variables are missing

  • Check Circle

    Enhanced type safety: Full TypeScript integration with proper types

  • Check Circle

    Intelligent IntelliSense: Autocomplete in your IDE for available variables

  • Check Circle

    Security boundaries: Private variables cannot be exposed to the client

  • Check Circle

    Default values: Specify fallbacks for optional variables

  • Check Circle

    Centralized configuration: Define everything in one place

astro.config.ts
import { defineConfig, envField } from 'astro/config';
import cloudflare from '@astrojs/cloudflare';
// https://astro.build/config
export default defineConfig({
site: 'https://example.com',
output: 'static',
trailingSlash: 'ignore',
integrations: [],
adapter: cloudflare(),
env: {
schema: {
// Public variable accessible anywhere
PUBLIC_VARIABLE_1: envField.string({
context: 'client',
access: 'public',
default: 'default value',
}),
// Public variable accessible on the server
PUBLIC_VARIABLE_2: envField.boolean({
context: 'server',
access: 'public',
default: false,
}),
// Private variable accessible on the server
PRIVATE_VARIABLE_3: envField.number({
context: 'server',
access: 'secret',
}),
},
},
vite: {
ssr: {
target: 'webworker',
},
},
});

Notice how each variable is defined with:

  1. Type information (string, boolean, number)
  2. Context (client or server)
  3. Access level (public or secret)
  4. Optional default values

This configuration automatically generates the appropriate TypeScript types and enforces security boundaries between client and server code.

// Server-side code
import { PUBLIC_VARIABLE_2, PRIVATE_VARIABLE_3 } from 'astro:env/server';
// Client-side code
import { PUBLIC_VARIABLE_1 } from 'astro:env/client';

This import pattern creates a clear separation between client and server variables, preventing accidental exposure of sensitive information. The TypeScript compiler will even throw errors if you try to import server variables in client code!

For the new environment variable system to work correctly with Cloudflare, you need to update your Cloudflare Pages settings. You have two options:

  1. Set the compatibility date to April 1, 2025, or later
  2. Enable the compatibility flag specifically for this feature

Here’s how to access these settings in your Cloudflare dashboard:

Cloudflare runtime settings

If you’re starting a new project or can safely update your compatibility date:

Cloudflare runtime settings compatibility date

If you need to maintain an earlier compatibility date for other features:

Cloudflare runtime settings compatibility flag
  • Check Circle

    Use descriptive variable names that indicate their purpose

  • Check Circle

    Set appropriate access levels (public vs. secret) for each variable

  • Check Circle

    Provide default values for non-critical configuration

  • Check Circle

    Group related variables together in your schema

  • Check Circle

    Document expected formats in comments for team members

By following these practices, you’ll create a more maintainable, secure, and developer-friendly configuration for your AstroJS projects on Cloudflare Pages.

The new environment variable system represents a significant improvement in how we manage configuration in AstroJS projects. With proper Cloudflare integration, you can now enjoy all these benefits while deploying to one of the fastest and most reliable edge networks available.

Related Articles

Read more AstroJS articles
North Star Themes Logo

Subscribe to our newsletter

Get the latest AstroJS tips and tricks right to your inbox

Email: [email protected]

© 2025 North Star Themes

Web Kit Provided By North Star Themes