Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions docs/bundler/executables.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -364,6 +364,8 @@ Standalone executables can automatically load configuration files from the direc
- **`tsconfig.json`** and **`package.json`** loading is **disabled** — these are typically only needed at development time, and the bundler already uses them when compiling
- **`.env`** and **`bunfig.toml`** loading is **enabled** — these often contain runtime configuration that may vary per deployment

A standalone executable runs as `production` unless `NODE_ENV` (or `BUN_ENV`) is `development` or `test`. An unset variable, or any other value, counts as production. It loads `.env.production`, not `.env.development`, and `Bun.serve()` defaults to `development: false`. Set `NODE_ENV=development` in the environment to get the development behavior.

<Note>
In a future version of Bun, `.env` and `bunfig.toml` may also be disabled by default for more deterministic behavior.
</Note>
Expand Down Expand Up @@ -551,6 +553,8 @@ The result is a single file you can deploy anywhere without installing Node.js,

Bun serves the frontend assets with the correct MIME types and cache headers. Bun replaces the HTML import with a manifest object that `Bun.serve` uses to serve the pre-bundled assets.

Inside a compiled executable, `Bun.serve()` defaults to `development: false`. An uncaught error in a route handler returns a plain `500` response instead of the development error page, which includes the error message, the stack trace, and the source. To get the development behavior, run the executable with `NODE_ENV=development` or pass `development: true` to `Bun.serve()`. See [Automatic config loading](#automatic-config-loading).

For more on building full-stack applications, see the [full-stack guide](/bundler/fullstack).

---
Expand Down
5 changes: 5 additions & 0 deletions packages/bun-types/serve.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -765,6 +765,11 @@ declare module "bun" {

/**
* Whether to render contextual errors with Bun's error page
*
* Inside a standalone executable (`bun build --compile`), the default
* is `false` unless the `NODE_ENV` (or `BUN_ENV`) environment variable
* is `development` or `test`.
*
* @default process.env.NODE_ENV !== 'production'
*/
development?: Development;
Expand Down
9 changes: 9 additions & 0 deletions src/bun.js.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,15 @@ pub(crate) fn apply_standalone_runtime_flags(
b.resolver.opts.load_package_json = !graph
.flags
.contains(GraphFlags::DISABLE_AUTOLOAD_PACKAGE_JSON);

// A compiled executable boots as production unless NODE_ENV/BUN_ENV says otherwise.
let env = b.env_mut();
bun_core::handle_oom(env.load_process());
let node_env = env.get_node_env().unwrap_or(b"");
if node_env != b"development" && node_env != b"test" {
b.options.set_production(true);
b.resolver.opts.set_production(true);
}
}

#[cold]
Expand Down
2 changes: 1 addition & 1 deletion src/bundler/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1406,7 +1406,7 @@ impl<'a> BundleOptions<'a> {
self.rewrite_jest_for_tests
}

pub(crate) fn set_production(&mut self, value: bool) {
pub fn set_production(&mut self, value: bool) {
if self.force_node_env == ForceNodeEnv::Unspecified {
self.production = value;
self.jsx.development = !value;
Expand Down
53 changes: 53 additions & 0 deletions test/bundler/bundler_compile.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1298,6 +1298,59 @@ describe("bundler", () => {
},
run: { stdout: JSON.stringify({ server: "client sees the text", clientHasLiteral: true, clientHasBunfs: false }) },
});

// A compiled executable defaults Bun.serve to production. The dev error page
// (message, stack, source) must not be served unless the user opts in.
const serveDevelopmentEntry = (options: string) => /* js */ `
const server = Bun.serve({
port: 0,
hostname: "127.0.0.1",
${options}
routes: { "/boom": () => { throw new Error("secret-stack-detail"); } },
fetch() { return new Response("nf", { status: 404 }); },
});
const res = await fetch(server.url + "boom", { headers: { accept: "text/html" } });
const body = await res.text();
console.log(JSON.stringify({
development: server.development,
status: res.status,
contentType: res.headers.get("content-type"),
leaks: body.includes("secret-stack-detail"),
}));
server.stop(true);
process.exit(0);
`;
const serveProduction = JSON.stringify({
development: false,
status: 500,
contentType: "text/plain",
leaks: false,
});
const serveDevelopment = JSON.stringify({
development: true,
status: 500,
contentType: "text/html;charset=utf-8",
leaks: true,
});
// bunEnv clears NODE_ENV but not BUN_ENV. Clear both so the shell cannot leak in.
const nodeEnv = (env: Record<string, string> = {}) => ({ NODE_ENV: undefined, BUN_ENV: undefined, ...env });
itBundled("compile/ServeDefaultsToProduction", {
compile: true,
files: { "/entry.ts": serveDevelopmentEntry("") },
run: [
{ env: nodeEnv(), stdout: serveProduction },
{ env: nodeEnv({ NODE_ENV: "production" }), stdout: serveProduction },
{ env: nodeEnv({ NODE_ENV: "development" }), stdout: serveDevelopment },
{ env: nodeEnv({ BUN_ENV: "development" }), stdout: serveDevelopment },
{ env: nodeEnv({ NODE_ENV: "test" }), stdout: serveDevelopment },
{ env: nodeEnv({ NODE_ENV: "staging" }), stdout: serveProduction },
],
Comment thread
robobun marked this conversation as resolved.
Comment thread
robobun marked this conversation as resolved.
});
itBundled("compile/ServeExplicitDevelopment", {
compile: true,
files: { "/entry.ts": serveDevelopmentEntry("development: true,") },
run: { env: nodeEnv(), stdout: serveDevelopment },
});
itBundled("compile/Utf8", {
compile: true,
files: {
Expand Down
19 changes: 19 additions & 0 deletions test/bundler/bundler_compile_autoload.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,25 @@ describe("bundler", () => {
},
});

// A standalone executable runs as production, so it loads .env.production
// unless NODE_ENV asks for development.
itBundled("compile/AutoloadDotenvProductionSuffix", {
compile: true,
files: {
"/entry.ts": /* js */ `
console.log(process.env.TEST_VAR || "not found");
`,
},
runtimeFiles: {
"/.env.development": `TEST_VAR=from_development`,
"/.env.production": `TEST_VAR=from_production`,
},
run: [
{ stdout: "from_production", setCwd: true, env: { NODE_ENV: undefined, BUN_ENV: undefined } },
{ stdout: "from_development", setCwd: true, env: { NODE_ENV: "development", BUN_ENV: undefined } },
],
});

// Test that bunfig.toml is loaded by default (preload is executed)
itBundled("compile/AutoloadBunfigDefault", {
compile: true,
Expand Down
3 changes: 2 additions & 1 deletion test/bundler/expectBundled.ts
Original file line number Diff line number Diff line change
Expand Up @@ -424,7 +424,8 @@ export interface BundlerTestRunOptions {
*/
errorLineMatch?: RegExp;

env?: Record<string, string>;
/** An `undefined` value removes the variable inherited from `bunEnv`. */
env?: Record<string, string | undefined>;

runtime?: "bun" | "node";

Expand Down
Loading