diff options
| author | 2023-07-26 14:59:39 -0700 | |
|---|---|---|
| committer | 2023-07-26 14:59:39 -0700 | |
| commit | 4c89c60867591b50e0b31bf5009fd5ad6a3cebe1 (patch) | |
| tree | fc1d2f47309c0345a850933496baa40d94bfdcbb /docs/guides/http/hot.md | |
| parent | 6bfee02301a2e2a0b79339974af0445eb5a2688f (diff) | |
| download | bun-4c89c60867591b50e0b31bf5009fd5ad6a3cebe1.tar.gz bun-4c89c60867591b50e0b31bf5009fd5ad6a3cebe1.tar.zst bun-4c89c60867591b50e0b31bf5009fd5ad6a3cebe1.zip | |
Add files (#3826)
Diffstat (limited to 'docs/guides/http/hot.md')
| -rw-r--r-- | docs/guides/http/hot.md | 55 |
1 files changed, 55 insertions, 0 deletions
diff --git a/docs/guides/http/hot.md b/docs/guides/http/hot.md new file mode 100644 index 000000000..c033e5be5 --- /dev/null +++ b/docs/guides/http/hot.md @@ -0,0 +1,55 @@ +--- +name: Hot reload an HTTP server +--- + +Bun supports the [`--hot`](/docs/runtime/hot#hot-mode) flag to run a file with hot reloading enabled. When any module or file changes, Bun re-runs the file. + +```sh +bun --hot run index.ts +``` + +--- + +To avoid re-running `Bun.serve()` during `--hot` reloads, you should assign the `Server` instance as a property of `globalThis`. The `globalThis` object survives hot reloads. + +```ts +import { type Serve, type Server } from "bun"; + +// make TypeScript happy +declare global { + var server: Server; +} + +// define server parameters +const serveOptions: Serve = { + port: 3000, + fetch(req) { + return new Response(`Hello world`); + }, +}; + +if (!globalThis.server) { + globalThis.server = Bun.serve(serveOptions); +} else { + globalThis.server.reload(serveOptions); +} +``` + +--- + +To avoid manually calling `server.reload()`, you can use start a server with Bun's [object syntax](/docs/runtime/hot#http-servers). If you `export default` a plain object with a `fetch` handler defined, then run this file with Bun, Bun will start an HTTP server as if you'd passed this object into `Bun.serve()`. + +With this approach, Bun automatically reloads the server when reloads happen. + +See [HTTP > Hot Reloading](<[/docs/api/http](https://bun.sh/docs/api/http#hot-reloading)>) for full docs. + +```ts +import { type Serve } from "bun"; + +export default { + port: 3000, + fetch(req) { + return new Response(`Hello world`); + }, +} satisfies Serve; +``` |
