Config
elements man configElements compiles your config as part of the build. Config is written in JSOC, a language that extends JSON to make configuration easier to write across different environments. The compiler reads your config at build time, resolves environment values, and emits plain JSON. Anything that depends on a config value rebuilds when the value changes. Missing env variables, invalid types, and other config mistakes are build errors at the call site, not runtime failures during a deploy.
A project has one config file: config.jsoc at the project root. It holds three
things: the project's package dependencies, the import map, and app config
(database, session, email, deploy, and so on). There is no package.json and no
tsconfig.json.
Build-Time Evaluation
The compiler evaluates config.jsoc against the current environment values and
emits the result as a JSON literal. The running app loads that JSON. It does not
parse JSOC and does not look up environment variables. This has three
effects.
Missing required values fail the build. env!("DB_HOST") with the variable
unset is a build diagnostic, not a runtime crash.
Wrong types fail the build. env<number>("SMTP_PORT", 587) with SMTP_PORT=abc
errors at the call site.
Config references are constant-folded. A reference to a config value becomes a literal in the emitted code.
Config is part of the build output. When a config value changes, every file that imports or references that value is rebuilt and the affected modules are reloaded.
env(...) runs at build time: it reads an environment variable while the
config compiles and folds the value into the output, so changing the variable
triggers a rebuild. It is not the same as process.env. Runtime code that must read a live
environment variable (one that can differ per process without a rebuild) reads
process.env directly, and that value is never folded into the build. Use
env(...) for every config value; use process.env only when a value
has to stay out of the build.
Environments
Your local development environment is called development. The default deploy
environment is called production. You can add others; staging is common.
An environment is defined in the project's config. It is not a name you make
up at the command line. development and production exist by default; any other
name works only once it has its own config/env/<name>.env and, for deploys, a
deploy.env.<name> block in config.jsoc. Commands that take an environment
(elements deploy production, elements deploy staging) select one of these
configured environments. Passing a name that isn't configured is an error, not a
request to create a new one.
The environment name is used in two places. It selects the env file that
supplies values (production loads config/env/production.env), and it names
the deploy target that holds the machines (production reads
deploy.env.production). Everything that serves live traffic runs under
production, so its secrets go in production.env and its machines go in
deploy.env.production. Add a new environment only when it has its own machines
and its own env file, like staging; you don't make one per app.
Tests aren't a separate environment. They run inside every environment, against that environment's config. There's no test environment to keep in sync with development or production.
JSOC
config.jsoc is written in JSOC: JSON with comments, unquoted keys, trailing
commas, and the env() function. elements man jsoc is the language page. It
covers the grammar, every form of env() and how values coerce, how an imported
.jsoc file is typed, and the @browser tag that decides which keys reach the
browser. The short version of env():
Usageenv("KEY", "default") // optional, falls back to the default when unset env!("KEY") // required, build error when unset env<number>("KEY", 5433) // coerced to number, boolean, or string
Env Files
Environment values come from two places. OS environment variables provide the
initial values. Files under config/env/ override them for the active
environment:
Directory layoutconfig/env/ development.env # used when ENV=development (default) production.env # used when ENV=production staging.env # used when ENV=staging
Format is KEY=value per line. Comments start with #. No quoting required.
Saving an env file triggers an automatic rebuild. JSOC files that reference the changed value re-evaluate, files that depend on those config values rebuild, and the build server reloads the affected modules.
Commit development.env. It holds dev-safe values that every contributor can
share. Don't commit production.env. It holds production secrets, and the
file is gitignored by default.
At a Glance
config.jsoc{ // Package dependencies. The package manager resolves these into // package.lock: don't edit package.lock by hand. package: { dependencies: { "@elements/app": "1.0.0", "@elements/ui": "1.0.0", }, }, // Import map. `#config` resolves to this file; `#app/*` resolves to // the app source tree, so `import home from "#app/pages/home"` works // from anywhere without relative paths. resolve: { imports: { "#config": "./config.jsoc", "#app/*": "./app/*", }, }, // Database connection. Empty/omitted fields fall back to the bundled // Postgres cluster (127.0.0.1:5433, user postgres, no password). database: { name: "my_app", host: env("DB_HOST", "127.0.0.1"), port: env<number>("DB_PORT", 5433), user: env("DB_USER", "postgres"), password: env("DB_PASSWORD", ""), ssl: env("DB_SSL", ""), sslRootCert: env("DB_SSL_ROOT_CERT", ""), }, // Email. `live: false` writes messages to the logger instead of sending. email: { live: env<boolean>("EMAIL_LIVE", false), from: "dev@example.com", host: env("SMTP_HOST"), port: env<number>("SMTP_PORT", 587), user: env("SMTP_USER"), password: env("SMTP_PASSWORD"), startTls: true, }, // Session policy. session: { expires: "30d", }, // How the app listens. The base for every environment, including the one you // run locally. A deploy environment overrides it under deploy.env.<name>. server: { port: env<number>("PORT", 4000), address: env("ADDRESS", "127.0.0.1"), domain: env!("DOMAIN"), }, deploy: { ssh: { user: "ubuntu", identityFile: "~/.ssh/id_ed25519" }, env: { production: { machines: [ { name: "production1", publicIp: "203.0.113.10", privateIp: "10.0.0.10" }, ], }, }, }, }
config/env/development.envDB_HOST=localhost DOMAIN=localhost
config/env/production.envDB_HOST=127.0.0.1 DOMAIN=example.com
Config Blocks
-
package: the project's dependency lists (dependencies,devDependencies, …). Resolved intopackage.lock. -
resolve.imports: the subpath import map (#config,#app/*, and any you add). -
database: connection settings:name,host,port,user,password,appUser,appPassword,default,ssl,sslRootCert. An empty field takes the bundled cluster's value.sslis the TLS mode by its libpq name (disable,require,verify-ca,verify-full) andsslRootCertis your provider's CA certificate file; a CA file alone gives verified TLS. Full topic:elements man database. -
session:expires("close"| a duration like"30d"or"1y"),autoRenew,domain,reaperIntervalSeconds. Full topic:elements man session. -
email: flat SMTP settings:live,log,logFormat,from,replyTo,host,port,user,password,secure,startTls,timeout. Full topic:elements man email. -
server:port(default 4000) andaddress(default127.0.0.1). The app listens on this port and address in every environment unlessdeployordeploy.env.<name>sets its own, soserver.portis the field to change when the port your app runs on locally is already taken.deployoverridesserver, anddeploy.env.<name>overridesdeploy.trailingSlash("never", the default, or"always") picks which form of a URL is canonical; seeelements man router.maxUploadis the largest request the app accepts, in bytes: every request body and every rpc message. The default is 25 MB (26214400). A larger body is a 413, and a larger rpc call fails in the browser with "Request too large". A route's ownmaxUploadraises or lowers it; seeelements man router.domainis every host the app answers: a string, or a map from the key a route'sdomainnames to a host, wheredefaultis for routes that name none (elements man router). Values come fromenv!(), so each env file supplies its own and a missing one fails the build. Unset islocalhost; local names end in.localhost. A deploy certifies each value and 301s itswwwpair to it.config.jsocserver: { domain: { default: env!("DOMAIN"), "shop.example.com": env!("DOMAIN_SHOP") } } -
deploy: SSH, machines, load balancer, services. Alsoportandaddresswhen a deployed environment needs something other than theservervalues. Full topic:elements man deploy. -
build:assetUrl,assetPath,sourceMap, andtypescript(a flat mirror of tsconfig'scompilerOptions). -
migrations:allowed,ignoreStaleMigrations. Full topic:elements man migrations. -
workers: number of job/test worker processes to spawn.
Importing Config
You import config the same way everywhere:
Exampleimport config from "#config"; let dbName = config.database.name;
#config is an import-map entry in config.jsoc that resolves to the config
file. Every key is server-only unless you tag it, so database credentials,
session policy, and SMTP passwords never reach the browser bundle. A
/** @browser */ tag on a property exposes that property, and everything under
it, to the browser as well:
config.jsoc{ /** @browser */ public: { appName: "Acme", supportEmail: "help@example.com" }, database: { ... }, }
To read a key in the browser, tag it. The browser's copy of #config holds
public and nothing else. Reading an untagged key in browser code is a build
error at the line that reads it, and the error names the key. Server code,
including the body of an @rpc function and a helper that only @rpc bodies
call, reads every key. The rules for which keys the browser's copy holds, including
the same key written twice, are in elements man jsoc.
process.env Constant Folding
process.env.X === "value" comparisons are constant-folded at build time. In
browser code the compiler reads env values directly from the active
environment's env file and folds the comparison to a literal, then eliminates
the dead branch from the bundle. This is independent of JSOC; you don't have to
expose a value through config.jsoc for process.env.X to fold.
ENV always holds the active environment's name, and comparisons on it fold in
server code too, because the build server gives every program that same
value at runtime. On the server, read other env file values through env(...)
in config.jsoc. A server program's process.env is the environment it was
started in, which does not include the env file, so only ENV folds there.
Exampleif (process.env.ENV === "production") { trackAnalytics(event); }
In a development build this becomes nothing (the whole if is dropped). In a
production build it becomes the trackAnalytics(event); call.
The same works for custom env variables:
Exampleif (process.env.FEATURE_BETA_CHECKOUT === "true") { return betaCheckoutFlow(); } return defaultCheckoutFlow();
When FEATURE_BETA_CHECKOUT is unset in the active environment, the beta branch
and any imports it pulls in are removed entirely from the bundle.
The folding handles ===, ==, !==, != against string literals, nested
&& and || chains where every operand is foldable, and boolean literals. Use
this for environment-conditional code that should not be in a target's
bundle. A module imported only inside a branch that folds to false is removed
from the bundle.
App and Asset URLs
getAppUrl() returns the app's external base URL for the active environment,
and getAssetUrl() returns the asset prefix (a CDN if configured, the app URL
otherwise). Both are server-only and read from the running app's config, so
you do not pass environment variables to them.
Exampleimport { getAppUrl, getAssetUrl } from "@elements/app"; let verifyUrl = `${getAppUrl()}/verify?token=${id}`; // e.g. https://example.com/verify?token=... let logoUrl = `${getAssetUrl()}/logo.png`; // e.g. https://cdn.example.com/logo.png
Resolution for getAppUrl():
- When the default domain (
server.domain) is a public host, the URL is<scheme>://<domain>:httpswhen ssl is on (the default) andhttpwhen it is explicitly off. No port: the load balancer listens in front of the app. - When it is a local name on a local machine, in any env, the URL is
http://<domain>:<port>with the env-resolved port (deploy.env.<env>.port>deploy.port>server.port> 4000). - On a deploy machine with a local name, the URL is
http://localhost.
Resolution for getAssetUrl():
build.assetUrl(top-level inconfig.jsoc, env-substituted viaenv("ASSET_URL")) when set.- Otherwise
getAppUrl().
Reading config.build.assetUrl from an imported #config does not give the
same result as calling getAssetUrl(). The field is undefined or empty
whenever no CDN is configured. In that case getAssetUrl() returns
getAppUrl(), the app's own URL, built from the active environment's
domain, ssl setting and port.
Put a CDN URL in build.assetUrl: set
ASSET_URL=https://cdn.example.com in config/env/production.env and
ASSET_URL= (empty) in development.env, then
build.assetUrl: env("ASSET_URL") in config.jsoc. With the empty development value,
getAssetUrl() returns getAppUrl(), so assets resolve to the development
server.
The active environment is determined by env() (also exported from
@elements/app), which reads process.env.ENV set by the build server when
it spawns each program. Environment names are an open set: ENV defaults to
development locally and elements deploy defaults to production, and any
other name works the same way.
Where the app runs is a separate question from which environment it runs in.
isDeployMachine() from @elements/app (server-only) is true on a deploy
machine and false on a local machine, whatever ENV is. Branch on it, not on
the environment name, for behavior that belongs to a local machine, such as a
preview route or a debug page:
Exampleimport { isDeployMachine } from "@elements/app"; if (!isDeployMachine()) { app.route("/dev/preview", preview); }
Related
- Database:
elements man database. Thedatabaseblock and the bundled Postgres cluster. - Session:
elements man session. Thesessionblock and lifetime policy. - Email:
elements man email. Theemailblock for SMTP and development-mode logging. - Deploy:
elements man deploy. Thedeployblock for SSH and the machine list.