Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
description: How environment variables are defined, validated, and consumed across Carbon apps and packages paths: - "apps/" - "packages/env/" - "packages/auth/**" - ".env*" - "scripts/setup-env-files.ts"
Environment Configuration
Source of truth
All env access lives in packages/env/src/index.ts (the @carbon/env
package). @carbon/config and @carbon/auth/config/env both just
export * from "@carbon/env", and @carbon/auth's root index re-exports it, so
import { SUPABASE_URL } from "@carbon/auth" and from "@carbon/auth/config"
both resolve here. Prefer importing the exported constant over reading
process.env directly.
import { SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY } from "@carbon/auth";
Every variable is declared once in packages/env/src/schema.ts: group, one-line
description, optional zod type, secret, browser, required and aliases.
getEnv(name) reads one — its own name first, then its deprecated aliases
(APP_URL ← VERCEL_URL, APP_ENV ← VERCEL_ENV, DATABASE_URL ←
SUPABASE_DB_URL, AI_API_KEY ← OPENAI_API_KEY).
- Server reads
process.env; browser readswindow.env, and asecretvariable reads as""there. validateEnv(validate.ts) runs once at module load on the server andformatReportprints every problem together, grouped as Required, Invalid and half-configured features, plus the features that are off. A secret's value is never printed.required: "error"throws that report.required: "warn", an invalid type and a half-configured feature (some of a group'sneededvariables set, not all) are only printed for now and become errors in the next release.- Not validated under Vitest or with
SKIP_ENV_VALIDATIONset. - The
deployments-set-required-envcheck (@carbon/checks) reads whatsst.config.ts,crbn upand the Vercel projects set and fails when any would hit a startup error.
window.env is populated by getBrowserEnv(), injected via an inline script in
each app's root.tsx (apps/erp/app/root.tsx, apps/mes/app/root.tsx). Only the
keys listed in getBrowserEnv() are exposed client-side.
Env files & dev workflow
.env— genuine secrets only (OAuth, Stripe, Resend, AI keys). Gitignored. Template is.env.example..env.local— generated bycrbn up(packages/dev/src/commands/up.ts); "Do not edit by hand". Holds per-worktree ports, portless*.devURLs, dev Supabase keys, Redis/Inngest dev settings,DEV_BYPASS_EMAIL,ASSEMBLER_SERVICE_URL/_API_KEY, plus the keys inFROM_DOT_ENV(packages/dev/src/env.ts) copied from.env(a key with a fallback is always written; one without only when set). Vite / React Router auto-load it on top of.env, with.env.localoverriding.#forceescape hatch — end a line in.envwith a#forcecomment (e.g.ASSEMBLER_SERVICE_URL=https://… #force) andwriteEnv(packages/dev/src/env.ts) omits that key from the generated.env.local, so the.envvalue wins. Survives regeneration (the marker lives in.env, which crbn never writes). Use it to point a local stack at a remote service.- Self-hosting? The Swarm stack does not use a prod
.envfor secrets — it uses Docker Swarm secrets + non-secretcontrib/deploying/simple-docker-caddy/.env. See the self-host deployment README. scripts/setup-env-files.tssymlinks the root.env(and.env.localif present) intoapps/*and packagesdatabase,jobs,kv.
Key vars by domain (names verified in code)
Supabase / DB — SUPABASE_URL, SUPABASE_ANON_KEY (public),
SUPABASE_SERVICE_ROLE_KEY (required, secret), SUPABASE_DB_URL (required,
secret), SUPABASE_JWT_SECRET (optional), plus
SUPABASE_AUTH_EXTERNAL_{GOOGLE,AZURE}_CLIENT_ID/SECRET for OAuth.
Redis — REDIS_URL (required, secret).
Jobs (Inngest) — INNGEST_SIGNING_KEY, INNGEST_EVENT_KEY (required unless
INNGEST_DEV is set). Dev also uses INNGEST_DEV, INNGEST_BASE_URL,
INNGEST_SERVE_HOST, INNGEST_TLS_HOST.
Auth / session — SESSION_SECRET (required; also signs the short-lived,
single-use carbon-oauth-state cookie in @carbon/auth/oauth-state.server),
AUTH_COOKIE_SUFFIX (optional; suffixes the auth cookie names when another deployment
shares DOMAIN — EU sets eu, see authentication-system.md), AUTH_PROVIDERS
(email,google,azure,passkey,sso; gate via isAuthProviderEnabled),
CLOUDFLARE_TURNSTILE_SITE_KEY / _SECRET_KEY, RATE_LIMIT. IS_VERCEL reads
Vercel's own VERCEL=1. BOT_PROTECTION (botid | turnstile, unset = BotID for
Cloud on Vercel, else Turnstile if keyed) picks the login bot check (see
authentication-system.md).
SAML_ENABLED / SAML_PRIVATE_KEY are NOT @carbon/env vars — they live in
root .env and reach GoTrue via docker-compose substitution (GOTRUE_SAML_*).
Both crbn up and crbn reload preload .env.local then .env into
process.env before invoking compose so these survive a recreate; see the
crbn reload lesson in .ai/lessons.md.
Stripe — STRIPE_SECRET_KEY, STRIPE_WEBHOOK_SECRET,
STRIPE_CONNECT_WEBHOOK_SECRET (all optional), STRIPE_BYPASS_COMPANY_IDS,
STRIPE_BYPASS_USER_IDS. The two webhook secrets are distinct: the platform
endpoint (/api/webhook/stripe, billing) and the Connect endpoint
(/api/webhook/stripe-connect, connected-account events) are signed separately.
Email — SMTP_HOST, SMTP_PORT (465 = implicit TLS, 587 = STARTTLS,
default 587), SMTP_USER, SMTP_PASSWORD, SMTP_FROM (default
Carbon <[email protected]>). All optional — unset disables email sending.
Optional RESEND_API_KEY (marketing contacts; also a legacy SMTP fallback via
smtp.resend.com when SMTP_* is unset) and RESEND_AUDIENCE_ID.
Push — no env vars. getVapidDetails() (@carbon/env/push.server,
server-only because it imports node:crypto) derives the VAPID pair from
SESSION_SECRET with HKDF-SHA256 (salt carbon, info web-push-vapid/<n>,
the first n whose 32 bytes are a valid P-256 scalar) and memoizes it. The
subject is getAppUrl() when it is https, else mailto: + SUPPORT_EMAIL.
Every browser subscription is bound to the public key, so the pair must be
stable: never generate it at build time (images are published per commit, which
would rotate it and ship the private key). Rotating SESSION_SECRET rotates the
pair — each browser re-subscribes on its next visit
(useRestoreBrowserNotifications); until then, a push to an old-key row gets
401 (WNS) or 403 (FCM), and send-push logs a warning and keeps the row. It
never deletes on those codes: Apple answers 403 for a token it refuses, which
would remove every Safari row. The hash, salt and info label are frozen —
push.server.test.ts pins a known answer.
isPushConfigured() is false only without SESSION_SECRET (a
SKIP_ENV_VALIDATION script). The public key reaches the browser through the
account notifications loader and the app shell loader (pushPublicKey), not
getBrowserEnv().
Integrations (all optional) — Ramp (RAMP_CLIENT_ID, public and exposed by
getBrowserEnv() for the authorize URL; RAMP_CLIENT_SECRET, server-only for code
exchange/token refresh), Slack (SLACK_BOT_TOKEN, SLACK_CLIENT_ID,
SLACK_CLIENT_SECRET, SLACK_SIGNING_SECRET,
SLACK_OAUTH_REDIRECT_URL — one Slack app serves the Assistant and workflow steps; the value may still name the legacy /api/integrations/slack/oauth path, which forwards to the connections callback), Onshape (two Onshape apps, no shared variable:
ONSHAPE_CLIENT_ID/SECRET + ONSHAPE_OAUTH_REDIRECT_URL for the onshape sync
integration, ONSHAPE_V2_CLIENT_ID/SECRET + ONSHAPE_V2_OAUTH_REDIRECT_URL for the
onshape-v2 panel. crbn up writes ONSHAPE_V2_OAUTH_REDIRECT_URL
into .env.local from the stack's ERP_URL, so each worktree host must be registered
on the panel's Onshape app, or pinned in .env with #force), Google (GOOGLE_CLIENT_ID, public and exposed by
getBrowserEnv() so the Google Calendar and Gmail cards can show "Coming soon";
GOOGLE_CLIENT_SECRET, GOOGLE_OAUTH_REDIRECT_URL — one Google app serves both
workflow pieces; its own google feature group, so a half-set app is reported), Xero, QuickBooks, Jira (each *_CLIENT_ID/SECRET,
plus webhook/redirect/state secrets), EXCHANGE_RATES_API_KEY,
GOOGLE_PLACES_API_KEY, AI keys ANTHROPIC_API_KEY / OPENAI_API_KEY.
Ramp intentionally has no separate RAMP_STATE_SECRET. issueOAuthState() /
issueOAuthStates() store a random nonce plus {integrationId,userId,companyId,expiresAt}
per integration (keyed by integrationId, 1 h lifetime, a still-fresh one is reused) in
one signed HttpOnly cookie backed by SESSION_SECRET; pass the request so other
integrations' pending states survive. consumeOAuthState() validates all fields and
removes that integration's entry on every attempt (the cookie is destroyed once empty).
The integrations page loader issues none (pinned by integrations.oauth-state.test.ts).
An integration with an oauth config (Ramp, Xero, QuickBooks, Jira) starts at
api+/integrations.$id.connect.ts (startOAuthConnect in useIntegrationInstall.ts
navigates there): it issues the state with the chosen install mode as an extra and
redirects to the authorize URL it builds server-side. Onshape's
api+/integrations.onshape.install.ts issues its own (via beginOnshapeAuthorization,
@carbon/ee/onshape.server), Onshape Government's is issued by the integration settings
save — its OAuth client is the customer's private app, not an env var — and each callback
consumes it.
Slack and every other workflow piece use the same cookie:
api+/integrations.connections.$piece.connect.ts issues the state with the account
name and an optional connectionId as extras, and api+/integrations.connections.callback.ts
consumes it with consumeOAuthStateByValue, since one callback serves every piece. Managed deployment propagates both Ramp OAuth
vars through ci/src/deploy.ts → sst.config.ts → the ERP service only.
Analytics / config — POSTHOG_API_HOST, POSTHOG_PROJECT_PUBLIC_KEY
(optional, public), CARBON_EDITION (community|cloud|enterprise|test →
CarbonEdition), CONTROLLED_ENVIRONMENT (ITAR flag), INTEGRATION_EARLY_ACCESS_USER_IDS (server-only, comma-separated user ids that can install an internalOnly integration on Cloud; a fallback beside the integration-early-access flag until a flags source is live), DEFAULT_LANGUAGE
(default en), GTM_URL, GTM_EVENTS_API_SECRET_KEY.
Maintenance and status (both optional, server-only) — MAINTENANCE_MODE=true
makes maintenanceMiddleware (@carbon/auth/middleware/maintenance.server, in
every app's root middleware, after security) answer every request with a 503:
a page renders the root ErrorBoundary's 503 screen, an open tab gets the same
screen on its next navigation, and a resource route (API, MCP, webhooks,
/api/inngest) returns a bare 503 with Retry-After: 300 so the caller retries.
/health answers 200 { status: "maintenance" } without probing the database,
so the load balancer keeps the tasks. The flag is read at start: changing it
needs a restart or redeploy. SYSTEM_STATUS_URL is a JSON document the app
reads for { latestVersion?, announcement? } (systemStatusValidator,
@carbon/lib/system-status); unset means no request is made, on any edition.
getSystemStatus() caches it in Redis for 5 minutes (a failure for 1), each
app serves it at api+/system-status, and the shell shows the announcement
with AnnouncementBar (@carbon/react). latestVersion is returned but not
shown — Carbon has no version to compare it with. Neither variable is on the
workspaces row, so ci/src/deploy.ts does not set them; sst.config.ts
forwards them from the deploying process's environment.
Feature flags (both optional, server-only) — CARBON_FLAGS_ENDPOINT is a
flagd JSON document (@carbon/env/flags.server, spec
.ai/specs/2026-10-28-feature-flags.md); CARBON_FLAGS_HEADERS holds its
request headers in the OTEL_EXPORTER_OTLP_HEADERS format (secret: true, it
carries the token). An https: endpoint is the Carbon Cloud source: each ERP
and MES process reads the shared copy in Redis (redisFlagsStore, @carbon/kv,
hash flags:<scope>) every 10 s and, when that copy is older than 60 s, one
process fetches the source under a lease. A data: endpoint loads
once: ci/src/deploy.ts fetches each AWS workspace's document at deploy time
(workspaces.flags_endpoint / flags_token, 32 KiB cap for the task
definition) and passes it as a data: URL, and sst.config.ts forwards it.
Unset means every flag answers its registry default (packages/env/src/flags.ts).
Read flags only with flags.* / evaluateBrowserFlags and, in React,
useFeatureFlags().feature(key) (@carbon/react), never with an
OpenFeature client.
Tracing (all optional) — the standard OpenTelemetry variables, read raw by
the OTel SDK (not @carbon/env): OTEL_EXPORTER_OTLP_ENDPOINT (or
OTEL_EXPORTER_OTLP_TRACES_ENDPOINT) turns server tracing on,
OTEL_EXPORTER_OTLP_HEADERS carries the backend's auth, and
OTEL_SERVICE_NAME / OTEL_TRACES_SAMPLER / OTEL_TRACES_SAMPLER_ARG tune it.
Unset = no tracing. See packages/logger/AGENTS.md → Tracing. The Rust assembler
reads the same variables (apps/assembler/AGENTS.md → Tracing).
Deployment — APP_URL (this app's own origin, optional; VERCEL_URL is its
deprecated alias), APP_ENV (production | preview | development; alias
VERCEL_ENV, defaults to NODE_ENV), NODE_ENV. ERP_URL /
MES_URL drive getAppUrl() / getMESUrl().
URL resolution
getAppUrl() / getMESUrl(): in prod (VERCEL_ENV or NODE_ENV =
production) return ERP_URL/MES_URL, falling back to itar.carbon.ms /
app.carbon.ms based on CONTROLLED_ENVIRONMENT. In preview, derive from
VERCEL_URL. In dev, honor the ERP_URL/MES_URL that crbn up wrote into
.env.local (portless *.dev hostnames), else localhost:3000/3001.
MES posts to the ERP over HTTP (erpPostingUrl, apps/mes/app/services/erp.ts)
and does not use getAppUrl() for it: on a preview that is MES itself. It takes
ERP_URL; without it, localhost:3000 in local dev and app.carbon.ms /
itar.carbon.ms on Carbon Cloud production (CARBON_EDITION=cloud, not a
preview). Anywhere else a posting fails with a configuration error, so a
self-hosted or preview MES needs ERP_URL.
Gotchas
- Validation runs at module load. Missing
SUPABASE_SERVICE_ROLE_KEY,DATABASE_URL(orSUPABASE_DB_URL),REDIS_URL,SESSION_SECRET, or the Inngest keys withoutINNGEST_DEV, stops boot. MissingSUPABASE_URL,SUPABASE_ANON_KEY, and outside Cloud in productionERP_URL,MES_URLandSMTP_FROM, is a warning for now.POSTHOG_*andAPP_URLare optional. - Email is deliberately lazy:
packages/lib/src/email.server.tsbuilds the SMTP transport on first send, never at import, so a deployment with no mail config boots fine andsendEmailno-ops. - Only keys in
getBrowserEnv()reach the client; adding a public var meansbrowser: truein the schema, adding it there (typecheck enforces this), AND adding it to each app's root-loaderenvobject. - Don't put ports/URLs/Supabase/Redis/Inngest dev values in
.env—crbn upowns them via.env.local, which overrides.env.