Environment Variables & Secrets
Manage database credentials, API tokens, DINOU_PUBLIC_* client constants, and Edge resource bindings securely across Node.js, Bun, Deno, Cloudflare Workers, and Netlify.
Environment Variables in Dinou
Dinou isolates all environment variables to the server by default across Esbuild, Rollup, and Webpack. Private secrets (such as database passwords or payment API keys) are never bundled into browser JavaScript or leaked during Client Component SSR/SSG, while variables explicitly prefixed with DINOU_PUBLIC_ are safely inlined for client use.
DINOU_PUBLIC_* across Esbuild, Rollup, Webpack, and export-static.dinou dev and production.Server Isolation & DINOU_PUBLIC_*
Dinou enforces a strict compile-time and SSR boundary between private server credentials and public browser configuration:
- Unprefixed variables (e.g.
DATABASE_URL,STRIPE_SECRET_KEY): Accessible exclusively on the server. Inside"use client"components, unprefixedprocess.env.*accesses safely evaluate toundefinedduring both SSR/SSG and browser execution—never leaking secrets into HTML or throwingReferenceError: process is not defined. - Prefixed variables (
DINOU_PUBLIC_*): Embedded at build time into Client Components and SSR across all 3 bundlers.
Private Server Secrets
Read private environment variables freely in any server-only execution context:
Query databases or private CMS APIs directly inside page.tsx and layout.tsx.
Use private payment SDKs, signing keys, and database pools in RPC mutations.
Access backend credentials in getProps, getStaticPaths, and validateParams.
Read service tokens in dinou.config.ts, setupFiles, and plugin.onRequest.
// src/server-functions/checkout.ts
"use server";
import Stripe from "stripe";
// Private secret stays 100% on the server
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
export async function createCheckoutSession(amount: number) {
const session = await stripe.checkout.sessions.create({
payment_method_types: ["card"],
line_items: [{ price_data: { currency: "usd", unit_amount: amount }, quantity: 1 }],
mode: "payment",
success_url: `${process.env.APP_URL}/success`,
cancel_url: `${process.env.APP_URL}/cancel`,
});
return session.url;
}Public Client Variables (DINOU_PUBLIC_*)
To expose a non-sensitive value (such as an analytics ID, Sentry DSN, Supabase project URL, or Stripe publishable key) directly to "use client" modules without prop-drilling, prefix its name with DINOU_PUBLIC_:
// src/components/analytics-banner.tsx
"use client";
export default function AnalyticsBanner() {
// Inlined at build time across Esbuild, Rollup, and Webpack (both direct & destructured)
const siteId = process.env.DINOU_PUBLIC_ANALYTICS_ID;
const { DINOU_PUBLIC_ENABLE_BETA } = process.env;
if (DINOU_PUBLIC_ENABLE_BETA !== "true") {
return null; // Dead-code eliminated in production builds
}
return <p className="text-xs">Tracking ID: {siteId}</p>;
}Build-Time Prefix vs. Runtime Props
Dinou supports both ways of delivering public configuration to Client Components—choose the one that matches your deployment workflow:
- Use
DINOU_PUBLIC_*for values known at build time, SDK singletons initialized outside React trees, or standalone static exports (dinou export-static). - Pass props from a dynamic Server Component when deploying a single pre-built Docker container image across multiple environments (e.g. staging and production) where values are injected at container startup (
dinou start) rather thandinou build:
// src/checkout/page.tsx (Dynamic Server Component)
import PaymentWidget from "./payment-widget"; // "use client"
export default function CheckoutPage() {
// Evaluated live on the server at request time (great for Docker runtime config)
const publishableKey = process.env.STRIPE_PUBLISHABLE_KEY ?? "";
return (
<main className="container max-w-xl mx-auto py-8">
<h1>Complete Your Order</h1>
<PaymentWidget publishableKey={publishableKey} />
</main>
);
}Defining .env Files
Dinou automatically loads .env files from your project root across all bundlers (esbuild, rollup, webpack) and commands (dinou dev, dinou build, dinou start, dinou export-static, and dinou typegen). For most projects, a single .env file is all you need:
# .env
PORT=3000
# Private server-only secrets (NEVER sent to the browser)
DATABASE_URL="postgresql://postgres:password@localhost:5432/my_app_dev"
STRIPE_SECRET_KEY="sk_test_..."
# Public browser-safe variables (inlined into client & SSR bundles)
DINOU_PUBLIC_STRIPE_KEY="pk_test_..."
DINOU_PUBLIC_APP_URL="http://localhost:3000".env* Precedence Hierarchy & Live Hot-Reload
When separating team defaults from personal machine secrets or testing local development vs. production builds, Dinou resolves variables from highest priority to lowest priority:
- OS / Shell / Hosting Environment (e.g.
PORT=4000 npx dinou dev, Docker, Railway, Fly.io, Netlify) — always wins; never overwritten by.env*files. .env.development.local(indinou dev) or.env.production.local(indinou build/dinou start)..env.local— local machine overrides (skipped whenNODE_ENV=testfor deterministic tests)..env.developmentor.env.production— mode-specific defaults..env— base project defaults.
While dinou dev is running, editing any root .env* file automatically reloads server variables in-place, updates TypeScript declarations in .dinou/types/routes.d.ts, and rebuilds client/SSR definitions whenever a DINOU_PUBLIC_* variable changes—no manual server restart required.
Built-In Framework Variables
Dinou recognizes the following optional runtime and CLI environment variables out of the box:
PORT— HTTP server port fordinou devanddinou start*(default:3000).HOST— Network interface hostname to bind in production Node, Bun, and Deno servers.HMR_PORT— Custom WebSocket HMR port indinou dev(default:PORT + 1).IDLE_TIMEOUT— Keep-alive idle timeout in seconds for the Bun server adapter (default:120).DENO_KV_URL/DENO_KV_PATH— Remote Deno Deploy KV endpoint or custom SQLite file path for Deno ISR cache storage.DINOU_WRITE_TO_DISK— Set to"true"duringdinou devto mirror in-memory client bundles and manifests to.dinou/publicand.dinou/node-dev.DINOU_UNVENDORIZED— Set to"true"(equivalent todinou -u) to resolve dependencies fromnode_modulesinstead of Dinou's pre-compiled vendors.
Git & Secret Hygiene
- Ignore secret files in Git: Keep
.env.local,.env.*.local, and any.envcontaining real credentials in.gitignoreand.dockerignore. - Commit a
.env.example: Document required variable names with safe placeholder values so teammates get instant TypeScript autocomplete onnpx dinou typegen. - Never prefix private keys with
DINOU_PUBLIC_: Anything starting withDINOU_PUBLIC_is intentionally visible in browser DevTools.
Multi-Platform Runtimes
Dinou provides a unified environment model across all five server runtimes. Plain-text secrets work via both process.env and getContext().env everywhere on the server:
Node.js & Bun
On Node.js (dinou start) and Bun (dinou start:bun), Dinou loads your .env* hierarchy on startup and exposes variables on both process.env and getContext().env:
const dbUrl = process.env.DATABASE_URL;
const port = Number(process.env.PORT || 3000);Cloudflare Workers & Bindings
In Cloudflare Workers, configure non-secret variables under [vars] in wrangler.toml, local Worker secrets in .dev.vars, and production secrets via npx wrangler secret put MY_API_SECRET. With compatibility_flags = ["nodejs_compat"], Dinou automatically bridges text bindings onto process.env and exposes both text secrets and live resource bindings on getContext().env:
Cloudflare Resource Bindings (KV namespaces, D1 SQL databases, R2 buckets, Durable Objects) are live JavaScript host objects rather than strings, so they are accessed via getContext().env. Because getContext().env automatically falls back to process.env and Deno.env outside Cloudflare, your server code runs seamlessly in local npx dinou dev and on Cloudflare Edge without conditional checks.
// src/users/[id]/page_functions.ts
import { getContext } from "dinou";
import type { PageFunctions } from "./dinou";
export const getProps: PageFunctions["getProps"] = async (params) => {
// 1. Plain-text secrets work via process.env OR getContext().env across all runtimes:
const { env } = getContext();
const apiSecret = env.MY_API_SECRET;
// 2. Cloudflare Resource Bindings (KV, D1, R2 live instances):
const kv = env.MY_KV_NAMESPACE;
const cachedProfile = kv && params?.id ? await kv.get(`user:${params.id}`, "json") : null;
return { cachedProfile, hasSecret: Boolean(apiSecret) };
};To get full TypeScript autocompletion for Cloudflare bindings on getContext().env, augment Dinou's DinouEnv interface in dinou-env.d.ts:
// dinou-env.d.ts
/// <reference types="dinou/env" />
declare module "dinou" {
interface DinouEnv {
MY_KV_NAMESPACE?: KVNamespace;
DB?: D1Database;
MY_API_SECRET?: string;
}
}Deno (--allow-env & Deno KV)
Deno sandboxes environment access behind the --allow-env flag. Dinou's CLI passes the required permissions automatically when running npx dinou start:deno (or standalone binaries compiled with npx dinou build:deno:compile):
# Recommended via Dinou CLI (includes --unstable-kv and --allow-env)
npx dinou start:deno
# Or running the generated Deno orchestrator directly
deno run --unstable-kv --allow-net --allow-read --allow-write --allow-env --allow-sys .dinou/deno/main.jsDinou loads your .env* hierarchy into both Deno.env and process.env, so process.env.KEY, Deno.env.get("KEY"), and getContext().env.KEY all behave identically.
Netlify (Functions v2)
On Netlify, configure environment variables in the Netlify Dashboard, netlify.toml, or via netlify env:set MY_API_SECRET "...". Dinou's Functions v2 bundle automatically merges process.env with Netlify.env.toObject() on every request, making both build-time DINOU_PUBLIC_* constants and runtime secrets available via process.env and getContext().env.
TypeScript & Zod Validation
Dinou's type generator (dinou dev, dinou build, and dinou typegen) automatically scans variable names in your root .env* and .env.example files and augments NodeJS.ProcessEnv inside .dinou/types/routes.d.ts—giving you instant IDE autocomplete on process.env.* without ever writing secret values to disk.
To also guarantee at runtime that required variables are present and well-formed when your server boots, validate getContext().env (or process.env) with a schema library such as Zod:
// src/lib/env.ts (import ONLY in Server Components, page_functions, or Server Functions)
import { z } from "zod";
import { getContext } from "dinou";
const envSchema = z.object({
NODE_ENV: z.enum(["development", "production", "test"]).default("development"),
PORT: z.coerce.number().default(3000),
DATABASE_URL: z.string().url("DATABASE_URL must be a valid connection string"),
STRIPE_SECRET_KEY: z.string().min(1, "STRIPE_SECRET_KEY is required"),
DINOU_PUBLIC_STRIPE_KEY: z.string().min(1, "DINOU_PUBLIC_STRIPE_KEY is required"),
});
export function getServerEnv() {
const parsed = envSchema.safeParse(getContext().env);
if (!parsed.success) {
console.error("❌ Invalid environment variables:", parsed.error.format());
throw new Error("Invalid server environment configuration.");
}
return parsed.data;
}Anti-Leak Security & Bot Shield
Automated vulnerability scanners routinely probe web servers for exposed environment files using direct, nested, and percent-encoded paths:
GET /.env
GET /.env.production
GET /api/.env.local
GET /%2eenv- HTTP Anti-Bot Shield: Dinou's request handler inspects both raw and URL-decoded request paths and immediately terminates probes targeting
.env,.env.*,.git,.sql, and.bakwith404 Not Foundbefore plugins, dynamic routes, or ISG caching can run. - Static Dotfile Confinement: Dinou's static asset resolver blocks all hidden dotfile requests (except RFC 8615
/.well-known/*). - Physical Build Exclusion: Even if a
.envor.env.*file is accidentally placed insidepublic/, Dinou's Esbuild, Rollup, Webpack, Cloudflare, andexport-staticpipelines refuse to copy it into.dinou/dist3,.dinou/cloudflare/assets, orout/.
Production Deployment Checklist:
- Verify
.env,.env.local, and.env.*.localare listed in.gitignoreand.dockerignore. - Inject production secrets via your host's secret manager (e.g.
wrangler secret put,netlify env:set,fly secrets set,railway variables set). - Use
DINOU_PUBLIC_*strictly for public browser configuration—never for private credentials. - Validate required server secrets with a schema validator such as Zod.