bun-types 1.3.2-canary.20251105T140650 → 1.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bun.d.ts +102 -6
- package/docs/README.md +28 -0
- package/docs/bundler/bytecode.mdx +465 -0
- package/docs/bundler/{css.md → css.mdx} +97 -101
- package/docs/bundler/esbuild.mdx +253 -0
- package/docs/bundler/{executables.md → executables.mdx} +130 -221
- package/docs/bundler/fullstack.mdx +1064 -0
- package/docs/bundler/{hmr.md → hot-reloading.mdx} +74 -79
- package/docs/bundler/{html.md → html-static.mdx} +148 -111
- package/docs/bundler/index.mdx +1499 -0
- package/docs/bundler/loaders.mdx +356 -0
- package/docs/bundler/{macros.md → macros.mdx} +83 -84
- package/docs/bundler/minifier.mdx +1306 -0
- package/docs/bundler/plugins.mdx +411 -0
- package/docs/feedback.mdx +85 -0
- package/docs/guides/binary/{arraybuffer-to-array.md → arraybuffer-to-array.mdx} +3 -1
- package/docs/guides/binary/{arraybuffer-to-blob.md → arraybuffer-to-blob.mdx} +3 -1
- package/docs/guides/binary/{arraybuffer-to-buffer.md → arraybuffer-to-buffer.mdx} +3 -1
- package/docs/guides/binary/{arraybuffer-to-string.md → arraybuffer-to-string.mdx} +3 -1
- package/docs/guides/binary/{arraybuffer-to-typedarray.md → arraybuffer-to-typedarray.mdx} +3 -1
- package/docs/guides/binary/{blob-to-arraybuffer.md → blob-to-arraybuffer.mdx} +3 -1
- package/docs/guides/binary/{blob-to-dataview.md → blob-to-dataview.mdx} +3 -1
- package/docs/guides/binary/{blob-to-stream.md → blob-to-stream.mdx} +3 -1
- package/docs/guides/binary/{blob-to-string.md → blob-to-string.mdx} +3 -1
- package/docs/guides/binary/{blob-to-typedarray.md → blob-to-typedarray.mdx} +3 -1
- package/docs/guides/binary/{buffer-to-arraybuffer.md → buffer-to-arraybuffer.mdx} +3 -1
- package/docs/guides/binary/{buffer-to-blob.md → buffer-to-blob.mdx} +3 -1
- package/docs/guides/binary/{buffer-to-readablestream.md → buffer-to-readablestream.mdx} +3 -1
- package/docs/guides/binary/{buffer-to-string.md → buffer-to-string.mdx} +3 -1
- package/docs/guides/binary/{buffer-to-typedarray.md → buffer-to-typedarray.mdx} +3 -1
- package/docs/guides/binary/{dataview-to-string.md → dataview-to-string.mdx} +3 -1
- package/docs/guides/binary/{typedarray-to-arraybuffer.md → typedarray-to-arraybuffer.mdx} +3 -1
- package/docs/guides/binary/{typedarray-to-blob.md → typedarray-to-blob.mdx} +3 -1
- package/docs/guides/binary/{typedarray-to-buffer.md → typedarray-to-buffer.mdx} +3 -1
- package/docs/guides/binary/{typedarray-to-dataview.md → typedarray-to-dataview.mdx} +3 -1
- package/docs/guides/binary/{typedarray-to-readablestream.md → typedarray-to-readablestream.mdx} +3 -1
- package/docs/guides/binary/{typedarray-to-string.md → typedarray-to-string.mdx} +3 -1
- package/docs/guides/deployment/aws-lambda.mdx +204 -0
- package/docs/guides/deployment/digital-ocean.mdx +161 -0
- package/docs/guides/deployment/google-cloud-run.mdx +197 -0
- package/docs/guides/deployment/{railway.md → railway.mdx} +42 -54
- package/docs/guides/deployment/render.mdx +82 -0
- package/docs/guides/deployment/vercel.mdx +99 -0
- package/docs/guides/ecosystem/{astro.md → astro.mdx} +16 -6
- package/docs/guides/ecosystem/{discordjs.md → discordjs.mdx} +21 -18
- package/docs/guides/ecosystem/{docker.md → docker.mdx} +25 -14
- package/docs/guides/ecosystem/{drizzle.md → drizzle.mdx} +32 -22
- package/docs/guides/ecosystem/{edgedb.md → edgedb.mdx} +63 -34
- package/docs/guides/ecosystem/{elysia.md → elysia.mdx} +11 -11
- package/docs/guides/ecosystem/{express.md → express.mdx} +12 -9
- package/docs/guides/ecosystem/{hono.md → hono.mdx} +16 -8
- package/docs/guides/ecosystem/{mongoose.md → mongoose.mdx} +26 -21
- package/docs/guides/ecosystem/{neon-drizzle.md → neon-drizzle.mdx} +49 -35
- package/docs/guides/ecosystem/{neon-serverless-postgres.md → neon-serverless-postgres.mdx} +16 -11
- package/docs/guides/ecosystem/{nextjs.md → nextjs.mdx} +18 -10
- package/docs/guides/ecosystem/{nuxt.md → nuxt.mdx} +45 -11
- package/docs/guides/ecosystem/{pm2.md → pm2.mdx} +7 -9
- package/docs/guides/ecosystem/prisma-postgres.mdx +169 -0
- package/docs/guides/ecosystem/prisma.mdx +164 -0
- package/docs/guides/ecosystem/{qwik.md → qwik.mdx} +18 -11
- package/docs/guides/ecosystem/{react.md → react.mdx} +9 -7
- package/docs/guides/ecosystem/{remix.md → remix.mdx} +45 -26
- package/docs/guides/ecosystem/{sentry.md → sentry.mdx} +7 -5
- package/docs/guides/ecosystem/{solidstart.md → solidstart.mdx} +21 -13
- package/docs/guides/ecosystem/{ssr-react.md → ssr-react.mdx} +9 -11
- package/docs/guides/ecosystem/{stric.md → stric.mdx} +16 -17
- package/docs/guides/ecosystem/{sveltekit.md → sveltekit.mdx} +42 -29
- package/docs/guides/ecosystem/{systemd.md → systemd.mdx} +27 -26
- package/docs/guides/ecosystem/upstash.mdx +87 -0
- package/docs/guides/ecosystem/{vite.md → vite.mdx} +20 -14
- package/docs/guides/html-rewriter/{extract-links.md → extract-links.mdx} +11 -7
- package/docs/guides/html-rewriter/{extract-social-meta.md → extract-social-meta.mdx} +6 -2
- package/docs/guides/http/{cluster.md → cluster.mdx} +10 -7
- package/docs/guides/http/{fetch-unix.md → fetch-unix.mdx} +5 -3
- package/docs/guides/http/{fetch.md → fetch.mdx} +5 -3
- package/docs/guides/http/{file-uploads.md → file-uploads.mdx} +18 -15
- package/docs/guides/http/{hot.md → hot.mdx} +9 -7
- package/docs/guides/http/{proxy.md → proxy.mdx} +7 -5
- package/docs/guides/http/{server.md → server.mdx} +4 -2
- package/docs/guides/http/{simple.md → simple.mdx} +4 -2
- package/docs/guides/http/{stream-file.md → stream-file.mdx} +6 -4
- package/docs/guides/http/{stream-iterator.md → stream-iterator.mdx} +5 -3
- package/docs/guides/http/{stream-node-streams-in-bun.md → stream-node-streams-in-bun.mdx} +4 -2
- package/docs/guides/http/{tls.md → tls.mdx} +5 -3
- package/docs/guides/index.mdx +10 -0
- package/docs/guides/install/{add-dev.md → add-dev.mdx} +8 -6
- package/docs/guides/install/add-git.mdx +38 -0
- package/docs/guides/install/{add-optional.md → add-optional.mdx} +7 -5
- package/docs/guides/install/{add-peer.md → add-peer.mdx} +13 -11
- package/docs/guides/install/{add-tarball.md → add-tarball.mdx} +7 -5
- package/docs/guides/install/{add.md → add.mdx} +12 -10
- package/docs/guides/install/{azure-artifacts.md → azure-artifacts.mdx} +15 -12
- package/docs/guides/{runtime/cicd.md → install/cicd.mdx} +13 -13
- package/docs/guides/install/{custom-registry.md → custom-registry.mdx} +6 -4
- package/docs/guides/install/{from-npm-install-to-bun-install.md → from-npm-install-to-bun-install.mdx} +50 -34
- package/docs/guides/install/{git-diff-bun-lockfile.md → git-diff-bun-lockfile.mdx} +14 -11
- package/docs/guides/install/{jfrog-artifactory.md → jfrog-artifactory.mdx} +4 -4
- package/docs/guides/install/{npm-alias.md → npm-alias.mdx} +6 -4
- package/docs/guides/install/{registry-scope.md → registry-scope.mdx} +6 -4
- package/docs/guides/install/{trusted.md → trusted.mdx} +22 -18
- package/docs/guides/install/{workspaces.md → workspaces.mdx} +13 -13
- package/docs/guides/install/{yarnlock.md → yarnlock.mdx} +15 -9
- package/docs/guides/process/{argv.md → argv.mdx} +17 -9
- package/docs/guides/process/{ctrl-c.md → ctrl-c.mdx} +4 -2
- package/docs/guides/process/{ipc.md → ipc.mdx} +13 -10
- package/docs/guides/process/{nanoseconds.md → nanoseconds.mdx} +3 -1
- package/docs/guides/process/{os-signals.md → os-signals.mdx} +3 -1
- package/docs/guides/process/{spawn-stderr.md → spawn-stderr.mdx} +4 -1
- package/docs/guides/process/{spawn-stdout.md → spawn-stdout.mdx} +3 -1
- package/docs/guides/process/{spawn.md → spawn.mdx} +3 -1
- package/docs/guides/process/{stdin.md → stdin.mdx} +15 -7
- package/docs/guides/read-file/{arraybuffer.md → arraybuffer.mdx} +5 -3
- package/docs/guides/read-file/{buffer.md → buffer.mdx} +4 -2
- package/docs/guides/read-file/{exists.md → exists.mdx} +4 -2
- package/docs/guides/read-file/{json.md → json.mdx} +4 -2
- package/docs/guides/read-file/{mime.md → mime.mdx} +3 -1
- package/docs/guides/read-file/{stream.md → stream.mdx} +3 -1
- package/docs/guides/read-file/{string.md → string.mdx} +3 -1
- package/docs/guides/read-file/{uint8array.md → uint8array.mdx} +3 -1
- package/docs/guides/read-file/{watch.md → watch.mdx} +6 -8
- package/docs/guides/runtime/{build-time-constants.md → build-time-constants.mdx} +24 -22
- package/docs/guides/{install/cicd.md → runtime/cicd.mdx} +11 -7
- package/docs/guides/runtime/{codesign-macos-executable.md → codesign-macos-executable.mdx} +14 -9
- package/docs/guides/runtime/{define-constant.md → define-constant.mdx} +20 -16
- package/docs/guides/runtime/{delete-directory.md → delete-directory.mdx} +5 -3
- package/docs/guides/runtime/{delete-file.md → delete-file.mdx} +4 -2
- package/docs/guides/runtime/{heap-snapshot.md → heap-snapshot.mdx} +5 -3
- package/docs/guides/runtime/{import-html.md → import-html.mdx} +4 -2
- package/docs/guides/runtime/{import-json.md → import-json.mdx} +6 -4
- package/docs/guides/runtime/{import-toml.md → import-toml.mdx} +5 -3
- package/docs/guides/runtime/{import-yaml.md → import-yaml.mdx} +9 -7
- package/docs/guides/runtime/{read-env.md → read-env.mdx} +10 -5
- package/docs/guides/runtime/{set-env.md → set-env.mdx} +14 -10
- package/docs/guides/runtime/{shell.md → shell.mdx} +6 -4
- package/docs/guides/runtime/{timezone.md → timezone.mdx} +10 -7
- package/docs/guides/runtime/{tsconfig-paths.md → tsconfig-paths.mdx} +5 -3
- package/docs/guides/runtime/{typescript.md → typescript.mdx} +8 -6
- package/docs/guides/runtime/{vscode-debugger.md → vscode-debugger.mdx} +12 -11
- package/docs/guides/runtime/{web-debugger.md → web-debugger.mdx} +39 -18
- package/docs/guides/streams/{node-readable-to-arraybuffer.md → node-readable-to-arraybuffer.mdx} +3 -1
- package/docs/guides/streams/{node-readable-to-blob.md → node-readable-to-blob.mdx} +3 -1
- package/docs/guides/streams/{node-readable-to-json.md → node-readable-to-json.mdx} +3 -1
- package/docs/guides/streams/{node-readable-to-string.md → node-readable-to-string.mdx} +3 -1
- package/docs/guides/streams/{node-readable-to-uint8array.md → node-readable-to-uint8array.mdx} +3 -1
- package/docs/guides/streams/{to-array.md → to-array.mdx} +3 -1
- package/docs/guides/streams/{to-arraybuffer.md → to-arraybuffer.mdx} +3 -1
- package/docs/guides/streams/{to-blob.md → to-blob.mdx} +3 -1
- package/docs/guides/streams/{to-buffer.md → to-buffer.mdx} +3 -1
- package/docs/guides/streams/{to-json.md → to-json.mdx} +4 -2
- package/docs/guides/streams/{to-string.md → to-string.mdx} +3 -1
- package/docs/guides/streams/{to-typedarray.md → to-typedarray.mdx} +3 -1
- package/docs/guides/test/{bail.md → bail.mdx} +7 -5
- package/docs/guides/test/{coverage-threshold.md → coverage-threshold.mdx} +14 -7
- package/docs/guides/test/{coverage.md → coverage.mdx} +9 -4
- package/docs/guides/test/{happy-dom.md → happy-dom.mdx} +13 -8
- package/docs/guides/test/{migrate-from-jest.md → migrate-from-jest.mdx} +19 -37
- package/docs/guides/test/{mock-clock.md → mock-clock.mdx} +3 -1
- package/docs/guides/test/{mock-functions.md → mock-functions.mdx} +7 -5
- package/docs/guides/test/{rerun-each.md → rerun-each.mdx} +5 -3
- package/docs/guides/test/{run-tests.md → run-tests.mdx} +16 -11
- package/docs/guides/test/{skip-tests.md → skip-tests.mdx} +8 -4
- package/docs/guides/test/{snapshot.md → snapshot.mdx} +20 -13
- package/docs/guides/test/spy-on.mdx +49 -0
- package/docs/guides/test/{svelte-test.md → svelte-test.mdx} +16 -23
- package/docs/guides/test/{testing-library.md → testing-library.mdx} +18 -17
- package/docs/guides/test/{timeout.md → timeout.mdx} +5 -3
- package/docs/guides/test/{todo-tests.md → todo-tests.mdx} +13 -6
- package/docs/guides/test/{update-snapshots.md → update-snapshots.mdx} +9 -6
- package/docs/guides/test/{watch-mode.md → watch-mode.mdx} +9 -4
- package/docs/guides/util/{base64.md → base64.mdx} +3 -1
- package/docs/guides/util/{deep-equals.md → deep-equals.mdx} +5 -3
- package/docs/guides/util/{deflate.md → deflate.mdx} +3 -1
- package/docs/guides/util/{detect-bun.md → detect-bun.mdx} +3 -1
- package/docs/guides/util/{entrypoint.md → entrypoint.mdx} +4 -2
- package/docs/guides/util/{escape-html.md → escape-html.mdx} +3 -1
- package/docs/guides/util/{file-url-to-path.md → file-url-to-path.mdx} +3 -1
- package/docs/guides/util/{gzip.md → gzip.mdx} +3 -1
- package/docs/guides/util/{hash-a-password.md → hash-a-password.mdx} +3 -1
- package/docs/guides/util/{import-meta-dir.md → import-meta-dir.mdx} +4 -2
- package/docs/guides/util/{import-meta-file.md → import-meta-file.mdx} +4 -2
- package/docs/guides/util/{import-meta-path.md → import-meta-path.mdx} +4 -2
- package/docs/guides/util/{javascript-uuid.md → javascript-uuid.mdx} +3 -1
- package/docs/guides/util/{main.md → main.mdx} +19 -8
- package/docs/guides/util/{path-to-file-url.md → path-to-file-url.mdx} +3 -1
- package/docs/guides/util/{sleep.md → sleep.mdx} +3 -1
- package/docs/guides/util/{version.md → version.mdx} +6 -4
- package/docs/guides/util/{which-path-to-executable-bin.md → which-path-to-executable-bin.mdx} +4 -2
- package/docs/guides/websocket/{compression.md → compression.mdx} +5 -3
- package/docs/guides/websocket/{context.md → context.mdx} +9 -12
- package/docs/guides/websocket/{pubsub.md → pubsub.mdx} +5 -6
- package/docs/guides/websocket/{simple.md → simple.mdx} +5 -3
- package/docs/guides/write-file/{append.md → append.mdx} +3 -1
- package/docs/guides/write-file/{basic.md → basic.mdx} +3 -1
- package/docs/guides/write-file/{blob.md → blob.mdx} +3 -1
- package/docs/guides/write-file/{cat.md → cat.mdx} +4 -2
- package/docs/guides/write-file/{file-cp.md → file-cp.mdx} +3 -1
- package/docs/guides/write-file/{filesink.md → filesink.mdx} +3 -1
- package/docs/guides/write-file/{response.md → response.mdx} +3 -1
- package/docs/guides/write-file/{stdout.md → stdout.mdx} +3 -1
- package/docs/guides/write-file/{stream.md → stream.mdx} +3 -1
- package/docs/guides/write-file/{unlink.md → unlink.mdx} +3 -1
- package/docs/{index.md → index.mdx} +97 -41
- package/docs/installation.mdx +365 -0
- package/docs/{cli/bunx.md → pm/bunx.mdx} +25 -31
- package/docs/{install/catalogs.md → pm/catalogs.mdx} +18 -24
- package/docs/{cli/add.md → pm/cli/add.mdx} +61 -55
- package/docs/{install/audit.md → pm/cli/audit.mdx} +11 -8
- package/docs/{cli/install.md → pm/cli/install.mdx} +208 -81
- package/docs/{cli/link.md → pm/cli/link.mdx} +27 -19
- package/docs/{cli/outdated.md → pm/cli/outdated.mdx} +119 -12
- package/docs/{install/patch.md → pm/cli/patch.mdx} +25 -15
- package/docs/{cli/pm.md → pm/cli/pm.mdx} +96 -62
- package/docs/{cli/publish.md → pm/cli/publish.mdx} +38 -35
- package/docs/pm/cli/remove.mdx +16 -0
- package/docs/{cli/update.md → pm/cli/update.mdx} +26 -15
- package/docs/{cli/why.md → pm/cli/why.mdx} +27 -10
- package/docs/{cli/filter.md → pm/filter.mdx} +26 -14
- package/docs/{install/cache.md → pm/global-cache.mdx} +25 -12
- package/docs/{install/isolated.md → pm/isolated-installs.mdx} +32 -24
- package/docs/{install/lifecycle.md → pm/lifecycle.mdx} +20 -9
- package/docs/{install/lockfile.md → pm/lockfile.mdx} +18 -12
- package/docs/{install/npmrc.md → pm/npmrc.mdx} +30 -24
- package/docs/{install/overrides.md → pm/overrides.mdx} +47 -37
- package/docs/{install/registries.md → pm/scopes-registries.mdx} +8 -3
- package/docs/{install/security-scanner-api.md → pm/security-scanner-api.mdx} +22 -8
- package/docs/{install/workspaces.md → pm/workspaces.mdx} +17 -22
- package/docs/project/{benchmarking.md → benchmarking.mdx} +26 -11
- package/docs/project/{bindgen.md → bindgen.mdx} +12 -14
- package/docs/project/{building-windows.md → building-windows.mdx} +18 -47
- package/docs/project/{contributing.md → contributing.mdx} +56 -60
- package/docs/project/feedback.mdx +20 -0
- package/docs/project/license.mdx +78 -0
- package/docs/project/roadmap.mdx +8 -0
- package/docs/quickstart.mdx +240 -0
- package/docs/runtime/{autoimport.md → auto-install.mdx} +34 -31
- package/docs/{api/binary-data.md → runtime/binary-data.mdx} +77 -269
- package/docs/runtime/bun-apis.mdx +59 -0
- package/docs/runtime/{bunfig.md → bunfig.mdx} +95 -225
- package/docs/{api/cc.md → runtime/c-compiler.mdx} +16 -9
- package/docs/{api/spawn.md → runtime/child-process.mdx} +69 -119
- package/docs/{api/color.md → runtime/color.mdx} +6 -1
- package/docs/{api/console.md → runtime/console.mdx} +17 -7
- package/docs/{api/cookie.md → runtime/cookies.mdx} +24 -19
- package/docs/runtime/{debugger.md → debugger.mdx} +61 -51
- package/docs/runtime/environment-variables.mdx +214 -0
- package/docs/{api/ffi.md → runtime/ffi.mdx} +53 -45
- package/docs/{api/file-io.md → runtime/file-io.mdx} +41 -101
- package/docs/{api/file-system-router.md → runtime/file-system-router.mdx} +8 -2
- package/docs/{bundler/loaders.md → runtime/file-types.mdx} +56 -112
- package/docs/{api/glob.md → runtime/glob.mdx} +4 -1
- package/docs/runtime/globals.mdx +72 -0
- package/docs/{api/hashing.md → runtime/hashing.mdx} +18 -22
- package/docs/{api/html-rewriter.md → runtime/html-rewriter.mdx} +36 -30
- package/docs/runtime/http/cookies.mdx +79 -0
- package/docs/runtime/http/error-handling.mdx +40 -0
- package/docs/runtime/http/metrics.mdx +36 -0
- package/docs/runtime/http/routing.mdx +289 -0
- package/docs/runtime/http/server.mdx +647 -0
- package/docs/runtime/http/tls.mdx +101 -0
- package/docs/{api/websockets.md → runtime/http/websockets.mdx} +62 -231
- package/docs/{cli/run.md → runtime/index.mdx} +70 -108
- package/docs/runtime/jsx.mdx +115 -0
- package/docs/runtime/{modules.md → module-resolution.mdx} +83 -61
- package/docs/{api/dns.md → runtime/networking/dns.mdx} +23 -22
- package/docs/{api/fetch.md → runtime/networking/fetch.mdx} +10 -5
- package/docs/{api/tcp.md → runtime/networking/tcp.mdx} +59 -41
- package/docs/{api/udp.md → runtime/networking/udp.mdx} +14 -8
- package/docs/{api/node-api.md → runtime/node-api.mdx} +5 -0
- package/docs/runtime/{nodejs-apis.md → nodejs-compat.mdx} +9 -4
- package/docs/{bundler/plugins.md → runtime/plugins.mdx} +17 -61
- package/docs/{api/redis.md → runtime/redis.mdx} +65 -80
- package/docs/{api/s3.md → runtime/s3.mdx} +79 -66
- package/docs/{api/secrets.md → runtime/secrets.mdx} +27 -10
- package/docs/{api/semver.md → runtime/semver.mdx} +9 -4
- package/docs/runtime/{shell.md → shell.mdx} +52 -20
- package/docs/{api/sql.md → runtime/sql.mdx} +129 -99
- package/docs/{api/sqlite.md → runtime/sqlite.mdx} +162 -157
- package/docs/{api/streams.md → runtime/streams.mdx} +33 -31
- package/docs/{cli/bun-create.md → runtime/templating/create.mdx} +74 -143
- package/docs/{cli/init.md → runtime/templating/init.mdx} +24 -51
- package/docs/{api/transpiler.md → runtime/transpiler.mdx} +50 -38
- package/docs/{typescript.md → runtime/typescript.mdx} +7 -2
- package/docs/{api/utils.md → runtime/utils.mdx} +81 -50
- package/docs/runtime/{hot.md → watch-mode.mdx} +53 -37
- package/docs/runtime/web-apis.mdx +29 -0
- package/docs/{api/workers.md → runtime/workers.mdx} +28 -22
- package/docs/{api/yaml.md → runtime/yaml.mdx} +33 -232
- package/docs/snippets/cli/add.mdx +166 -0
- package/docs/snippets/cli/build.mdx +196 -0
- package/docs/snippets/cli/feedback.mdx +17 -0
- package/docs/snippets/cli/init.mdx +84 -0
- package/docs/snippets/cli/install.mdx +173 -0
- package/docs/snippets/cli/link.mdx +163 -0
- package/docs/snippets/cli/outdated.mdx +140 -0
- package/docs/snippets/cli/patch.mdx +171 -0
- package/docs/snippets/cli/publish.mdx +198 -0
- package/docs/snippets/cli/remove.mdx +146 -0
- package/docs/snippets/cli/run.mdx +293 -0
- package/docs/snippets/cli/test.mdx +100 -0
- package/docs/snippets/cli/update.mdx +144 -0
- package/docs/snippets/product-card.mdx +32 -0
- package/docs/snippets/product-tiles.mdx +94 -0
- package/docs/test/code-coverage.mdx +409 -0
- package/docs/test/configuration.mdx +467 -0
- package/docs/test/{time.md → dates-times.mdx} +23 -20
- package/docs/test/{discovery.md → discovery.mdx} +15 -10
- package/docs/test/dom.mdx +226 -0
- package/docs/{cli/test.md → test/index.mdx} +77 -94
- package/docs/test/lifecycle.mdx +348 -0
- package/docs/test/mocks.mdx +637 -0
- package/docs/test/{reporters.md → reporters.mdx} +15 -15
- package/docs/test/runtime-behavior.mdx +342 -0
- package/docs/test/snapshots.mdx +434 -0
- package/docs/test/writing-tests.mdx +635 -0
- package/docs/typescript.mdx +54 -0
- package/package.json +8 -6
- package/test.d.ts +2 -2
- package/docs/api/file.md +0 -19
- package/docs/api/globals.md +0 -387
- package/docs/api/http.md +0 -1408
- package/docs/api/import-meta.md +0 -69
- package/docs/benchmarks.md +0 -120
- package/docs/bun-flavored-toml.md +0 -42
- package/docs/bundler/css_modules.md +0 -145
- package/docs/bundler/fullstack.md +0 -418
- package/docs/bundler/index.md +0 -1735
- package/docs/bundler/intro.md +0 -75
- package/docs/bundler/vs-esbuild.md +0 -1127
- package/docs/cli/bun-completions.md +0 -3
- package/docs/cli/bun-install.md +0 -349
- package/docs/cli/bun-upgrade.md +0 -39
- package/docs/cli/info.md +0 -65
- package/docs/cli/patch-commit.md +0 -11
- package/docs/cli/remove.md +0 -7
- package/docs/cli/unlink.md +0 -9
- package/docs/contributing/upgrading-webkit.md +0 -57
- package/docs/ecosystem/elysia.md +0 -24
- package/docs/ecosystem/express.md +0 -37
- package/docs/ecosystem/hono.md +0 -18
- package/docs/ecosystem/react.md +0 -65
- package/docs/ecosystem/stric.md +0 -38
- package/docs/guides/ecosystem/prisma.md +0 -141
- package/docs/guides/ecosystem/render.md +0 -79
- package/docs/guides/install/add-git.md +0 -36
- package/docs/guides/test/spy-on.md +0 -46
- package/docs/install/index.md +0 -248
- package/docs/installation.md +0 -327
- package/docs/project/asan.md +0 -124
- package/docs/project/internals/build-process-for-ci.md +0 -75
- package/docs/project/licensing.md +0 -73
- package/docs/project/roadmap.md +0 -87
- package/docs/quickstart.md +0 -157
- package/docs/runtime/bun-apis.md +0 -207
- package/docs/runtime/env.md +0 -253
- package/docs/runtime/index.md +0 -312
- package/docs/runtime/jsx.md +0 -385
- package/docs/runtime/loaders.md +0 -130
- package/docs/runtime/plugins.md +0 -561
- package/docs/runtime/typescript.md +0 -139
- package/docs/runtime/web-apis.md +0 -128
- package/docs/test/configuration.md +0 -154
- package/docs/test/coverage.md +0 -142
- package/docs/test/dom.md +0 -75
- package/docs/test/examples/concurrent-test-glob.md +0 -132
- package/docs/test/hot.md +0 -15
- package/docs/test/lifecycle.md +0 -81
- package/docs/test/mocks.md +0 -313
- package/docs/test/runtime-behavior.md +0 -95
- package/docs/test/snapshots.md +0 -68
- package/docs/test/writing.md +0 -825
package/docs/api/http.md
DELETED
|
@@ -1,1408 +0,0 @@
|
|
|
1
|
-
The page primarily documents the Bun-native `Bun.serve` API. Bun also implements [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) and the Node.js [`http`](https://nodejs.org/api/http.html) and [`https`](https://nodejs.org/api/https.html) modules.
|
|
2
|
-
|
|
3
|
-
{% callout %}
|
|
4
|
-
These modules have been re-implemented to use Bun's fast internal HTTP infrastructure. Feel free to use these modules directly; frameworks like [Express](https://expressjs.com/) that depend on these modules should work out of the box. For granular compatibility information, see [Runtime > Node.js APIs](https://bun.com/docs/runtime/nodejs-apis).
|
|
5
|
-
{% /callout %}
|
|
6
|
-
|
|
7
|
-
To start a high-performance HTTP server with a clean API, the recommended approach is [`Bun.serve`](#start-a-server-bun-serve).
|
|
8
|
-
|
|
9
|
-
## `Bun.serve()`
|
|
10
|
-
|
|
11
|
-
Use `Bun.serve` to start an HTTP server in Bun.
|
|
12
|
-
|
|
13
|
-
```ts
|
|
14
|
-
Bun.serve({
|
|
15
|
-
// `routes` requires Bun v1.2.3+
|
|
16
|
-
routes: {
|
|
17
|
-
// Static routes
|
|
18
|
-
"/api/status": new Response("OK"),
|
|
19
|
-
|
|
20
|
-
// Dynamic routes
|
|
21
|
-
"/users/:id": req => {
|
|
22
|
-
return new Response(`Hello User ${req.params.id}!`);
|
|
23
|
-
},
|
|
24
|
-
|
|
25
|
-
// Per-HTTP method handlers
|
|
26
|
-
"/api/posts": {
|
|
27
|
-
GET: () => new Response("List posts"),
|
|
28
|
-
POST: async req => {
|
|
29
|
-
const body = await req.json();
|
|
30
|
-
return Response.json({ created: true, ...body });
|
|
31
|
-
},
|
|
32
|
-
},
|
|
33
|
-
|
|
34
|
-
// Wildcard route for all routes that start with "/api/" and aren't otherwise matched
|
|
35
|
-
"/api/*": Response.json({ message: "Not found" }, { status: 404 }),
|
|
36
|
-
|
|
37
|
-
// Redirect from /blog/hello to /blog/hello/world
|
|
38
|
-
"/blog/hello": Response.redirect("/blog/hello/world"),
|
|
39
|
-
|
|
40
|
-
// Serve a file by buffering it in memory
|
|
41
|
-
"/favicon.ico": new Response(await Bun.file("./favicon.ico").bytes(), {
|
|
42
|
-
headers: {
|
|
43
|
-
"Content-Type": "image/x-icon",
|
|
44
|
-
},
|
|
45
|
-
}),
|
|
46
|
-
},
|
|
47
|
-
|
|
48
|
-
// (optional) fallback for unmatched routes:
|
|
49
|
-
// Required if Bun's version < 1.2.3
|
|
50
|
-
fetch(req) {
|
|
51
|
-
return new Response("Not Found", { status: 404 });
|
|
52
|
-
},
|
|
53
|
-
});
|
|
54
|
-
```
|
|
55
|
-
|
|
56
|
-
### Routing
|
|
57
|
-
|
|
58
|
-
Routes in `Bun.serve()` receive a `BunRequest` (which extends [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request)) and return a [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) or `Promise<Response>`. This makes it easier to use the same code for both sending & receiving HTTP requests.
|
|
59
|
-
|
|
60
|
-
```ts
|
|
61
|
-
// Simplified for brevity
|
|
62
|
-
interface BunRequest<T extends string> extends Request {
|
|
63
|
-
params: Record<T, string>;
|
|
64
|
-
readonly cookies: CookieMap;
|
|
65
|
-
}
|
|
66
|
-
```
|
|
67
|
-
|
|
68
|
-
#### Async/await in routes
|
|
69
|
-
|
|
70
|
-
You can use async/await in route handlers to return a `Promise<Response>`.
|
|
71
|
-
|
|
72
|
-
```ts
|
|
73
|
-
import { sql, serve } from "bun";
|
|
74
|
-
|
|
75
|
-
serve({
|
|
76
|
-
port: 3001,
|
|
77
|
-
routes: {
|
|
78
|
-
"/api/version": async () => {
|
|
79
|
-
const [version] = await sql`SELECT version()`;
|
|
80
|
-
return Response.json(version);
|
|
81
|
-
},
|
|
82
|
-
},
|
|
83
|
-
});
|
|
84
|
-
```
|
|
85
|
-
|
|
86
|
-
#### Promise in routes
|
|
87
|
-
|
|
88
|
-
You can also return a `Promise<Response>` from a route handler.
|
|
89
|
-
|
|
90
|
-
```ts
|
|
91
|
-
import { sql, serve } from "bun";
|
|
92
|
-
|
|
93
|
-
serve({
|
|
94
|
-
routes: {
|
|
95
|
-
"/api/version": () => {
|
|
96
|
-
return new Promise(resolve => {
|
|
97
|
-
setTimeout(async () => {
|
|
98
|
-
const [version] = await sql`SELECT version()`;
|
|
99
|
-
resolve(Response.json(version));
|
|
100
|
-
}, 100);
|
|
101
|
-
});
|
|
102
|
-
},
|
|
103
|
-
},
|
|
104
|
-
});
|
|
105
|
-
```
|
|
106
|
-
|
|
107
|
-
#### Type-safe route parameters
|
|
108
|
-
|
|
109
|
-
TypeScript parses route parameters when passed as a string literal, so that your editor will show autocomplete when accessing `request.params`.
|
|
110
|
-
|
|
111
|
-
```ts
|
|
112
|
-
import type { BunRequest } from "bun";
|
|
113
|
-
|
|
114
|
-
Bun.serve({
|
|
115
|
-
routes: {
|
|
116
|
-
// TypeScript knows the shape of params when passed as a string literal
|
|
117
|
-
"/orgs/:orgId/repos/:repoId": req => {
|
|
118
|
-
const { orgId, repoId } = req.params;
|
|
119
|
-
return Response.json({ orgId, repoId });
|
|
120
|
-
},
|
|
121
|
-
|
|
122
|
-
"/orgs/:orgId/repos/:repoId/settings": (
|
|
123
|
-
// optional: you can explicitly pass a type to BunRequest:
|
|
124
|
-
req: BunRequest<"/orgs/:orgId/repos/:repoId/settings">,
|
|
125
|
-
) => {
|
|
126
|
-
const { orgId, repoId } = req.params;
|
|
127
|
-
return Response.json({ orgId, repoId });
|
|
128
|
-
},
|
|
129
|
-
},
|
|
130
|
-
});
|
|
131
|
-
```
|
|
132
|
-
|
|
133
|
-
Percent-encoded route parameter values are automatically decoded. Unicode characters are supported. Invalid unicode is replaced with the unicode replacement character `&0xFFFD;`.
|
|
134
|
-
|
|
135
|
-
### Static responses
|
|
136
|
-
|
|
137
|
-
Routes can also be `Response` objects (without the handler function). Bun.serve() optimizes it for zero-allocation dispatch - perfect for health checks, redirects, and fixed content:
|
|
138
|
-
|
|
139
|
-
```ts
|
|
140
|
-
Bun.serve({
|
|
141
|
-
routes: {
|
|
142
|
-
// Health checks
|
|
143
|
-
"/health": new Response("OK"),
|
|
144
|
-
"/ready": new Response("Ready", {
|
|
145
|
-
headers: {
|
|
146
|
-
// Pass custom headers
|
|
147
|
-
"X-Ready": "1",
|
|
148
|
-
},
|
|
149
|
-
}),
|
|
150
|
-
|
|
151
|
-
// Redirects
|
|
152
|
-
"/blog": Response.redirect("https://bun.com/blog"),
|
|
153
|
-
|
|
154
|
-
// API responses
|
|
155
|
-
"/api/config": Response.json({
|
|
156
|
-
version: "1.0.0",
|
|
157
|
-
env: "production",
|
|
158
|
-
}),
|
|
159
|
-
},
|
|
160
|
-
});
|
|
161
|
-
```
|
|
162
|
-
|
|
163
|
-
Static responses do not allocate additional memory after initialization. You can generally expect at least a 15% performance improvement over manually returning a `Response` object.
|
|
164
|
-
|
|
165
|
-
Static route responses are cached for the lifetime of the server object. To reload static routes, call `server.reload(options)`.
|
|
166
|
-
|
|
167
|
-
### File Responses vs Static Responses
|
|
168
|
-
|
|
169
|
-
When serving files in routes, there are two distinct behaviors depending on whether you buffer the file content or serve it directly:
|
|
170
|
-
|
|
171
|
-
```ts
|
|
172
|
-
Bun.serve({
|
|
173
|
-
routes: {
|
|
174
|
-
// Static route - content is buffered in memory at startup
|
|
175
|
-
"/logo.png": new Response(await Bun.file("./logo.png").bytes()),
|
|
176
|
-
|
|
177
|
-
// File route - content is read from filesystem on each request
|
|
178
|
-
"/download.zip": new Response(Bun.file("./download.zip")),
|
|
179
|
-
},
|
|
180
|
-
});
|
|
181
|
-
```
|
|
182
|
-
|
|
183
|
-
**Static routes** (`new Response(await file.bytes())`) buffer content in memory at startup:
|
|
184
|
-
|
|
185
|
-
- **Zero filesystem I/O** during requests - content served entirely from memory
|
|
186
|
-
- **ETag support** - Automatically generates and validates ETags for caching
|
|
187
|
-
- **If-None-Match** - Returns `304 Not Modified` when client ETag matches
|
|
188
|
-
- **No 404 handling** - Missing files cause startup errors, not runtime 404s
|
|
189
|
-
- **Memory usage** - Full file content stored in RAM
|
|
190
|
-
- **Best for**: Small static assets, API responses, frequently accessed files
|
|
191
|
-
|
|
192
|
-
**File routes** (`new Response(Bun.file(path))`) read from filesystem per request:
|
|
193
|
-
|
|
194
|
-
- **Filesystem reads** on each request - checks file existence and reads content
|
|
195
|
-
- **Built-in 404 handling** - Returns `404 Not Found` if file doesn't exist or becomes inaccessible
|
|
196
|
-
- **Last-Modified support** - Uses file modification time for `If-Modified-Since` headers
|
|
197
|
-
- **If-Modified-Since** - Returns `304 Not Modified` when file hasn't changed since client's cached version
|
|
198
|
-
- **Range request support** - Automatically handles partial content requests with `Content-Range` headers
|
|
199
|
-
- **Streaming transfers** - Uses buffered reader with backpressure handling for efficient memory usage
|
|
200
|
-
- **Memory efficient** - Only buffers small chunks during transfer, not entire file
|
|
201
|
-
- **Best for**: Large files, dynamic content, user uploads, files that change frequently
|
|
202
|
-
|
|
203
|
-
### HTTP Caching Behavior
|
|
204
|
-
|
|
205
|
-
Both route types implement HTTP caching standards but with different strategies:
|
|
206
|
-
|
|
207
|
-
#### Static Routes Caching
|
|
208
|
-
|
|
209
|
-
- **ETag generation**: Automatically computes ETag hash from content at startup
|
|
210
|
-
- **If-None-Match**: Validates client ETag against server ETag
|
|
211
|
-
- **304 responses**: Returns `304 Not Modified` with empty body when ETags match
|
|
212
|
-
- **Cache headers**: Inherits any `Cache-Control` headers you provide in the Response
|
|
213
|
-
- **Consistency**: ETag remains constant until server restart or route reload
|
|
214
|
-
|
|
215
|
-
#### File Routes Caching
|
|
216
|
-
|
|
217
|
-
- **Last-Modified**: Uses file's `mtime` for `Last-Modified` header
|
|
218
|
-
- **If-Modified-Since**: Compares client date with file modification time
|
|
219
|
-
- **304 responses**: Returns `304 Not Modified` when file unchanged since client's cached version
|
|
220
|
-
- **Content-Length**: Automatically set based on current file size
|
|
221
|
-
- **Dynamic validation**: Checks file modification time on each request
|
|
222
|
-
|
|
223
|
-
#### Status Code Handling
|
|
224
|
-
|
|
225
|
-
Both route types automatically adjust status codes:
|
|
226
|
-
|
|
227
|
-
- **200 → 204**: Empty files (0 bytes) return `204 No Content` instead of `200 OK`
|
|
228
|
-
- **200 → 304**: Successful cache validation returns `304 Not Modified`
|
|
229
|
-
- **File routes only**: Missing or inaccessible files return `404 Not Found`
|
|
230
|
-
|
|
231
|
-
```ts
|
|
232
|
-
const server = Bun.serve({
|
|
233
|
-
static: {
|
|
234
|
-
"/api/time": new Response(new Date().toISOString()),
|
|
235
|
-
},
|
|
236
|
-
|
|
237
|
-
fetch(req) {
|
|
238
|
-
return new Response("404!");
|
|
239
|
-
},
|
|
240
|
-
});
|
|
241
|
-
|
|
242
|
-
// Update the time every second.
|
|
243
|
-
setInterval(() => {
|
|
244
|
-
server.reload({
|
|
245
|
-
static: {
|
|
246
|
-
"/api/time": new Response(new Date().toISOString()),
|
|
247
|
-
},
|
|
248
|
-
|
|
249
|
-
fetch(req) {
|
|
250
|
-
return new Response("404!");
|
|
251
|
-
},
|
|
252
|
-
});
|
|
253
|
-
}, 1000);
|
|
254
|
-
```
|
|
255
|
-
|
|
256
|
-
Reloading routes only impact the next request. In-flight requests continue to use the old routes. After in-flight requests to old routes are finished, the old routes are freed from memory.
|
|
257
|
-
|
|
258
|
-
To simplify error handling, static routes do not support streaming response bodies from `ReadableStream` or an `AsyncIterator`. Fortunately, you can still buffer the response in memory first:
|
|
259
|
-
|
|
260
|
-
```ts
|
|
261
|
-
const time = await fetch("https://api.example.com/v1/data");
|
|
262
|
-
// Buffer the response in memory first.
|
|
263
|
-
const blob = await time.blob();
|
|
264
|
-
|
|
265
|
-
const server = Bun.serve({
|
|
266
|
-
static: {
|
|
267
|
-
"/api/data": new Response(blob),
|
|
268
|
-
},
|
|
269
|
-
|
|
270
|
-
fetch(req) {
|
|
271
|
-
return new Response("404!");
|
|
272
|
-
},
|
|
273
|
-
});
|
|
274
|
-
```
|
|
275
|
-
|
|
276
|
-
### Route precedence
|
|
277
|
-
|
|
278
|
-
Routes are matched in order of specificity:
|
|
279
|
-
|
|
280
|
-
1. Exact routes (`/users/all`)
|
|
281
|
-
2. Parameter routes (`/users/:id`)
|
|
282
|
-
3. Wildcard routes (`/users/*`)
|
|
283
|
-
4. Global catch-all (`/*`)
|
|
284
|
-
|
|
285
|
-
```ts
|
|
286
|
-
Bun.serve({
|
|
287
|
-
routes: {
|
|
288
|
-
// Most specific first
|
|
289
|
-
"/api/users/me": () => new Response("Current user"),
|
|
290
|
-
"/api/users/:id": req => new Response(`User ${req.params.id}`),
|
|
291
|
-
"/api/*": () => new Response("API catch-all"),
|
|
292
|
-
"/*": () => new Response("Global catch-all"),
|
|
293
|
-
},
|
|
294
|
-
});
|
|
295
|
-
```
|
|
296
|
-
|
|
297
|
-
### Per-HTTP Method Routes
|
|
298
|
-
|
|
299
|
-
Route handlers can be specialized by HTTP method:
|
|
300
|
-
|
|
301
|
-
```ts
|
|
302
|
-
Bun.serve({
|
|
303
|
-
routes: {
|
|
304
|
-
"/api/posts": {
|
|
305
|
-
// Different handlers per method
|
|
306
|
-
GET: () => new Response("List posts"),
|
|
307
|
-
POST: async req => {
|
|
308
|
-
const post = await req.json();
|
|
309
|
-
return Response.json({ id: crypto.randomUUID(), ...post });
|
|
310
|
-
},
|
|
311
|
-
PUT: async req => {
|
|
312
|
-
const updates = await req.json();
|
|
313
|
-
return Response.json({ updated: true, ...updates });
|
|
314
|
-
},
|
|
315
|
-
DELETE: () => new Response(null, { status: 204 }),
|
|
316
|
-
},
|
|
317
|
-
},
|
|
318
|
-
});
|
|
319
|
-
```
|
|
320
|
-
|
|
321
|
-
You can pass any of the following methods:
|
|
322
|
-
|
|
323
|
-
| Method | Usecase example |
|
|
324
|
-
| --------- | ------------------------------- |
|
|
325
|
-
| `GET` | Fetch a resource |
|
|
326
|
-
| `HEAD` | Check if a resource exists |
|
|
327
|
-
| `OPTIONS` | Get allowed HTTP methods (CORS) |
|
|
328
|
-
| `DELETE` | Delete a resource |
|
|
329
|
-
| `PATCH` | Update a resource |
|
|
330
|
-
| `POST` | Create a resource |
|
|
331
|
-
| `PUT` | Update a resource |
|
|
332
|
-
|
|
333
|
-
When passing a function instead of an object, all methods will be handled by that function:
|
|
334
|
-
|
|
335
|
-
```ts
|
|
336
|
-
const server = Bun.serve({
|
|
337
|
-
routes: {
|
|
338
|
-
"/api/version": () => Response.json({ version: "1.0.0" }),
|
|
339
|
-
},
|
|
340
|
-
});
|
|
341
|
-
|
|
342
|
-
await fetch(new URL("/api/version", server.url));
|
|
343
|
-
await fetch(new URL("/api/version", server.url), { method: "PUT" });
|
|
344
|
-
// ... etc
|
|
345
|
-
```
|
|
346
|
-
|
|
347
|
-
### Hot Route Reloading
|
|
348
|
-
|
|
349
|
-
Update routes without server restarts using `server.reload()`:
|
|
350
|
-
|
|
351
|
-
```ts
|
|
352
|
-
const server = Bun.serve({
|
|
353
|
-
routes: {
|
|
354
|
-
"/api/version": () => Response.json({ version: "1.0.0" }),
|
|
355
|
-
},
|
|
356
|
-
});
|
|
357
|
-
|
|
358
|
-
// Deploy new routes without downtime
|
|
359
|
-
server.reload({
|
|
360
|
-
routes: {
|
|
361
|
-
"/api/version": () => Response.json({ version: "2.0.0" }),
|
|
362
|
-
},
|
|
363
|
-
});
|
|
364
|
-
```
|
|
365
|
-
|
|
366
|
-
### Error Handling
|
|
367
|
-
|
|
368
|
-
Bun provides structured error handling for routes:
|
|
369
|
-
|
|
370
|
-
```ts
|
|
371
|
-
Bun.serve({
|
|
372
|
-
routes: {
|
|
373
|
-
// Errors are caught automatically
|
|
374
|
-
"/api/risky": () => {
|
|
375
|
-
throw new Error("Something went wrong");
|
|
376
|
-
},
|
|
377
|
-
},
|
|
378
|
-
// Global error handler
|
|
379
|
-
error(error) {
|
|
380
|
-
console.error(error);
|
|
381
|
-
return new Response(`Internal Error: ${error.message}`, {
|
|
382
|
-
status: 500,
|
|
383
|
-
headers: {
|
|
384
|
-
"Content-Type": "text/plain",
|
|
385
|
-
},
|
|
386
|
-
});
|
|
387
|
-
},
|
|
388
|
-
});
|
|
389
|
-
```
|
|
390
|
-
|
|
391
|
-
### HTML imports
|
|
392
|
-
|
|
393
|
-
Bun supports importing HTML files directly into your server code, enabling full-stack applications with both server-side and client-side code. HTML imports work in two modes:
|
|
394
|
-
|
|
395
|
-
**Development (`bun --hot`):** Assets are bundled on-demand at runtime, enabling hot module replacement (HMR) for a fast, iterative development experience. When you change your frontend code, the browser automatically updates without a full page reload.
|
|
396
|
-
|
|
397
|
-
**Production (`bun build`):** When building with `bun build --target=bun`, the `import index from "./index.html"` statement resolves to a pre-built manifest object containing all bundled client assets. `Bun.serve` consumes this manifest to serve optimized assets with zero runtime bundling overhead. This is ideal for deploying to production.
|
|
398
|
-
|
|
399
|
-
```ts
|
|
400
|
-
import myReactSinglePageApp from "./index.html";
|
|
401
|
-
|
|
402
|
-
Bun.serve({
|
|
403
|
-
routes: {
|
|
404
|
-
"/": myReactSinglePageApp,
|
|
405
|
-
},
|
|
406
|
-
});
|
|
407
|
-
```
|
|
408
|
-
|
|
409
|
-
HTML imports don't just serve HTML — it's a full-featured frontend bundler, transpiler, and toolkit built using Bun's [bundler](https://bun.com/docs/bundler), JavaScript transpiler and CSS parser. You can use this to build full-featured frontends with React, TypeScript, Tailwind CSS, and more.
|
|
410
|
-
|
|
411
|
-
For a complete guide on building full-stack applications with HTML imports, including detailed examples and best practices, see [/docs/bundler/fullstack](https://bun.com/docs/bundler/fullstack).
|
|
412
|
-
|
|
413
|
-
### Practical example: REST API
|
|
414
|
-
|
|
415
|
-
Here's a basic database-backed REST API using Bun's router with zero dependencies:
|
|
416
|
-
|
|
417
|
-
{% codetabs %}
|
|
418
|
-
|
|
419
|
-
```ts#server.ts
|
|
420
|
-
import type { Post } from "./types.ts";
|
|
421
|
-
import { Database } from "bun:sqlite";
|
|
422
|
-
|
|
423
|
-
const db = new Database("posts.db");
|
|
424
|
-
db.exec(`
|
|
425
|
-
CREATE TABLE IF NOT EXISTS posts (
|
|
426
|
-
id TEXT PRIMARY KEY,
|
|
427
|
-
title TEXT NOT NULL,
|
|
428
|
-
content TEXT NOT NULL,
|
|
429
|
-
created_at TEXT NOT NULL
|
|
430
|
-
)
|
|
431
|
-
`);
|
|
432
|
-
|
|
433
|
-
Bun.serve({
|
|
434
|
-
routes: {
|
|
435
|
-
// List posts
|
|
436
|
-
"/api/posts": {
|
|
437
|
-
GET: () => {
|
|
438
|
-
const posts = db.query("SELECT * FROM posts").all();
|
|
439
|
-
return Response.json(posts);
|
|
440
|
-
},
|
|
441
|
-
|
|
442
|
-
// Create post
|
|
443
|
-
POST: async req => {
|
|
444
|
-
const post: Omit<Post, "id" | "created_at"> = await req.json();
|
|
445
|
-
const id = crypto.randomUUID();
|
|
446
|
-
|
|
447
|
-
db.query(
|
|
448
|
-
`INSERT INTO posts (id, title, content, created_at)
|
|
449
|
-
VALUES (?, ?, ?, ?)`,
|
|
450
|
-
).run(id, post.title, post.content, new Date().toISOString());
|
|
451
|
-
|
|
452
|
-
return Response.json({ id, ...post }, { status: 201 });
|
|
453
|
-
},
|
|
454
|
-
},
|
|
455
|
-
|
|
456
|
-
// Get post by ID
|
|
457
|
-
"/api/posts/:id": req => {
|
|
458
|
-
const post = db
|
|
459
|
-
.query("SELECT * FROM posts WHERE id = ?")
|
|
460
|
-
.get(req.params.id);
|
|
461
|
-
|
|
462
|
-
if (!post) {
|
|
463
|
-
return new Response("Not Found", { status: 404 });
|
|
464
|
-
}
|
|
465
|
-
|
|
466
|
-
return Response.json(post);
|
|
467
|
-
},
|
|
468
|
-
},
|
|
469
|
-
|
|
470
|
-
error(error) {
|
|
471
|
-
console.error(error);
|
|
472
|
-
return new Response("Internal Server Error", { status: 500 });
|
|
473
|
-
},
|
|
474
|
-
});
|
|
475
|
-
```
|
|
476
|
-
|
|
477
|
-
```ts#types.ts
|
|
478
|
-
export interface Post {
|
|
479
|
-
id: string;
|
|
480
|
-
title: string;
|
|
481
|
-
content: string;
|
|
482
|
-
created_at: string;
|
|
483
|
-
}
|
|
484
|
-
```
|
|
485
|
-
|
|
486
|
-
{% /codetabs %}
|
|
487
|
-
|
|
488
|
-
### Routing performance
|
|
489
|
-
|
|
490
|
-
`Bun.serve()`'s router builds on top uWebSocket's [tree-based approach](https://github.com/oven-sh/bun/blob/0d1a00fa0f7830f8ecd99c027fce8096c9d459b6/packages/bun-uws/src/HttpRouter.h#L57-L64) to add [SIMD-accelerated route parameter decoding](https://github.com/oven-sh/bun/blob/main/src/bun.js/bindings/decodeURIComponentSIMD.cpp#L21-L271) and [JavaScriptCore structure caching](https://github.com/oven-sh/bun/blob/main/src/bun.js/bindings/ServerRouteList.cpp#L100-L101) to push the performance limits of what modern hardware allows.
|
|
491
|
-
|
|
492
|
-
### `fetch` request handler
|
|
493
|
-
|
|
494
|
-
The `fetch` handler handles incoming requests that weren't matched by any route. It receives a [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) object and returns a [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) or [`Promise<Response>`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
|
|
495
|
-
|
|
496
|
-
```ts
|
|
497
|
-
Bun.serve({
|
|
498
|
-
fetch(req) {
|
|
499
|
-
const url = new URL(req.url);
|
|
500
|
-
if (url.pathname === "/") return new Response("Home page!");
|
|
501
|
-
if (url.pathname === "/blog") return new Response("Blog!");
|
|
502
|
-
return new Response("404!");
|
|
503
|
-
},
|
|
504
|
-
});
|
|
505
|
-
```
|
|
506
|
-
|
|
507
|
-
The `fetch` handler supports async/await:
|
|
508
|
-
|
|
509
|
-
```ts
|
|
510
|
-
import { sleep, serve } from "bun";
|
|
511
|
-
serve({
|
|
512
|
-
async fetch(req) {
|
|
513
|
-
const start = performance.now();
|
|
514
|
-
await sleep(10);
|
|
515
|
-
const end = performance.now();
|
|
516
|
-
return new Response(`Slept for ${end - start}ms`);
|
|
517
|
-
},
|
|
518
|
-
});
|
|
519
|
-
```
|
|
520
|
-
|
|
521
|
-
Promise-based responses are also supported:
|
|
522
|
-
|
|
523
|
-
```ts
|
|
524
|
-
Bun.serve({
|
|
525
|
-
fetch(req) {
|
|
526
|
-
// Forward the request to another server.
|
|
527
|
-
return fetch("https://example.com");
|
|
528
|
-
},
|
|
529
|
-
});
|
|
530
|
-
```
|
|
531
|
-
|
|
532
|
-
You can also access the `Server` object from the `fetch` handler. It's the second argument passed to the `fetch` function.
|
|
533
|
-
|
|
534
|
-
```ts
|
|
535
|
-
// `server` is passed in as the second argument to `fetch`.
|
|
536
|
-
const server = Bun.serve({
|
|
537
|
-
fetch(req, server) {
|
|
538
|
-
const ip = server.requestIP(req);
|
|
539
|
-
return new Response(`Your IP is ${ip.address}`);
|
|
540
|
-
},
|
|
541
|
-
});
|
|
542
|
-
```
|
|
543
|
-
|
|
544
|
-
### Changing the `port` and `hostname`
|
|
545
|
-
|
|
546
|
-
To configure which port and hostname the server will listen on, set `port` and `hostname` in the options object.
|
|
547
|
-
|
|
548
|
-
```ts
|
|
549
|
-
Bun.serve({
|
|
550
|
-
port: 8080, // defaults to $BUN_PORT, $PORT, $NODE_PORT otherwise 3000
|
|
551
|
-
hostname: "mydomain.com", // defaults to "0.0.0.0"
|
|
552
|
-
fetch(req) {
|
|
553
|
-
return new Response("404!");
|
|
554
|
-
},
|
|
555
|
-
});
|
|
556
|
-
```
|
|
557
|
-
|
|
558
|
-
To randomly select an available port, set `port` to `0`.
|
|
559
|
-
|
|
560
|
-
```ts
|
|
561
|
-
const server = Bun.serve({
|
|
562
|
-
port: 0, // random port
|
|
563
|
-
fetch(req) {
|
|
564
|
-
return new Response("404!");
|
|
565
|
-
},
|
|
566
|
-
});
|
|
567
|
-
|
|
568
|
-
// server.port is the randomly selected port
|
|
569
|
-
console.log(server.port);
|
|
570
|
-
```
|
|
571
|
-
|
|
572
|
-
You can view the chosen port by accessing the `port` property on the server object, or by accessing the `url` property.
|
|
573
|
-
|
|
574
|
-
```ts
|
|
575
|
-
console.log(server.port); // 3000
|
|
576
|
-
console.log(server.url); // http://localhost:3000
|
|
577
|
-
```
|
|
578
|
-
|
|
579
|
-
#### Configuring a default port
|
|
580
|
-
|
|
581
|
-
Bun supports several options and environment variables to configure the default port. The default port is used when the `port` option is not set.
|
|
582
|
-
|
|
583
|
-
- `--port` CLI flag
|
|
584
|
-
|
|
585
|
-
```sh
|
|
586
|
-
$ bun --port=4002 server.ts
|
|
587
|
-
```
|
|
588
|
-
|
|
589
|
-
- `BUN_PORT` environment variable
|
|
590
|
-
|
|
591
|
-
```sh
|
|
592
|
-
$ BUN_PORT=4002 bun server.ts
|
|
593
|
-
```
|
|
594
|
-
|
|
595
|
-
- `PORT` environment variable
|
|
596
|
-
|
|
597
|
-
```sh
|
|
598
|
-
$ PORT=4002 bun server.ts
|
|
599
|
-
```
|
|
600
|
-
|
|
601
|
-
- `NODE_PORT` environment variable
|
|
602
|
-
|
|
603
|
-
```sh
|
|
604
|
-
$ NODE_PORT=4002 bun server.ts
|
|
605
|
-
```
|
|
606
|
-
|
|
607
|
-
### Unix domain sockets
|
|
608
|
-
|
|
609
|
-
To listen on a [unix domain socket](https://en.wikipedia.org/wiki/Unix_domain_socket), pass the `unix` option with the path to the socket.
|
|
610
|
-
|
|
611
|
-
```ts
|
|
612
|
-
Bun.serve({
|
|
613
|
-
unix: "/tmp/my-socket.sock", // path to socket
|
|
614
|
-
fetch(req) {
|
|
615
|
-
return new Response(`404!`);
|
|
616
|
-
},
|
|
617
|
-
});
|
|
618
|
-
```
|
|
619
|
-
|
|
620
|
-
### Abstract namespace sockets
|
|
621
|
-
|
|
622
|
-
Bun supports Linux abstract namespace sockets. To use an abstract namespace socket, prefix the `unix` path with a null byte.
|
|
623
|
-
|
|
624
|
-
```ts
|
|
625
|
-
Bun.serve({
|
|
626
|
-
unix: "\0my-abstract-socket", // abstract namespace socket
|
|
627
|
-
fetch(req) {
|
|
628
|
-
return new Response(`404!`);
|
|
629
|
-
},
|
|
630
|
-
});
|
|
631
|
-
```
|
|
632
|
-
|
|
633
|
-
Unlike unix domain sockets, abstract namespace sockets are not bound to the filesystem and are automatically removed when the last reference to the socket is closed.
|
|
634
|
-
|
|
635
|
-
## Error handling
|
|
636
|
-
|
|
637
|
-
To activate development mode, set `development: true`.
|
|
638
|
-
|
|
639
|
-
```ts
|
|
640
|
-
Bun.serve({
|
|
641
|
-
development: true,
|
|
642
|
-
fetch(req) {
|
|
643
|
-
throw new Error("woops!");
|
|
644
|
-
},
|
|
645
|
-
});
|
|
646
|
-
```
|
|
647
|
-
|
|
648
|
-
In development mode, Bun will surface errors in-browser with a built-in error page.
|
|
649
|
-
|
|
650
|
-
{% image src="/images/exception_page.png" caption="Bun's built-in 500 page" /%}
|
|
651
|
-
|
|
652
|
-
### `error` callback
|
|
653
|
-
|
|
654
|
-
To handle server-side errors, implement an `error` handler. This function should return a `Response` to serve to the client when an error occurs. This response will supersede Bun's default error page in `development` mode.
|
|
655
|
-
|
|
656
|
-
```ts
|
|
657
|
-
Bun.serve({
|
|
658
|
-
fetch(req) {
|
|
659
|
-
throw new Error("woops!");
|
|
660
|
-
},
|
|
661
|
-
error(error) {
|
|
662
|
-
return new Response(`<pre>${error}\n${error.stack}</pre>`, {
|
|
663
|
-
headers: {
|
|
664
|
-
"Content-Type": "text/html",
|
|
665
|
-
},
|
|
666
|
-
});
|
|
667
|
-
},
|
|
668
|
-
});
|
|
669
|
-
```
|
|
670
|
-
|
|
671
|
-
{% callout %}
|
|
672
|
-
[Learn more about debugging in Bun](https://bun.com/docs/runtime/debugger)
|
|
673
|
-
{% /callout %}
|
|
674
|
-
|
|
675
|
-
The call to `Bun.serve` returns a `Server` object. To stop the server, call the `.stop()` method.
|
|
676
|
-
|
|
677
|
-
```ts
|
|
678
|
-
const server = Bun.serve({
|
|
679
|
-
fetch() {
|
|
680
|
-
return new Response("Bun!");
|
|
681
|
-
},
|
|
682
|
-
});
|
|
683
|
-
|
|
684
|
-
server.stop();
|
|
685
|
-
```
|
|
686
|
-
|
|
687
|
-
## TLS
|
|
688
|
-
|
|
689
|
-
Bun supports TLS out of the box, powered by [BoringSSL](https://boringssl.googlesource.com/boringssl). Enable TLS by passing in a value for `key` and `cert`; both are required to enable TLS.
|
|
690
|
-
|
|
691
|
-
```ts-diff
|
|
692
|
-
Bun.serve({
|
|
693
|
-
fetch(req) {
|
|
694
|
-
return new Response("Hello!!!");
|
|
695
|
-
},
|
|
696
|
-
|
|
697
|
-
+ tls: {
|
|
698
|
-
+ key: Bun.file("./key.pem"),
|
|
699
|
-
+ cert: Bun.file("./cert.pem"),
|
|
700
|
-
+ }
|
|
701
|
-
});
|
|
702
|
-
```
|
|
703
|
-
|
|
704
|
-
The `key` and `cert` fields expect the _contents_ of your TLS key and certificate, _not a path to it_. This can be a string, `BunFile`, `TypedArray`, or `Buffer`.
|
|
705
|
-
|
|
706
|
-
```ts
|
|
707
|
-
Bun.serve({
|
|
708
|
-
fetch() {},
|
|
709
|
-
|
|
710
|
-
tls: {
|
|
711
|
-
// BunFile
|
|
712
|
-
key: Bun.file("./key.pem"),
|
|
713
|
-
// Buffer
|
|
714
|
-
key: fs.readFileSync("./key.pem"),
|
|
715
|
-
// string
|
|
716
|
-
key: fs.readFileSync("./key.pem", "utf8"),
|
|
717
|
-
// array of above
|
|
718
|
-
key: [Bun.file("./key1.pem"), Bun.file("./key2.pem")],
|
|
719
|
-
},
|
|
720
|
-
});
|
|
721
|
-
```
|
|
722
|
-
|
|
723
|
-
If your private key is encrypted with a passphrase, provide a value for `passphrase` to decrypt it.
|
|
724
|
-
|
|
725
|
-
```ts-diff
|
|
726
|
-
Bun.serve({
|
|
727
|
-
fetch(req) {
|
|
728
|
-
return new Response("Hello!!!");
|
|
729
|
-
},
|
|
730
|
-
|
|
731
|
-
tls: {
|
|
732
|
-
key: Bun.file("./key.pem"),
|
|
733
|
-
cert: Bun.file("./cert.pem"),
|
|
734
|
-
+ passphrase: "my-secret-passphrase",
|
|
735
|
-
}
|
|
736
|
-
});
|
|
737
|
-
```
|
|
738
|
-
|
|
739
|
-
Optionally, you can override the trusted CA certificates by passing a value for `ca`. By default, the server will trust the list of well-known CAs curated by Mozilla. When `ca` is specified, the Mozilla list is overwritten.
|
|
740
|
-
|
|
741
|
-
```ts-diff
|
|
742
|
-
Bun.serve({
|
|
743
|
-
fetch(req) {
|
|
744
|
-
return new Response("Hello!!!");
|
|
745
|
-
},
|
|
746
|
-
tls: {
|
|
747
|
-
key: Bun.file("./key.pem"), // path to TLS key
|
|
748
|
-
cert: Bun.file("./cert.pem"), // path to TLS cert
|
|
749
|
-
+ ca: Bun.file("./ca.pem"), // path to root CA certificate
|
|
750
|
-
}
|
|
751
|
-
});
|
|
752
|
-
```
|
|
753
|
-
|
|
754
|
-
To override Diffie-Hellman parameters:
|
|
755
|
-
|
|
756
|
-
```ts
|
|
757
|
-
Bun.serve({
|
|
758
|
-
// ...
|
|
759
|
-
tls: {
|
|
760
|
-
// other config
|
|
761
|
-
dhParamsFile: "/path/to/dhparams.pem", // path to Diffie Hellman parameters
|
|
762
|
-
},
|
|
763
|
-
});
|
|
764
|
-
```
|
|
765
|
-
|
|
766
|
-
### Server name indication (SNI)
|
|
767
|
-
|
|
768
|
-
To configure the server name indication (SNI) for the server, set the `serverName` field in the `tls` object.
|
|
769
|
-
|
|
770
|
-
```ts
|
|
771
|
-
Bun.serve({
|
|
772
|
-
// ...
|
|
773
|
-
tls: {
|
|
774
|
-
// ... other config
|
|
775
|
-
serverName: "my-server.com", // SNI
|
|
776
|
-
},
|
|
777
|
-
});
|
|
778
|
-
```
|
|
779
|
-
|
|
780
|
-
To allow multiple server names, pass an array of objects to `tls`, each with a `serverName` field.
|
|
781
|
-
|
|
782
|
-
```ts
|
|
783
|
-
Bun.serve({
|
|
784
|
-
// ...
|
|
785
|
-
tls: [
|
|
786
|
-
{
|
|
787
|
-
key: Bun.file("./key1.pem"),
|
|
788
|
-
cert: Bun.file("./cert1.pem"),
|
|
789
|
-
serverName: "my-server1.com",
|
|
790
|
-
},
|
|
791
|
-
{
|
|
792
|
-
key: Bun.file("./key2.pem"),
|
|
793
|
-
cert: Bun.file("./cert2.pem"),
|
|
794
|
-
serverName: "my-server2.com",
|
|
795
|
-
},
|
|
796
|
-
],
|
|
797
|
-
});
|
|
798
|
-
```
|
|
799
|
-
|
|
800
|
-
## idleTimeout
|
|
801
|
-
|
|
802
|
-
To configure the idle timeout, set the `idleTimeout` field in Bun.serve.
|
|
803
|
-
|
|
804
|
-
```ts
|
|
805
|
-
Bun.serve({
|
|
806
|
-
// 10 seconds:
|
|
807
|
-
idleTimeout: 10,
|
|
808
|
-
|
|
809
|
-
fetch(req) {
|
|
810
|
-
return new Response("Bun!");
|
|
811
|
-
},
|
|
812
|
-
});
|
|
813
|
-
```
|
|
814
|
-
|
|
815
|
-
This is the maximum amount of time a connection is allowed to be idle before the server closes it. A connection is idling if there is no data sent or received.
|
|
816
|
-
|
|
817
|
-
## export default syntax
|
|
818
|
-
|
|
819
|
-
Thus far, the examples on this page have used the explicit `Bun.serve` API. Bun also supports an alternate syntax.
|
|
820
|
-
|
|
821
|
-
```ts#server.ts
|
|
822
|
-
import {type Serve} from "bun";
|
|
823
|
-
|
|
824
|
-
export default {
|
|
825
|
-
fetch(req) {
|
|
826
|
-
return new Response("Bun!");
|
|
827
|
-
},
|
|
828
|
-
} satisfies Serve;
|
|
829
|
-
```
|
|
830
|
-
|
|
831
|
-
Instead of passing the server options into `Bun.serve`, `export default` it. This file can be executed as-is; when Bun sees a file with a `default` export containing a `fetch` handler, it passes it into `Bun.serve` under the hood.
|
|
832
|
-
|
|
833
|
-
<!-- This syntax has one major advantage: it is hot-reloadable out of the box. When any source file is changed, Bun will reload the server with the updated code _without restarting the process_. This makes hot reloads nearly instantaneous. Use the `--hot` flag when starting the server to enable hot reloading. -->
|
|
834
|
-
|
|
835
|
-
<!-- ```bash
|
|
836
|
-
$ bun --hot server.ts
|
|
837
|
-
``` -->
|
|
838
|
-
|
|
839
|
-
<!-- It's possible to configure hot reloading while using the explicit `Bun.serve` API; for details refer to [Runtime > Hot reloading](https://bun.com/docs/runtime/hot). -->
|
|
840
|
-
|
|
841
|
-
## Streaming files
|
|
842
|
-
|
|
843
|
-
To stream a file, return a `Response` object with a `BunFile` object as the body.
|
|
844
|
-
|
|
845
|
-
```ts
|
|
846
|
-
Bun.serve({
|
|
847
|
-
fetch(req) {
|
|
848
|
-
return new Response(Bun.file("./hello.txt"));
|
|
849
|
-
},
|
|
850
|
-
});
|
|
851
|
-
```
|
|
852
|
-
|
|
853
|
-
{% callout %}
|
|
854
|
-
⚡️ **Speed** — Bun automatically uses the [`sendfile(2)`](https://man7.org/linux/man-pages/man2/sendfile.2.html) system call when possible, enabling zero-copy file transfers in the kernel—the fastest way to send files.
|
|
855
|
-
{% /callout %}
|
|
856
|
-
|
|
857
|
-
You can send part of a file using the [`slice(start, end)`](https://developer.mozilla.org/en-US/docs/Web/API/Blob/slice) method on the `Bun.file` object. This automatically sets the `Content-Range` and `Content-Length` headers on the `Response` object.
|
|
858
|
-
|
|
859
|
-
```ts
|
|
860
|
-
Bun.serve({
|
|
861
|
-
fetch(req) {
|
|
862
|
-
// parse `Range` header
|
|
863
|
-
const [start = 0, end = Infinity] = req.headers
|
|
864
|
-
.get("Range") // Range: bytes=0-100
|
|
865
|
-
.split("=") // ["Range: bytes", "0-100"]
|
|
866
|
-
.at(-1) // "0-100"
|
|
867
|
-
.split("-") // ["0", "100"]
|
|
868
|
-
.map(Number); // [0, 100]
|
|
869
|
-
|
|
870
|
-
// return a slice of the file
|
|
871
|
-
const bigFile = Bun.file("./big-video.mp4");
|
|
872
|
-
return new Response(bigFile.slice(start, end));
|
|
873
|
-
},
|
|
874
|
-
});
|
|
875
|
-
```
|
|
876
|
-
|
|
877
|
-
## Server Lifecycle Methods
|
|
878
|
-
|
|
879
|
-
### server.stop() - Stop the server
|
|
880
|
-
|
|
881
|
-
To stop the server from accepting new connections:
|
|
882
|
-
|
|
883
|
-
```ts
|
|
884
|
-
const server = Bun.serve({
|
|
885
|
-
fetch(req) {
|
|
886
|
-
return new Response("Hello!");
|
|
887
|
-
},
|
|
888
|
-
});
|
|
889
|
-
|
|
890
|
-
// Gracefully stop the server (waits for in-flight requests)
|
|
891
|
-
await server.stop();
|
|
892
|
-
|
|
893
|
-
// Force stop and close all active connections
|
|
894
|
-
await server.stop(true);
|
|
895
|
-
```
|
|
896
|
-
|
|
897
|
-
By default, `stop()` allows in-flight requests and WebSocket connections to complete. Pass `true` to immediately terminate all connections.
|
|
898
|
-
|
|
899
|
-
### server.ref() and server.unref() - Process lifecycle control
|
|
900
|
-
|
|
901
|
-
Control whether the server keeps the Bun process alive:
|
|
902
|
-
|
|
903
|
-
```ts
|
|
904
|
-
// Don't keep process alive if server is the only thing running
|
|
905
|
-
server.unref();
|
|
906
|
-
|
|
907
|
-
// Restore default behavior - keep process alive
|
|
908
|
-
server.ref();
|
|
909
|
-
```
|
|
910
|
-
|
|
911
|
-
### server.reload() - Hot reload handlers
|
|
912
|
-
|
|
913
|
-
Update the server's handlers without restarting:
|
|
914
|
-
|
|
915
|
-
```ts
|
|
916
|
-
const server = Bun.serve({
|
|
917
|
-
routes: {
|
|
918
|
-
"/api/version": Response.json({ version: "v1" }),
|
|
919
|
-
},
|
|
920
|
-
fetch(req) {
|
|
921
|
-
return new Response("v1");
|
|
922
|
-
},
|
|
923
|
-
});
|
|
924
|
-
|
|
925
|
-
// Update to new handler
|
|
926
|
-
server.reload({
|
|
927
|
-
routes: {
|
|
928
|
-
"/api/version": Response.json({ version: "v2" }),
|
|
929
|
-
},
|
|
930
|
-
fetch(req) {
|
|
931
|
-
return new Response("v2");
|
|
932
|
-
},
|
|
933
|
-
});
|
|
934
|
-
```
|
|
935
|
-
|
|
936
|
-
This is useful for development and hot reloading. Only `fetch`, `error`, and `routes` can be updated.
|
|
937
|
-
|
|
938
|
-
## Per-Request Controls
|
|
939
|
-
|
|
940
|
-
<!-- ### server.abort(Request) - Abort requests
|
|
941
|
-
|
|
942
|
-
The `server.abort(request: Request)` method:
|
|
943
|
-
|
|
944
|
-
- Returns `true` if request was aborted, `false` if already aborted/completed
|
|
945
|
-
- Triggers the request's `AbortSignal`
|
|
946
|
-
- Cancels any attached `ReadableStream`
|
|
947
|
-
- Rejects any pending body promises (like `.text()`)
|
|
948
|
-
|
|
949
|
-
```ts
|
|
950
|
-
const server = Bun.serve({
|
|
951
|
-
fetch(req, server) {
|
|
952
|
-
// abort if the url contains "slow"
|
|
953
|
-
if (req.url.includes("slow")) {
|
|
954
|
-
server.abort(req);
|
|
955
|
-
|
|
956
|
-
// When aborted, the server will not error due to the lack of a `Response` object
|
|
957
|
-
// If you return a `Response` anyway, it will be ignored.
|
|
958
|
-
return;
|
|
959
|
-
}
|
|
960
|
-
|
|
961
|
-
return new Response("Processing...");
|
|
962
|
-
},
|
|
963
|
-
});
|
|
964
|
-
``` -->
|
|
965
|
-
|
|
966
|
-
### server.timeout(Request, seconds) - Custom request timeouts
|
|
967
|
-
|
|
968
|
-
Set a custom idle timeout for individual requests:
|
|
969
|
-
|
|
970
|
-
```ts
|
|
971
|
-
const server = Bun.serve({
|
|
972
|
-
fetch(req, server) {
|
|
973
|
-
// Set 60 second timeout for this request
|
|
974
|
-
server.timeout(req, 60);
|
|
975
|
-
|
|
976
|
-
// If they take longer than 60 seconds to send the body, the request will be aborted
|
|
977
|
-
await req.text();
|
|
978
|
-
|
|
979
|
-
return new Response("Done!");
|
|
980
|
-
},
|
|
981
|
-
});
|
|
982
|
-
```
|
|
983
|
-
|
|
984
|
-
Pass `0` to disable the timeout for a request.
|
|
985
|
-
|
|
986
|
-
### server.requestIP(Request) - Get client information
|
|
987
|
-
|
|
988
|
-
Get client IP and port information:
|
|
989
|
-
|
|
990
|
-
```ts
|
|
991
|
-
const server = Bun.serve({
|
|
992
|
-
fetch(req, server) {
|
|
993
|
-
const address = server.requestIP(req);
|
|
994
|
-
if (address) {
|
|
995
|
-
return new Response(
|
|
996
|
-
`Client IP: ${address.address}, Port: ${address.port}`,
|
|
997
|
-
);
|
|
998
|
-
}
|
|
999
|
-
return new Response("Unknown client");
|
|
1000
|
-
},
|
|
1001
|
-
});
|
|
1002
|
-
```
|
|
1003
|
-
|
|
1004
|
-
Returns `null` for closed requests or Unix domain sockets.
|
|
1005
|
-
|
|
1006
|
-
## Working with Cookies
|
|
1007
|
-
|
|
1008
|
-
Bun provides a built-in API for working with cookies in HTTP requests and responses. The `BunRequest` object includes a `cookies` property that provides a `CookieMap` for easily accessing and manipulating cookies. When using `routes`, `Bun.serve()` automatically tracks `request.cookies.set` and applies them to the response.
|
|
1009
|
-
|
|
1010
|
-
### Reading cookies
|
|
1011
|
-
|
|
1012
|
-
Read cookies from incoming requests using the `cookies` property on the `BunRequest` object:
|
|
1013
|
-
|
|
1014
|
-
```ts
|
|
1015
|
-
Bun.serve({
|
|
1016
|
-
routes: {
|
|
1017
|
-
"/profile": req => {
|
|
1018
|
-
// Access cookies from the request
|
|
1019
|
-
const userId = req.cookies.get("user_id");
|
|
1020
|
-
const theme = req.cookies.get("theme") || "light";
|
|
1021
|
-
|
|
1022
|
-
return Response.json({
|
|
1023
|
-
userId,
|
|
1024
|
-
theme,
|
|
1025
|
-
message: "Profile page",
|
|
1026
|
-
});
|
|
1027
|
-
},
|
|
1028
|
-
},
|
|
1029
|
-
});
|
|
1030
|
-
```
|
|
1031
|
-
|
|
1032
|
-
### Setting cookies
|
|
1033
|
-
|
|
1034
|
-
To set cookies, use the `set` method on the `CookieMap` from the `BunRequest` object.
|
|
1035
|
-
|
|
1036
|
-
```ts
|
|
1037
|
-
Bun.serve({
|
|
1038
|
-
routes: {
|
|
1039
|
-
"/login": req => {
|
|
1040
|
-
const cookies = req.cookies;
|
|
1041
|
-
|
|
1042
|
-
// Set a cookie with various options
|
|
1043
|
-
cookies.set("user_id", "12345", {
|
|
1044
|
-
maxAge: 60 * 60 * 24 * 7, // 1 week
|
|
1045
|
-
httpOnly: true,
|
|
1046
|
-
secure: true,
|
|
1047
|
-
path: "/",
|
|
1048
|
-
});
|
|
1049
|
-
|
|
1050
|
-
// Add a theme preference cookie
|
|
1051
|
-
cookies.set("theme", "dark");
|
|
1052
|
-
|
|
1053
|
-
// Modified cookies from the request are automatically applied to the response
|
|
1054
|
-
return new Response("Login successful");
|
|
1055
|
-
},
|
|
1056
|
-
},
|
|
1057
|
-
});
|
|
1058
|
-
```
|
|
1059
|
-
|
|
1060
|
-
`Bun.serve()` automatically tracks modified cookies from the request and applies them to the response.
|
|
1061
|
-
|
|
1062
|
-
### Deleting cookies
|
|
1063
|
-
|
|
1064
|
-
To delete a cookie, use the `delete` method on the `request.cookies` (`CookieMap`) object:
|
|
1065
|
-
|
|
1066
|
-
```ts
|
|
1067
|
-
Bun.serve({
|
|
1068
|
-
routes: {
|
|
1069
|
-
"/logout": req => {
|
|
1070
|
-
// Delete the user_id cookie
|
|
1071
|
-
req.cookies.delete("user_id", {
|
|
1072
|
-
path: "/",
|
|
1073
|
-
});
|
|
1074
|
-
|
|
1075
|
-
return new Response("Logged out successfully");
|
|
1076
|
-
},
|
|
1077
|
-
},
|
|
1078
|
-
});
|
|
1079
|
-
```
|
|
1080
|
-
|
|
1081
|
-
Deleted cookies become a `Set-Cookie` header on the response with the `maxAge` set to `0` and an empty `value`.
|
|
1082
|
-
|
|
1083
|
-
## Server Metrics
|
|
1084
|
-
|
|
1085
|
-
### server.pendingRequests and server.pendingWebSockets
|
|
1086
|
-
|
|
1087
|
-
Monitor server activity with built-in counters:
|
|
1088
|
-
|
|
1089
|
-
```ts
|
|
1090
|
-
const server = Bun.serve({
|
|
1091
|
-
fetch(req, server) {
|
|
1092
|
-
return new Response(
|
|
1093
|
-
`Active requests: ${server.pendingRequests}\n` +
|
|
1094
|
-
`Active WebSockets: ${server.pendingWebSockets}`,
|
|
1095
|
-
);
|
|
1096
|
-
},
|
|
1097
|
-
});
|
|
1098
|
-
```
|
|
1099
|
-
|
|
1100
|
-
### server.subscriberCount(topic) - WebSocket subscribers
|
|
1101
|
-
|
|
1102
|
-
Get count of subscribers for a WebSocket topic:
|
|
1103
|
-
|
|
1104
|
-
```ts
|
|
1105
|
-
const server = Bun.serve({
|
|
1106
|
-
fetch(req, server) {
|
|
1107
|
-
const chatUsers = server.subscriberCount("chat");
|
|
1108
|
-
return new Response(`${chatUsers} users in chat`);
|
|
1109
|
-
},
|
|
1110
|
-
websocket: {
|
|
1111
|
-
message(ws) {
|
|
1112
|
-
ws.subscribe("chat");
|
|
1113
|
-
},
|
|
1114
|
-
},
|
|
1115
|
-
});
|
|
1116
|
-
```
|
|
1117
|
-
|
|
1118
|
-
## WebSocket Configuration
|
|
1119
|
-
|
|
1120
|
-
### server.publish(topic, data, compress) - WebSocket Message Publishing
|
|
1121
|
-
|
|
1122
|
-
The server can publish messages to all WebSocket clients subscribed to a topic:
|
|
1123
|
-
|
|
1124
|
-
```ts
|
|
1125
|
-
const server = Bun.serve({
|
|
1126
|
-
websocket: {
|
|
1127
|
-
message(ws) {
|
|
1128
|
-
// Publish to all "chat" subscribers
|
|
1129
|
-
server.publish("chat", "Hello everyone!");
|
|
1130
|
-
},
|
|
1131
|
-
},
|
|
1132
|
-
|
|
1133
|
-
fetch(req) {
|
|
1134
|
-
// ...
|
|
1135
|
-
},
|
|
1136
|
-
});
|
|
1137
|
-
```
|
|
1138
|
-
|
|
1139
|
-
The `publish()` method returns:
|
|
1140
|
-
|
|
1141
|
-
- Number of bytes sent if successful
|
|
1142
|
-
- `0` if the message was dropped
|
|
1143
|
-
- `-1` if backpressure was applied
|
|
1144
|
-
|
|
1145
|
-
### WebSocket Handler Options
|
|
1146
|
-
|
|
1147
|
-
When configuring WebSockets, several advanced options are available through the `websocket` handler:
|
|
1148
|
-
|
|
1149
|
-
```ts
|
|
1150
|
-
Bun.serve({
|
|
1151
|
-
websocket: {
|
|
1152
|
-
// Maximum message size (in bytes)
|
|
1153
|
-
maxPayloadLength: 64 * 1024,
|
|
1154
|
-
|
|
1155
|
-
// Backpressure limit before messages are dropped
|
|
1156
|
-
backpressureLimit: 1024 * 1024,
|
|
1157
|
-
|
|
1158
|
-
// Close connection if backpressure limit is hit
|
|
1159
|
-
closeOnBackpressureLimit: true,
|
|
1160
|
-
|
|
1161
|
-
// Handler called when backpressure is relieved
|
|
1162
|
-
drain(ws) {
|
|
1163
|
-
console.log("Backpressure relieved");
|
|
1164
|
-
},
|
|
1165
|
-
|
|
1166
|
-
// Enable per-message deflate compression
|
|
1167
|
-
perMessageDeflate: {
|
|
1168
|
-
compress: true,
|
|
1169
|
-
decompress: true,
|
|
1170
|
-
},
|
|
1171
|
-
|
|
1172
|
-
// Send ping frames to keep connection alive
|
|
1173
|
-
sendPings: true,
|
|
1174
|
-
|
|
1175
|
-
// Handlers for ping/pong frames
|
|
1176
|
-
ping(ws, data) {
|
|
1177
|
-
console.log("Received ping");
|
|
1178
|
-
},
|
|
1179
|
-
pong(ws, data) {
|
|
1180
|
-
console.log("Received pong");
|
|
1181
|
-
},
|
|
1182
|
-
|
|
1183
|
-
// Whether server receives its own published messages
|
|
1184
|
-
publishToSelf: false,
|
|
1185
|
-
},
|
|
1186
|
-
});
|
|
1187
|
-
```
|
|
1188
|
-
|
|
1189
|
-
## Benchmarks
|
|
1190
|
-
|
|
1191
|
-
Below are Bun and Node.js implementations of a simple HTTP server that responds `Bun!` to each incoming `Request`.
|
|
1192
|
-
|
|
1193
|
-
{% codetabs %}
|
|
1194
|
-
|
|
1195
|
-
```ts#Bun
|
|
1196
|
-
Bun.serve({
|
|
1197
|
-
fetch(req: Request) {
|
|
1198
|
-
return new Response("Bun!");
|
|
1199
|
-
},
|
|
1200
|
-
port: 3000,
|
|
1201
|
-
});
|
|
1202
|
-
```
|
|
1203
|
-
|
|
1204
|
-
```ts#Node
|
|
1205
|
-
require("http")
|
|
1206
|
-
.createServer((req, res) => res.end("Bun!"))
|
|
1207
|
-
.listen(8080);
|
|
1208
|
-
```
|
|
1209
|
-
|
|
1210
|
-
{% /codetabs %}
|
|
1211
|
-
The `Bun.serve` server can handle roughly 2.5x more requests per second than Node.js on Linux.
|
|
1212
|
-
|
|
1213
|
-
{% table %}
|
|
1214
|
-
|
|
1215
|
-
- Runtime
|
|
1216
|
-
- Requests per second
|
|
1217
|
-
|
|
1218
|
-
---
|
|
1219
|
-
|
|
1220
|
-
- Node 16
|
|
1221
|
-
- ~64,000
|
|
1222
|
-
|
|
1223
|
-
---
|
|
1224
|
-
|
|
1225
|
-
- Bun
|
|
1226
|
-
- ~160,000
|
|
1227
|
-
|
|
1228
|
-
{% /table %}
|
|
1229
|
-
|
|
1230
|
-
{% image width="499" alt="image" src="https://user-images.githubusercontent.com/709451/162389032-fc302444-9d03-46be-ba87-c12bd8ce89a0.png" /%}
|
|
1231
|
-
|
|
1232
|
-
## Reference
|
|
1233
|
-
|
|
1234
|
-
{% details summary="See TypeScript definitions" %}
|
|
1235
|
-
|
|
1236
|
-
```ts
|
|
1237
|
-
interface Server extends Disposable {
|
|
1238
|
-
/**
|
|
1239
|
-
* Stop the server from accepting new connections.
|
|
1240
|
-
* @param closeActiveConnections If true, immediately terminates all connections
|
|
1241
|
-
* @returns Promise that resolves when the server has stopped
|
|
1242
|
-
*/
|
|
1243
|
-
stop(closeActiveConnections?: boolean): Promise<void>;
|
|
1244
|
-
|
|
1245
|
-
/**
|
|
1246
|
-
* Update handlers without restarting the server.
|
|
1247
|
-
* Only fetch and error handlers can be updated.
|
|
1248
|
-
*/
|
|
1249
|
-
reload(options: Serve): void;
|
|
1250
|
-
|
|
1251
|
-
/**
|
|
1252
|
-
* Make a request to the running server.
|
|
1253
|
-
* Useful for testing or internal routing.
|
|
1254
|
-
*/
|
|
1255
|
-
fetch(request: Request | string): Response | Promise<Response>;
|
|
1256
|
-
|
|
1257
|
-
/**
|
|
1258
|
-
* Upgrade an HTTP request to a WebSocket connection.
|
|
1259
|
-
* @returns true if upgrade successful, false if failed
|
|
1260
|
-
*/
|
|
1261
|
-
upgrade<T = undefined>(
|
|
1262
|
-
request: Request,
|
|
1263
|
-
options?: {
|
|
1264
|
-
headers?: Bun.HeadersInit;
|
|
1265
|
-
data?: T;
|
|
1266
|
-
},
|
|
1267
|
-
): boolean;
|
|
1268
|
-
|
|
1269
|
-
/**
|
|
1270
|
-
* Publish a message to all WebSocket clients subscribed to a topic.
|
|
1271
|
-
* @returns Bytes sent, 0 if dropped, -1 if backpressure applied
|
|
1272
|
-
*/
|
|
1273
|
-
publish(
|
|
1274
|
-
topic: string,
|
|
1275
|
-
data: string | ArrayBufferView | ArrayBuffer | SharedArrayBuffer,
|
|
1276
|
-
compress?: boolean,
|
|
1277
|
-
): ServerWebSocketSendStatus;
|
|
1278
|
-
|
|
1279
|
-
/**
|
|
1280
|
-
* Get count of WebSocket clients subscribed to a topic.
|
|
1281
|
-
*/
|
|
1282
|
-
subscriberCount(topic: string): number;
|
|
1283
|
-
|
|
1284
|
-
/**
|
|
1285
|
-
* Get client IP address and port.
|
|
1286
|
-
* @returns null for closed requests or Unix sockets
|
|
1287
|
-
*/
|
|
1288
|
-
requestIP(request: Request): SocketAddress | null;
|
|
1289
|
-
|
|
1290
|
-
/**
|
|
1291
|
-
* Set custom idle timeout for a request.
|
|
1292
|
-
* @param seconds Timeout in seconds, 0 to disable
|
|
1293
|
-
*/
|
|
1294
|
-
timeout(request: Request, seconds: number): void;
|
|
1295
|
-
|
|
1296
|
-
/**
|
|
1297
|
-
* Keep process alive while server is running.
|
|
1298
|
-
*/
|
|
1299
|
-
ref(): void;
|
|
1300
|
-
|
|
1301
|
-
/**
|
|
1302
|
-
* Allow process to exit if server is only thing running.
|
|
1303
|
-
*/
|
|
1304
|
-
unref(): void;
|
|
1305
|
-
|
|
1306
|
-
/** Number of in-flight HTTP requests */
|
|
1307
|
-
readonly pendingRequests: number;
|
|
1308
|
-
|
|
1309
|
-
/** Number of active WebSocket connections */
|
|
1310
|
-
readonly pendingWebSockets: number;
|
|
1311
|
-
|
|
1312
|
-
/** Server URL including protocol, hostname and port */
|
|
1313
|
-
readonly url: URL;
|
|
1314
|
-
|
|
1315
|
-
/** Port server is listening on */
|
|
1316
|
-
readonly port: number;
|
|
1317
|
-
|
|
1318
|
-
/** Hostname server is bound to */
|
|
1319
|
-
readonly hostname: string;
|
|
1320
|
-
|
|
1321
|
-
/** Whether server is in development mode */
|
|
1322
|
-
readonly development: boolean;
|
|
1323
|
-
|
|
1324
|
-
/** Server instance identifier */
|
|
1325
|
-
readonly id: string;
|
|
1326
|
-
}
|
|
1327
|
-
|
|
1328
|
-
interface WebSocketHandler<T = undefined> {
|
|
1329
|
-
/** Maximum WebSocket message size in bytes */
|
|
1330
|
-
maxPayloadLength?: number;
|
|
1331
|
-
|
|
1332
|
-
/** Bytes of queued messages before applying backpressure */
|
|
1333
|
-
backpressureLimit?: number;
|
|
1334
|
-
|
|
1335
|
-
/** Whether to close connection when backpressure limit hit */
|
|
1336
|
-
closeOnBackpressureLimit?: boolean;
|
|
1337
|
-
|
|
1338
|
-
/** Called when backpressure is relieved */
|
|
1339
|
-
drain?(ws: ServerWebSocket<T>): void | Promise<void>;
|
|
1340
|
-
|
|
1341
|
-
/** Seconds before idle timeout */
|
|
1342
|
-
idleTimeout?: number;
|
|
1343
|
-
|
|
1344
|
-
/** Enable per-message deflate compression */
|
|
1345
|
-
perMessageDeflate?:
|
|
1346
|
-
| boolean
|
|
1347
|
-
| {
|
|
1348
|
-
compress?: WebSocketCompressor | boolean;
|
|
1349
|
-
decompress?: WebSocketCompressor | boolean;
|
|
1350
|
-
};
|
|
1351
|
-
|
|
1352
|
-
/** Send ping frames to keep connection alive */
|
|
1353
|
-
sendPings?: boolean;
|
|
1354
|
-
|
|
1355
|
-
/** Whether server receives its own published messages */
|
|
1356
|
-
publishToSelf?: boolean;
|
|
1357
|
-
|
|
1358
|
-
/** Called when connection opened */
|
|
1359
|
-
open?(ws: ServerWebSocket<T>): void | Promise<void>;
|
|
1360
|
-
|
|
1361
|
-
/** Called when message received */
|
|
1362
|
-
message(
|
|
1363
|
-
ws: ServerWebSocket<T>,
|
|
1364
|
-
message: string | Buffer,
|
|
1365
|
-
): void | Promise<void>;
|
|
1366
|
-
|
|
1367
|
-
/** Called when connection closed */
|
|
1368
|
-
close?(
|
|
1369
|
-
ws: ServerWebSocket<T>,
|
|
1370
|
-
code: number,
|
|
1371
|
-
reason: string,
|
|
1372
|
-
): void | Promise<void>;
|
|
1373
|
-
|
|
1374
|
-
/** Called when ping frame received */
|
|
1375
|
-
ping?(ws: ServerWebSocket<T>, data: Buffer): void | Promise<void>;
|
|
1376
|
-
|
|
1377
|
-
/** Called when pong frame received */
|
|
1378
|
-
pong?(ws: ServerWebSocket<T>, data: Buffer): void | Promise<void>;
|
|
1379
|
-
}
|
|
1380
|
-
|
|
1381
|
-
interface TLSOptions {
|
|
1382
|
-
/** Certificate authority chain */
|
|
1383
|
-
ca?: string | Buffer | BunFile | Array<string | Buffer | BunFile>;
|
|
1384
|
-
|
|
1385
|
-
/** Server certificate */
|
|
1386
|
-
cert?: string | Buffer | BunFile | Array<string | Buffer | BunFile>;
|
|
1387
|
-
|
|
1388
|
-
/** Path to DH parameters file */
|
|
1389
|
-
dhParamsFile?: string;
|
|
1390
|
-
|
|
1391
|
-
/** Private key */
|
|
1392
|
-
key?: string | Buffer | BunFile | Array<string | Buffer | BunFile>;
|
|
1393
|
-
|
|
1394
|
-
/** Reduce TLS memory usage */
|
|
1395
|
-
lowMemoryMode?: boolean;
|
|
1396
|
-
|
|
1397
|
-
/** Private key passphrase */
|
|
1398
|
-
passphrase?: string;
|
|
1399
|
-
|
|
1400
|
-
/** OpenSSL options flags */
|
|
1401
|
-
secureOptions?: number;
|
|
1402
|
-
|
|
1403
|
-
/** Server name for SNI */
|
|
1404
|
-
serverName?: string;
|
|
1405
|
-
}
|
|
1406
|
-
```
|
|
1407
|
-
|
|
1408
|
-
{% /details %}
|