Pages Build Configuration & Environment Variables
In this tutorial, you'll learn about Pages Build Configuration & Environment Variables. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
This tutorial explains how to configure build settings and environment variables in Cloudflare Pages, including framework presets, custom build commands, and secret management. Proper build configuration ensures your site compiles correctly and your sensitive data stays protected. The DodaZIP documentation site uses environment variables to switch between staging and production API endpoints during the build Process.
Build Configuration Overview
Cloudflare Pages detects popular frameworks automatically and sets the correct build command and output directory. You can override these settings in the Pages dashboard or through wrangler.toml.
flowchart LR A[Git Push] --> B[Detect framework] B --> C[Install dependencies] C --> D[Run build command] D --> E[Copy output directory] E --> F[Deploy to edge] style D fill:#f90,color:#fff style F fill:#f90,color:#fff
Framework Presets
Cloudflare Pages includes built-in presets for frameworks like Next.js, Hugo, Jekyll, and React. When a preset is detected, Pages sets the build command and publish directory automatically.
// Detect which framework preset Cloudflare uses
async function detectFrameworkPreset() {
const configs = {
'next.config.js': { command: 'npm run build', output: 'out' },
'hugo.toml': { command: 'hugo --gc --minify', output: 'public' },
'_config.yml': { command: 'jekyll build', output: '_site' },
'astro.config.mjs': { command: 'npm run build', output: 'dist' }
};
const fs = await import('fs');
for (const [file, config] of Object.entries(configs)) {
if (fs.existsSync(file)) {
console.log('Detected preset for:', file);
console.log('Build command:', config.command);
console.log('Output directory:', config.output);
return config;
}
}
console.log('No preset detected. Using default.');
return { command: 'npm run build', output: 'dist' };
}
detectFrameworkPreset();
// Expected output:
// Detected preset for: hugo.toml
// Build command: hugo --gc --minify
// Output directory: public
Setting Environment Variables
You configure environment variables in the Cloudflare Pages dashboard under the Environment Variables section. Production and preview environments can have different variable values.
// functions/api/env-check.js
export async function onRequest(context) {
const environment = context.env.CF_PAGES_BRANCH || 'local';
const apiUrl = context.env.API_URL || 'https://default-api.example.com';
const debug = context.env.DEBUG === 'true';
const envInfo = {
branch: environment,
apiUrl: apiUrl,
debug: debug,
preview: context.env.CF_PAGES_URL || null
};
return new Response(JSON.stringify(envInfo, null, 2), {
headers: { 'Content-Type': 'application/json' }
});
}
// Visiting /api/env-check
// Expected output:
// {
// "branch": "main",
// "apiUrl": "https://api.prod.example.com",
// "debug": false,
// "preview": null
// }
Secret Environment Variables
Mark sensitive variables as secrets in the dashboard. Secrets are encrypted and not visible in the dashboard after creation. They are available in your build and function runtime.
# Example environment variables for a Pages project
# Non-secret (visible in dashboard)
NODE_VERSION=18
PUBLIC_SITE_URL=https://example.com
# Secret (encrypted, not visible after save)
DATABASE_URL=postgresql://user:pass@db.example.com/mydb
API_SECRET_KEY=sk_live_abc123
// Verify secrets are loaded without exposing values
async function validateSecrets() {
const required = ['DATABASE_URL', 'API_SECRET_KEY'];
const loaded = process.env;
for (const key of required) {
if (loaded[key]) {
console.log(key + ': configured (' + loaded[key].length + ' chars)');
} else {
console.error(key + ': MISSING');
}
}
}
validateSecrets();
// Expected output:
// DATABASE_URL: configured (42 chars)
// API_SECRET_KEY: configured (15 chars)
Custom Build Commands
Override the default build command for projects with custom build steps or Monorepo setups.
// Build script for a monorepo Pages project
const { execSync } = require('child_process');
function runBuild() {
const commands = [
'npm ci',
'npm run build:shared',
'npm run build:app',
'cp -r apps/docs/dist ./publish'
];
for (const cmd of commands) {
console.log('Running:', cmd);
execSync(cmd, { stdio: 'inherit' });
}
console.log('Build complete');
}
runBuild();
// Expected output:
// Running: npm ci
// Running: npm run build:shared
// Running: npm run build:app
// Running: cp -r apps/docs/dist ./publish
// Build complete
FAQ
{{< faq "How do I specify a Node.js version for my build?">}} Set the NODE_VERSION environment variable to your desired version, such as 18 or 20. Cloudflare Pages uses the specified version for both the build step and function runtime environment.{{< /faq >}}
Practice Questions
- How does Cloudflare Pages detect which framework your project uses?
- What is the difference between a regular environment variable and a secret?
- Which environment variable contains the branch name during a Pages build?
Summary
Cloudflare Pages build configuration includes automatic framework detection, custom build commands, and environment variable management. Secrets are encrypted and not visible after creation. Use different variable values for production and preview environments to maintain separate configurations.
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro — security-first tools for the modern web.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro