# What is Bun? Source: https://bun.sh/docs/index.md Bun is an all-in-one toolkit for JavaScript and TypeScript apps. It ships as a single executable called `bun`. At its core is the _Bun runtime_, a fast JavaScript runtime designed as **a drop-in replacement for Node.js**. It's written in Zig and powered by JavaScriptCore under the hood, dramatically reducing startup times and memory usage. ```bash $ bun run index.tsx # TS and JSX supported out of the box ``` The `bun` command-line tool also implements a test runner, script runner, and Node.js-compatible package manager, all significantly faster than existing tools and usable in existing Node.js projects with little to no changes necessary. ```bash $ bun run start # run the `start` script $ bun install # install a package $ bun build ./index.tsx # bundle a project for browsers $ bun test # run tests $ bunx cowsay 'Hello, world!' # execute a package ``` Get started with one of the quick links below, or read on to learn more about Bun. {% block className="gap-2 grid grid-flow-row grid-cols-1 md:grid-cols-2" %} {% arrowbutton href="/docs/installation" text="Install Bun" /%} {% arrowbutton href="/docs/quickstart" text="Do the quickstart" /%} {% arrowbutton href="/docs/cli/install" text="Install a package" /%} {% arrowbutton href="/docs/cli/bun-create" text="Use a project template" /%} {% arrowbutton href="/docs/bundler" text="Bundle code for production" /%} {% arrowbutton href="/docs/api/http" text="Build an HTTP server" /%} {% arrowbutton href="/docs/api/websockets" text="Build a Websocket server" /%} {% arrowbutton href="/docs/api/file-io" text="Read and write files" /%} {% arrowbutton href="/docs/api/sqlite" text="Run SQLite queries" /%} {% arrowbutton href="/docs/cli/test" text="Write and run tests" /%} {% /block %} ## What is a runtime? JavaScript (or, more formally, ECMAScript) is just a _specification_ for a programming language. Anyone can write a JavaScript _engine_ that ingests a valid JavaScript program and executes it. The two most popular engines in use today are V8 (developed by Google) and JavaScriptCore (developed by Apple). Both are open source. But most JavaScript programs don't run in a vacuum. They need a way to access the outside world to perform useful tasks. This is where _runtimes_ come in. They implement additional APIs that are then made available to the JavaScript programs they execute. ### Browsers Notably, browsers ship with JavaScript runtimes that implement a set of Web-specific APIs that are exposed via the global `window` object. Any JavaScript code executed by the browser can use these APIs to implement interactive or dynamic behavior in the context of the current webpage. ### Node.js Similarly, Node.js is a JavaScript runtime that can be used in non-browser environments, like servers. JavaScript programs executed by Node.js have access to a set of Node.js-specific [globals](https://nodejs.org/api/globals.html) like `Buffer`, `process`, and `__dirname` in addition to built-in modules for performing OS-level tasks like reading/writing files (`node:fs`) and networking (`node:net`, `node:http`). Node.js also implements a CommonJS-based module system and resolution algorithm that pre-dates JavaScript's native module system. Bun is designed as a faster, leaner, more modern replacement for Node.js. ## Design goals Bun is designed from the ground-up with today's JavaScript ecosystem in mind. - **Speed**. Bun processes start [4x faster than Node.js](https://twitter.com/jarredsumner/status/1499225725492076544) currently (try it yourself!) - **TypeScript & JSX support**. You can directly execute `.jsx`, `.ts`, and `.tsx` files; Bun's transpiler converts these to vanilla JavaScript before execution. - **ESM & CommonJS compatibility**. The world is moving towards ES modules (ESM), but millions of packages on npm still require CommonJS. Bun recommends ES modules, but supports CommonJS. - **Web-standard APIs**. Bun implements standard Web APIs like `fetch`, `WebSocket`, and `ReadableStream`. Bun is powered by the JavaScriptCore engine, which is developed by Apple for Safari, so some APIs like [`Headers`](https://developer.mozilla.org/en-US/docs/Web/API/Headers) and [`URL`](https://developer.mozilla.org/en-US/docs/Web/API/URL) directly use [Safari's implementation](https://github.com/oven-sh/bun/blob/HEAD/src/bun.js/bindings/webcore/JSFetchHeaders.cpp). - **Node.js compatibility**. In addition to supporting Node-style module resolution, Bun aims for full compatibility with built-in Node.js globals (`process`, `Buffer`) and modules (`path`, `fs`, `http`, etc.) _This is an ongoing effort that is not complete._ Refer to the [compatibility page](https://bun.sh/docs/runtime/nodejs-apis) for the current status. Bun is more than a runtime. The long-term goal is to be a cohesive, infrastructural toolkit for building apps with JavaScript/TypeScript, including a package manager, transpiler, bundler, script runner, test runner, and more. # Installation Source: https://bun.sh/docs/installation.md Bun ships as a single executable with no dependencies that can be installed a few different ways. ## Installing ### macOS and Linux {% callout %} **Linux users** — The `unzip` package is required to install Bun. Use `sudo apt install unzip` to install `unzip` package. Kernel version 5.6 or higher is strongly recommended, but the minimum is 5.1. Use `uname -r` to check Kernel version. {% /callout %} {% codetabs %} ```bash#macOS/Linux_(curl) $ curl -fsSL https://bun.sh/install | bash # for macOS, Linux, and WSL # to install a specific version $ curl -fsSL https://bun.sh/install | bash -s "bun-v$BUN_LATEST_VERSION" ``` ```bash#npm $ npm install -g bun # the last `npm` command you'll ever need ``` ```bash#Homebrew $ brew install oven-sh/bun/bun # for macOS and Linux ``` ```bash#Docker $ docker pull oven/bun $ docker run --rm --init --ulimit memlock=-1:-1 oven/bun ``` {% /codetabs %} ### Windows To install, paste this into a terminal: {% codetabs %} ```powershell#PowerShell/cmd.exe > powershell -c "irm bun.sh/install.ps1|iex" ``` ```powershell#npm > npm install -g bun # the last `npm` command you'll ever need ``` ```powershell#Scoop > scoop install bun ``` {% /codetabs %} {% callout %} Bun requires a minimum of Windows 10 version 1809 {% /callout %} For support and discussion, please join the [#windows channel on our Discord](http://bun.sh/discord). ## Docker Bun provides a [Docker image](https://hub.docker.com/r/oven/bun/tags) that supports both Linux x64 and arm64. ```bash $ docker pull oven/bun $ docker run --rm --init --ulimit memlock=-1:-1 oven/bun ``` There are also image variants for different operating systems. ```bash $ docker pull oven/bun:debian $ docker pull oven/bun:slim $ docker pull oven/bun:distroless $ docker pull oven/bun:alpine ``` ## Checking installation To check that Bun was installed successfully, open a new terminal window and run `bun --version`. ```sh $ bun --version 1.x.y ``` To see the precise commit of [oven-sh/bun](https://github.com/oven-sh/bun) that you're using, run `bun --revision`. ```sh $ bun --revision 1.x.y+b7982ac13189 ``` If you've installed Bun but are seeing a `command not found` error, you may have to manually add the installation directory (`~/.bun/bin`) to your `PATH`. ### How to add your `PATH` {% details summary="Linux / Mac" %} First, determine what shell you're using: ```sh $ echo $SHELL /bin/zsh # or /bin/bash or /bin/fish ``` Then add these lines below to bottom of your shell's configuration file. {% codetabs %} ```bash#~/.zshrc # add to ~/.zshrc export BUN_INSTALL="$HOME/.bun" export PATH="$BUN_INSTALL/bin:$PATH" ``` ```bash#~/.bashrc # add to ~/.bashrc export BUN_INSTALL="$HOME/.bun" export PATH="$BUN_INSTALL/bin:$PATH" ``` ```sh#~/.config/fish/config.fish # add to ~/.config/fish/config.fish export BUN_INSTALL="$HOME/.bun" export PATH="$BUN_INSTALL/bin:$PATH" ``` {% /codetabs %} Save the file. You'll need to open a new shell/terminal window for the changes to take effect. {% /details %} {% details summary="Windows" %} First, determine if the bun binary is properly installed on your system: ```pwsh & "$env:USERPROFILE\.bun\bin\bun" --version ``` If the command runs successfully but `bun --version` is not recognized, it means that bun is not in your system's `PATH`. To fix this, open a Powershell terminal and run the following command: ```pwsh [System.Environment]::SetEnvironmentVariable( "Path", [System.Environment]::GetEnvironmentVariable("Path", "User") + ";$env:USERPROFILE\.bun\bin", [System.EnvironmentVariableTarget]::User ) ``` After running the command, restart your terminal and test with `bun --version` {% /details %} ## Upgrading Once installed, the binary can upgrade itself. ```sh $ bun upgrade ``` {% callout %} **Homebrew users** — To avoid conflicts with Homebrew, use `brew upgrade bun` instead. **Scoop users** — To avoid conflicts with Scoop, use `scoop update bun` instead. {% /callout %} ## Canary builds Bun automatically releases an (untested) canary build on every commit to `main`. To upgrade to the latest canary build: ```sh $ bun upgrade --canary ``` The canary build is useful for testing new features and bug fixes before they're released in a stable build. To help the Bun team fix bugs faster, canary builds automatically upload crash reports to Bun's team. [View canary build](https://github.com/oven-sh/bun/releases/tag/canary) {% callout %} **Note** — To switch back to a stable release from canary, run `bun upgrade --stable`. {% /callout %} ## Installing older versions of Bun Since Bun is a single binary, you can install older versions of Bun by re-running the installer script with a specific version. ### Installing a specific version of Bun on Linux/Mac To install a specific version of Bun, you can pass the git tag of the version you want to install to the install script, such as `bun-v1.2.0` or `bun-v$BUN_LATEST_VERSION`. ```sh $ curl -fsSL https://bun.sh/install | bash -s "bun-v$BUN_LATEST_VERSION" ``` ### Installing a specific version of Bun on Windows On Windows, you can install a specific version of Bun by passing the version number to the Powershell install script. ```sh # PowerShell: $ iex "& {$(irm https://bun.sh/install.ps1)} -Version $BUN_LATEST_VERSION" ``` ## Downloading Bun binaries directly To download Bun binaries directly, you can visit the [releases page](https://github.com/oven-sh/bun/releases) page on GitHub. For convenience, here are download links for the latest version: - [`bun-linux-x64.zip`](https://github.com/oven-sh/bun/releases/latest/download/bun-linux-x64.zip) - [`bun-linux-x64-baseline.zip`](https://github.com/oven-sh/bun/releases/latest/download/bun-linux-x64-baseline.zip) - [`bun-linux-x64-musl.zip`](https://github.com/oven-sh/bun/releases/latest/download/bun-linux-x64-musl.zip) - [`bun-linux-x64-musl-baseline.zip`](https://github.com/oven-sh/bun/releases/latest/download/bun-linux-x64-musl-baseline.zip) - [`bun-windows-x64.zip`](https://github.com/oven-sh/bun/releases/latest/download/bun-windows-x64.zip) - [`bun-windows-x64-baseline.zip`](https://github.com/oven-sh/bun/releases/latest/download/bun-windows-x64-baseline.zip) - [`bun-darwin-aarch64.zip`](https://github.com/oven-sh/bun/releases/latest/download/bun-darwin-aarch64.zip) - [`bun-linux-aarch64.zip`](https://github.com/oven-sh/bun/releases/latest/download/bun-linux-aarch64.zip) - [`bun-linux-aarch64-musl.zip`](https://github.com/oven-sh/bun/releases/latest/download/bun-linux-aarch64-musl.zip) - [`bun-darwin-x64.zip`](https://github.com/oven-sh/bun/releases/latest/download/bun-darwin-x64.zip) The `musl` binaries are built for distributions that do not ship with the glibc libraries by default, instead relying on musl. The two most popular distros are Void Linux and Alpine Linux, with the latter is used heavily in Docker containers. If you encounter an error like the following: `bun: /lib/x86_64-linux-gnu/libm.so.6: version GLIBC_2.29' not found (required by bun)`, try using the musl binary. Bun's install script automatically chooses the correct binary for your system. Bun's `x64` binaries target the Haswell CPU architecture, which means they require AVX and AVX2 instructions. For Linux and Windows, the `x64-baseline` binaries are also available which target the Nehalem architecture. If you run into an "Illegal Instruction" error when running Bun, try using the `baseline` binaries instead. Bun's install scripts automatically chooses the correct binary for your system which helps avoid this issue. Baseline builds are slower than regular builds, so use them only if necessary. Bun also publishes `darwin-x64-baseline` binaries, but these are just a copy of the `darwin-x64` ones so they still have the same CPU requirement. We only maintain these since some tools expect them to exist. Bun requires macOS 13.0 or later, which does not support any CPUs that don't meet our requirement. ## Uninstall If you need to remove Bun from your system, use the following commands. {% codetabs %} ```bash#macOS/Linux_(curl) $ rm -rf ~/.bun # for macOS, Linux, and WSL ``` ```powershell#Windows > powershell -c ~\.bun\uninstall.ps1 ``` ```powershell#Scoop > scoop uninstall bun ``` ```bash#npm $ npm uninstall -g bun ``` ```bash#Homebrew $ brew uninstall bun ``` {% /codetabs %} # Quickstart Source: https://bun.sh/docs/quickstart.md Let's write a simple HTTP server using the built-in `Bun.serve` API. First, create a fresh directory. ```bash $ mkdir quickstart $ cd quickstart ``` Run `bun init` to scaffold a new project. It's an interactive tool; for this tutorial, just press `enter` to accept the default answer for each prompt. ```bash $ bun init bun init helps you get started with a minimal project and tries to guess sensible defaults. Press ^C anytime to quit. package name (quickstart): entry point (index.ts): Done! A package.json file was saved in the current directory. + index.ts + .gitignore + tsconfig.json (for editor auto-complete) + README.md To get started, run: bun run index.ts ``` Since our entry point is a `*.ts` file, Bun generates a `tsconfig.json` for you. If you're using plain JavaScript, it will generate a [`jsconfig.json`](https://code.visualstudio.com/docs/languages/jsconfig) instead. ## Run a file Open `index.ts` and paste the following code snippet, which implements a simple HTTP server with [`Bun.serve`](https://bun.sh/docs/api/http). ```ts const server = Bun.serve({ port: 3000, fetch(req) { return new Response("Bun!"); }, }); console.log(`Listening on http://localhost:${server.port} ...`); ``` {% details summary="Seeing TypeScript errors on `Bun`?" %} If you used `bun init`, Bun will have automatically installed Bun's TypeScript declarations and configured your `tsconfig.json`. If you're trying out Bun in an existing project, you may see a type error on the `Bun` global. To fix this, first install `@types/bun` as a dev dependency. ```sh $ bun add -d @types/bun ``` Then add the following to your `compilerOptions` in `tsconfig.json`: ```json#tsconfig.json { "compilerOptions": { "lib": ["ESNext"], "target": "ESNext", "module": "ESNext", "moduleDetection": "force", "moduleResolution": "bundler", "allowImportingTsExtensions": true, "verbatimModuleSyntax": true, "noEmit": true, } } ``` {% /details %} Run the file from your shell. ```bash $ bun index.ts Listening on http://localhost:3000 ... ``` Visit [http://localhost:3000](http://localhost:3000) to test the server. You should see a simple page that says "Bun!". ## Run a script Bun can also execute `"scripts"` from your `package.json`. Add the following script: ```json-diff { "name": "quickstart", "module": "index.ts", "type": "module", + "scripts": { + "start": "bun run index.ts" + }, "devDependencies": { "@types/bun": "latest" } } ``` Then run it with `bun run start`. ```bash $ bun run start $ bun run index.ts Listening on http://localhost:3000 ... ``` {% callout %} ⚡️ **Performance** — `bun run` is roughly 28x faster than `npm run` (6ms vs 170ms of overhead). {% /callout %} ## Install a package Let's make our server a little more interesting by installing a package. First install the `figlet` package and its type declarations. Figlet is a utility for converting strings into ASCII art. ```bash $ bun add figlet $ bun add -d @types/figlet # TypeScript users only ``` Update `index.ts` to use `figlet` in the `fetch` handler. ```ts-diff + import figlet from "figlet"; const server = Bun.serve({ port: 3000, fetch(req) { + const body = figlet.textSync("Bun!"); + return new Response(body); - return new Response("Bun!"); }, }); ``` Restart the server and refresh the page. You should see a new ASCII art banner. ```txt ____ _ | __ ) _ _ _ __ | | | _ \| | | | '_ \| | | |_) | |_| | | | |_| |____/ \__,_|_| |_(_) ``` # TypeScript Source: https://bun.sh/docs/typescript.md To install the TypeScript definitions for Bun's built-in APIs, install `@types/bun`. ```sh $ bun add -d @types/bun # dev dependency ``` At this point, you should be able to reference the `Bun` global in your TypeScript files without seeing errors in your editor. ```ts console.log(Bun.version); ``` ## Suggested `compilerOptions` Bun supports things like top-level await, JSX, and extensioned `.ts` imports, which TypeScript doesn't allow by default. Below is a set of recommended `compilerOptions` for a Bun project, so you can use these features without seeing compiler warnings from TypeScript. ```jsonc { "compilerOptions": { // Environment setup & latest features "lib": ["ESNext"], "target": "ESNext", "module": "ESNext", "moduleDetection": "force", "jsx": "react-jsx", "allowJs": true, // Bundler mode "moduleResolution": "bundler", "allowImportingTsExtensions": true, "verbatimModuleSyntax": true, "noEmit": true, // Best practices "strict": true, "skipLibCheck": true, "noFallthroughCasesInSwitch": true, "noUncheckedIndexedAccess": true, // Some stricter flags (disabled by default) "noUnusedLocals": false, "noUnusedParameters": false, "noPropertyAccessFromIndexSignature": false, }, } ``` If you run `bun init` in a new directory, this `tsconfig.json` will be generated for you. (The stricter flags are disabled by default.) ```sh $ bun init ``` # `bun init` Source: https://bun.sh/docs/cli/init.md Scaffold an empty Bun project with the interactive `bun init` command. ```bash $ bun init bun init helps you get started with a minimal project and tries to guess sensible defaults. Press ^C anytime to quit. package name (quickstart): entry point (index.ts): Done! A package.json file was saved in the current directory. + index.ts + .gitignore + tsconfig.json (for editor auto-complete) + README.md To get started, run: bun run index.ts ``` Press `enter` to accept the default answer for each prompt, or pass the `-y` flag to auto-accept the defaults. {% details summary="How `bun init` works" %} `bun init` is a quick way to start a blank project with Bun. It guesses with sane defaults and is non-destructive when run multiple times. ![Demo](https://user-images.githubusercontent.com/709451/183006613-271960a3-ff22-4f7c-83f5-5e18f684c836.gif) It creates: - a `package.json` file with a name that defaults to the current directory name - a `tsconfig.json` file or a `jsconfig.json` file, depending if the entry point is a TypeScript file or not - an entry point which defaults to `index.ts` unless any of `index.{tsx, jsx, js, mts, mjs}` exist or the `package.json` specifies a `module` or `main` field - a `README.md` file If you pass `-y` or `--yes`, it will assume you want to continue without asking questions. At the end, it runs `bun install` to install `@types/bun`. {% /details %} {% bunCLIUsage command="init" /%} # `bun create` Source: https://bun.sh/docs/cli/bun-create.md {% callout %} **Note** — You don’t need `bun create` to use Bun. You don’t need any configuration at all. This command exists to make getting started a bit quicker and easier. {% /callout %} Template a new Bun project with `bun create`. This is a flexible command that can be used to create a new project from a React component, a `create-