Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 39 ยท Runtime Basics

Watch Mode and Hot Reloading

Speed up development with bun --watch and bun --hot - how each works, when to choose which, keeping state across reloads with globalThis, test watch mode and what files are watched.

During development you change a file, save, switch to the terminal, stop the program and start it again. Bun removes that loop with two flags: --watch restarts your program when a file changes, and --hot swaps in the new code without restarting the process. Both are built in and start in milliseconds, so no nodemon or ts-node-dev is needed. This lesson explains how each flag works, how to pick one, and how to keep state alive across reloads.

--watch: restart on change

Terminal
bun --watch run index.ts
bun --watch index.ts          # same thing

Bun starts your file, remembers which files it imported, and watches them. When any of them is saved, Bun kills the process and starts a new one. Everything resets: variables, open connections and timers all begin again, exactly as if you had stopped the program and re-run it.

That makes --watch simple and predictable. It suits:

  • scripts and command-line tools you want to re-run on save;
  • programs whose start-up is cheap;
  • anything with state you want cleared on every change.

Place the flag right after bun, before the file name, otherwise it is passed to your program as an argument:

Terminal
bun --watch server.ts --port 4000   # --watch is Bun's, --port is yours

Put it in a script so the team uses it consistently:

JSON
{
  "scripts": {
    "dev": "bun --watch src/index.ts",
    "start": "bun src/index.ts"
  }
}

Run it with bun run dev. Bun clears the terminal on each restart, which keeps output tidy. Pass --no-clear-screen if you would rather keep earlier output visible.

--hot: reload without restarting

Terminal
bun --hot server.ts

Hot mode reloads the changed modules and re-runs your entry file inside the same process. Open sockets, the HTTP server and global variables survive. Bun's server is aware of this: if your entry file calls Bun.serve(...) again after a reload, Bun updates the existing server's handler in place instead of trying to bind the same port twice.

TypeScript
// server.ts
const server = Bun.serve({
  port: 3000,
  fetch() {
    return new Response("Version 1");
  },
});

console.log(`Listening on ${server.url}`);

Start with bun --hot server.ts, change "Version 1" to "Version 2", save, and refresh the browser. The new response appears at once, and the connection pool, caches and open WebSockets were untouched.

This is not the browser-style HMR you may know from Vite. Bun does not patch a module graph in a smart way; it re-evaluates modules that changed. That is simple but means top-level code runs again, which leads to the next section.

Keeping state across hot reloads

When your entry file re-runs, anything it creates at the top level is created again. A counter initialised with let count = 0 would reset each time. To keep something alive, store it on globalThis, and create it only if it is missing:

TypeScript
declare global {
  var requestCount: number | undefined;
}

globalThis.requestCount ??= 0;

Bun.serve({
  port: 3000,
  fetch() {
    globalThis.requestCount!++;
    return new Response(`Request number ${globalThis.requestCount}`);
  },
});

The ??= assignment only sets the counter on the first run. After a reload the old value is still there, so the count keeps climbing through code edits. The same pattern protects database connections, caches and in-memory sessions.

Bun also offers import.meta.hot for code that wants to participate: import.meta.hot.data is an object that persists between reloads, and import.meta.hot.accept() marks a module as handling its own updates. For most server code, the globalThis trick is all you need.

A Node stand-in for the idea

The ??= pattern is plain JavaScript. This stand-in simulates three "reloads" by running the same initialisation three times, once with a fresh start and twice preserving state:

Node.js Stand-in: preserving state across simulated reloads (Node 24)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The global counter keeps counting; the local one always shows 1. Under bun --hot, this is exactly what happens to your variables.

Choosing between --watch and --hot

Question --watch --hot
What happens on save? New process Modules re-evaluated in place
State kept? No Only what you store on globalThis
Open connections Closed and reopened Stay open
Risk Slower restart for big apps Leaks, or stale state if you forget cleanup
Best for Scripts, CLIs, anything with simple start-up HTTP servers, WebSocket apps, long-lived state

If something behaves strangely under --hot (a timer that fires twice, for example), the cause is usually a top-level setInterval that was started again without clearing the old one. Fall back to --watch, which cannot have that problem.

TypeScript
// leak under --hot: a new interval every reload
setInterval(() => console.log("tick"), 1000);

// fixed: remember and clear the previous one
clearInterval(globalThis.ticker);
globalThis.ticker = setInterval(() => console.log("tick"), 1000);

What does Bun watch?

Bun watches the entry file and every file it imports, including files imported dynamically after the first run once they have loaded. It does not watch files you only read with Bun.file(...) or fs.readFile: changing a data file does not restart the process. For that, restart manually or import the data as a module. It also ignores node_modules, so editing a dependency does not trigger a reload.

Watch mode for tests and builds

The same idea applies elsewhere:

Terminal
bun test --watch          # re-run tests when files change
bun build ./src/index.ts --outdir ./dist --watch

Test watch mode reruns affected tests quickly, which makes test-driven development pleasant; the Testing chapter of this course builds on it. For front-end projects, serving an HTML file with bun ./index.html starts a development server with its own live reload; see Loaders and HTML entry points.

Debugging tips

  • Add console.log at the top of the entry file: a line printed once per save confirms your changes are picked up.
  • If nothing reloads, check that the file you edited is actually imported (directly or indirectly) by the entry file.
  • If you rename or delete a watched file, Bun may print an error until the import is fixed; fix the import and save again.
  • On network drives or in some containers, file-change notifications can be unreliable. Mount the project on a local volume or restart manually.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does bun --watch do when a watched file changes?

    Watch mode restarts the whole process, so all state is reset.
  2. 2. How can you keep a variable's value across bun --hot reloads?

    Top-level code re-runs on each reload. globalThis survives, so globalThis.x ??= initial keeps the old value.
  3. 3. Where should the --watch flag go in "bun --watch server.ts --port 4000"?

    Bun's flags go before the script name; everything after the script is passed to your program.
  4. 4. A timer fires twice after each hot reload. What is the likely cause?

    Hot reload re-runs top-level code in the same process, so old intervals keep running unless you clear them.

Summary

  • bun --watch restarts the process on every save; it is simple and resets all state.
  • bun --hot re-evaluates modules in the same process, keeping connections and globalThis data alive.
  • Guard long-lived resources with globalThis.x ??= ... and clear timers before re-creating them.
  • Put Bun's flags before the script name; they are scripted easily in package.json.
  • Watch mode also exists for bun test and bun build.

Next: Installing and Adding Packages