### Install dependencies and start development server
Source: https://bun.sh/docs/guides/ecosystem/solidstart
Commands to navigate to the project directory, install required packages, and launch the development server.
```sh
cd my-app
bun install
```
```sh
bun dev
```
--------------------------------
### Global installation output example
Source: https://bun.sh/docs/pm/cli/add
Example output of running a globally installed command (`cowsay`) after installation with `bun add --global`.
```txt
______
< Bun! >
------
\ ^__^
\ (oo)\л_______
(__)\\ )\/\
||----w |
|| ||
```
--------------------------------
### Glob Quickstart
Source: https://bun.sh/docs/runtime/glob
Examples demonstrating how to scan directories for files and match strings against glob patterns using Bun's Glob class.
```APIDOC
## Glob Quickstart
### Scan a directory for files matching `*.ts`
```ts
import { Glob } from "bun";
const glob = new Glob("**/*.ts");
// Scans the current working directory and each of its sub-directories recursively
for await (const file of glob.scan(".")) {
console.log(file); // => "index.ts"
}
```
### Match a string against a glob pattern
```ts
import { Glob } from "bun";
const glob = new Glob("*.ts");
glob.match("index.ts"); // => true
glob.match("index.js"); // => false
```
```
--------------------------------
### Cron Job Quickstart
Source: https://bun.sh/docs/runtime/cron
Examples demonstrating how to use Bun.cron for different scheduling needs.
```APIDOC
## Quickstart
### Run a callback on a schedule in the current process:
```ts
Bun.cron("0 * * * *", async () => {
await cleanupTempFiles();
});
```
### Parse a cron expression to find the next matching time:
```ts
// Next weekday at 9:30 AM UTC
const next = Bun.cron.parse("30 9 * * MON-FRI");
```
### Register an OS-level cron job that runs a script on a schedule:
```ts
await Bun.cron("./worker.ts", "30 2 * * MON", "weekly-report");
```
```
--------------------------------
### Local template with setup scripts
Source: https://bun.sh/docs/runtime/templating/create
Define pre- and post-install setup scripts within the `bun-create` section of a local template's package.json. Supported fields include `preinstall`, `postinstall`, and `start`.
```json
{
"name": "@bun-examples/simplereact",
"version": "0.0.1",
"main": "index.js",
"dependencies": {
"react": "^17.0.2",
"react-dom": "^17.0.2"
},
"bun-create": {
"preinstall": "echo 'Installing...'",
"postinstall": ["echo 'Done!'"],
"start": "bun run echo 'Hello world!'"
}
}
```
--------------------------------
### Implement plugin hooks
Source: https://bun.sh/docs/bundler/esbuild
Example showing the usage of onStart, onResolve, onLoad, and onEnd hooks within the setup function.
```ts
import type { BunPlugin } from "bun";
const myPlugin: BunPlugin = {
name: "my-plugin",
setup(builder) {
builder.onStart(() => {
/* called when the bundle starts */
});
builder.onResolve(
{
/* onResolve.options */
},
args => {
return {
/* onResolve.results */
};
},
);
builder.onLoad(
{
/* onLoad.options */
},
args => {
return {
/* onLoad.results */
};
},
);
builder.onEnd(result => {
/* called when the bundle is complete */
});
},
};
```
--------------------------------
### Bun Auto-install Example
Source: https://bun.sh/docs/runtime/auto-install
This example demonstrates Bun's auto-installation feature. When executed without a node_modules directory, Bun will automatically install the 'foo' package from npm.
```typescript
import { foo } from "foo"; // install `latest` version
foo();
```
--------------------------------
### React application structure
Source: https://bun.sh/docs/bundler/standalone-html
Example files for a React application setup including HTML entry, main app component, and a sub-component.
```html
My App
```
```tsx
import React, { useState } from "react";
import { createRoot } from "react-dom/client";
import { Counter } from "./components/Counter.tsx";
function App() {
return (
Single-file React App
);
}
createRoot(document.getElementById("root")!).render();
```
```tsx
import React, { useState } from "react";
export function Counter() {
const [count, setCount] = useState(0);
return ;
}
```
--------------------------------
### Register onStart Callback
Source: https://bun.sh/docs/bundler/plugins
Use `build.onStart()` within a plugin's `setup` function to register a callback that runs when the bundler starts a new bundle. The callback can be asynchronous and Bun will wait for all `onStart` callbacks to complete before proceeding.
```typescript
import { plugin } from "bun";
plugin({
name: "onStart example",
setup(build) {
build.onStart(() => {
console.log("Bundle started!");
});
},
});
```
--------------------------------
### Start the development server
Source: https://bun.sh/docs/guides/ecosystem/sveltekit
Navigate to the project directory and start the development server using Bun.
```sh
cd my-app
bun --bun run dev
```
--------------------------------
### Initialize Project and Install Dependencies
Source: https://bun.sh/docs/guides/ecosystem/neon-drizzle
Set up the project directory and install the necessary Drizzle and Neon driver packages.
```sh
mkdir bun-drizzle-neon
cd bun-drizzle-neon
bun init -y
bun add drizzle-orm @neondatabase/serverless
bun add -D drizzle-kit
```
--------------------------------
### Basic Plugin Structure
Source: https://bun.sh/docs/bundler/esbuild
A basic example of how to define a Bun plugin using the `BunPlugin` type and the `setup` function, which receives a builder object.
```APIDOC
## Basic Plugin Structure
```ts
import type { BunPlugin } from "bun";
const myPlugin: BunPlugin = {
name: "my-plugin",
setup(builder) {
// define plugin logic here
},
};
```
```
--------------------------------
### Start HTTP Server with Bun.serve
Source: https://bun.sh/docs/guides/http/server
Starts an HTTP server on port 3000 and handles various routes for different responses and request types. Ensure Bun is installed to run this code.
```typescript
const server = Bun.serve({
async fetch(req) {
const path = new URL(req.url).pathname;
// respond with text/html
if (path === "/") return new Response("Welcome to Bun!");
// redirect
if (path === "/abc") return Response.redirect("/source", 301);
// send back a file (in this case, *this* file)
if (path === "/source") return new Response(Bun.file(import.meta.path));
// respond with JSON
if (path === "/api") return Response.json({ some: "buns", for: "you" });
// receive JSON data to a POST request
if (req.method === "POST" && path === "/api/post") {
const data = await req.json();
console.log("Received JSON:", data);
return Response.json({ success: true, data });
}
// receive POST data from a form
if (req.method === "POST" && path === "/form") {
const data = await req.formData();
console.log(data.get("someField"));
return new Response("Success");
}
// 404s
return new Response("Page not found", { status: 404 });
},
});
console.log(`Listening on ${server.url}`);
```
--------------------------------
### Astro Project Initialization Output
Source: https://bun.sh/docs/guides/ecosystem/astro
This is the expected output when creating an Astro project with Bun, showing the steps of project setup, dependency installation, and configuration.
```txt
╭─────╮ Houston:
│ ◠ ◡ ◠ We're glad to have you on board.
╰─────╯
astro v3.1.4 Launch sequence initiated.
dir Where should we create your new project?
./fumbling-field
tmpl How would you like to start your new project?
Use blog template
✔ Template copied
deps Install dependencies?
Yes
✔ Dependencies installed
ts Do you plan to write TypeScript?
Yes
use How strict should TypeScript be?
Strict
✔ TypeScript customized
git Initialize a new git repository?
Yes
✔ Git initialized
next Liftoff confirmed. Explore your project!
Enter your project directory using cd ./fumbling-field
Run `bun run dev` to start the dev server. CTRL+C to stop.
Add frameworks like react or tailwind using astro add.
Stuck? Join us at https://astro.build/chat
╭─────╮ Houston:
│ ◠ ◡ ◠ Good luck out there, astronaut! 🚀
╰─────╯
```
--------------------------------
### Start a Simple HTTP Server with Bun.js
Source: https://bun.sh/docs/guides/http/simple
This snippet starts an HTTP server on port 3000. It handles incoming requests by returning a static 'Welcome to Bun!' response. Ensure Bun is installed to run this code.
```typescript
const server = Bun.serve({
port: 3000,
fetch(request) {
return new Response("Welcome to Bun!");
},
});
console.log(`Listening on ${server.url}`);
```
--------------------------------
### Start the development server
Source: https://bun.sh/docs/guides/ecosystem/remix
Navigate to the project directory and start the development server using the Remix CLI.
```sh
cd my-app
bun run dev
```
```txt
$ remix dev
💿 remix dev
info building...
info built (263ms)
Remix App Server started at http://localhost:3000 (http://172.20.0.143:3000)
```
--------------------------------
### Install project dependencies
Source: https://bun.sh/docs/guides/ecosystem/vite
Navigate to the project directory and install dependencies using Bun.
```bash
cd my-app
bun install
```
--------------------------------
### Configure Bun in GitHub Actions workflow
Source: https://bun.sh/docs/guides/runtime/cicd
Basic setup for using the setup-bun action to install Bun and execute commands within a workflow job.
```yaml
name: my-workflow
jobs:
my-job:
name: my-job
runs-on: ubuntu-latest
steps:
# ...
- uses: actions/checkout@v4
- uses: oven-sh/setup-bun@v2 # [!code ++]
# run any `bun` or `bunx` command
- run: bun install # [!code ++]
- run: bun index.ts # [!code ++]
- run: bun run build # [!code ++]
```
--------------------------------
### Install Bun (Native)
Source: https://bun.sh/docs/project/contributing
Install Bun directly using the official installation script. This method is suitable for most users.
```bash
curl -fsSL https://bun.com/install | bash
```
--------------------------------
### bun install CLI Options
Source: https://bun.sh/docs/pm/cli/update
Comprehensive list of command-line arguments for the bun install command.
```APIDOC
## bun install CLI Options
### Description
Configuration flags for the bun install command to manage dependencies, registry settings, and project files.
### Parameters
#### Update Strategy
- **--force** (boolean) - Optional - Always request the latest versions from the registry & reinstall all dependencies. Alias: -f
- **--latest** (boolean) - Optional - Update packages to their latest versions
#### Dependency Scope
- **--production** (boolean) - Optional - Don't install devDependencies. Alias: -p
- **--global** (boolean) - Optional - Install globally. Alias: -g
- **--omit** (string) - Optional - Exclude dev, optional, or peer dependencies from install
#### Project File Management
- **--yarn** (boolean) - Optional - Write a yarn.lock file (yarn v1). Alias: -y
- **--no-save** (boolean) - Optional - Don't update package.json or save a lockfile
- **--save** (boolean) - Optional - Save to package.json (true by default)
- **--frozen-lockfile** (boolean) - Optional - Disallow changes to lockfile
- **--save-text-lockfile** (boolean) - Optional - Save a text-based lockfile
- **--lockfile-only** (boolean) - Optional - Generate a lockfile without installing dependencies
#### Network & Registry
- **--ca** (string) - Optional - Provide a Certificate Authority signing certificate
- **--cafile** (string) - Optional - Same as --ca, but as a file path to the certificate
- **--registry** (string) - Optional - Use a specific registry by default
- **--network-concurrency** (number) - Optional - Maximum number of concurrent network requests (default 48)
#### Caching
- **--cache-dir** (string) - Optional - Store & load cached data from a specific directory path
- **--no-cache** (boolean) - Optional - Ignore manifest cache entirely
#### Output & Logging
- **--silent** (boolean) - Optional - Don't log anything
- **--verbose** (boolean) - Optional - Excessively verbose logging
- **--no-progress** (boolean) - Optional - Disable the progress bar
- **--no-summary** (boolean) - Optional - Don't print a summary
#### Script Execution
- **--ignore-scripts** (boolean) - Optional - Skip lifecycle scripts in the project's package.json
- **--concurrent-scripts** (number) - Optional - Maximum number of concurrent jobs for lifecycle scripts (default 5)
#### Installation Controls
- **--no-verify** (boolean) - Optional - Skip verifying integrity of newly downloaded packages
- **--trust** (boolean) - Optional - Add to trustedDependencies in the project's package.json
- **--backend** (string) - Optional - Platform-specific optimizations (clonefile, hardlink, symlink, copyfile)
```
--------------------------------
### Install project dependencies
Source: https://bun.sh/docs/guides/ecosystem/hono
Navigates to the project directory and installs required dependencies.
```bash
cd myapp
bun install
```
--------------------------------
### Install Gel Client and Codegen
Source: https://bun.sh/docs/guides/ecosystem/gel
Install the Gel JavaScript client library and its codegen CLI using Bun.
```sh
bun add gel
bun add -D @gel/generate
touch seed.ts
```
--------------------------------
### Complete Test Configuration Example
Source: https://bun.sh/docs/test/configuration
A comprehensive example demonstrating various test discovery and execution settings.
```toml
[install]
# Install settings inherited by tests
registry = "https://registry.npmjs.org/"
exact = true
[test]
# Test discovery
root = "src"
preload = ["./test-setup.ts", "./global-mocks.ts"]
pathIgnorePatterns = ["vendor/**", "submodules/**"]
# Execution settings
timeout = 10000
smol = true
```
--------------------------------
### Install Global Package with Bun
Source: https://bun.sh/docs/pm/cli/install
Use the `-g` or `--global` flag to install packages globally, typically for command-line tools. This example shows installing and using `cowsay`.
```bash
bun install --global cowsay # or `bun install -g cowsay`
cowsay "Bun!"
```
--------------------------------
### Configure bun install logging
Source: https://bun.sh/docs/pm/cli/install
Adjust the verbosity of the installation process output.
```bash
bun install --verbose # debug logging
bun install --silent # no logging
```
--------------------------------
### bun init - Example usage for React presets
Source: https://bun.sh/docs/runtime/templating/init
Demonstrates various ways to scaffold React projects using `bun init` with different presets like Tailwind CSS and @shadcn/ui.
```bash
bun init --react bun init --react=tailwind bun init --react=shadcn
```
--------------------------------
### View node_modules tree structure
Source: https://bun.sh/docs/pm/overrides
Example output showing installed dependencies in the node_modules directory.
```text
node_modules
├── foo@1.2.3
└── bar@4.5.6
```
--------------------------------
### Initialize Bun Project and Add Neon Driver
Source: https://bun.sh/docs/guides/ecosystem/neon-serverless-postgres
Create a new Bun project directory, initialize it with `bun init`, and add the Neon serverless driver as a dependency.
```sh
mkdir bun-neon-postgres
cd bun-neon-postgres
bun init -y
bun add @neondatabase/serverless
```
--------------------------------
### Start the development server
Source: https://bun.sh/docs/guides/ecosystem/tanstack-start
Navigate to the project directory and launch the Vite development server using Bun.
```sh
cd my-tanstack-app
bun --bun run dev
```
--------------------------------
### Install and run global packages
Source: https://bun.sh/docs/guides/install/from-npm-install-to-bun-install
Installs packages to the global Bun directory and allows direct execution.
```sh
# Install a package globally
bun i -g eslint
# Run a globally-installed package without the `bun run` prefix
eslint --init
```
--------------------------------
### Basic HTTP Server Setup
Source: https://bun.sh/docs/runtime/http/server
Sets up a basic HTTP server with static, dynamic, and method-specific routes. Includes a wildcard route and a redirect. Requires Bun v1.2.3+ for the `routes` option.
```typescript
const server = Bun.serve({
// `routes` requires Bun v1.2.3+
routes: {
// Static routes
"/api/status": new Response("OK"),
// Dynamic routes
"/users/:id": req => {
return new Response(`Hello User ${req.params.id}!`);
},
// Per-HTTP method handlers
"/api/posts": {
GET: () => new Response("List posts"),
POST: async req => {
const body = await req.json();
return Response.json({ created: true, ...body });
},
},
// Wildcard route for all routes that start with "/api/" and aren't otherwise matched
"/api/*": Response.json({ message: "Not found" }, { status: 404 }),
// Redirect from /blog/hello to /blog/hello/world
"/blog/hello": Response.redirect("/blog/hello/world"),
// Serve a file by lazily loading it into memory
"/favicon.ico": Bun.file("./favicon.ico"),
},
// (optional) fallback for unmatched routes:
// Required if Bun's version < 1.2.3
fetch(req) {
return new Response("Not Found", { status: 404 });
},
});
console.log(`Server running at ${server.url}`);
```
--------------------------------
### Define a Custom Bun Plugin
Source: https://bun.sh/docs/bundler/plugins
Example of defining a custom Bun plugin with a name and a setup function. This plugin can then be passed to Bun.build.
```typescript
import type { BunPlugin } from "bun";
const myPlugin: BunPlugin = {
name: "Custom loader",
setup(build) {
// implementation
},
};
```
--------------------------------
### Start an HTTP Server with Bun.serve
Source: https://bun.sh/docs/runtime/bun-apis
This snippet demonstrates how to start a basic HTTP server using Bun.serve. It listens for requests and returns a 'Success!' response.
```typescript
Bun.serve({
fetch(req: Request) {
return new Response("Success!");
},
});
```
--------------------------------
### Initialize Bun project
Source: https://bun.sh/docs/guides/ecosystem/mongoose
Create a new directory and initialize a Bun project.
```sh
mkdir mongoose-app
cd mongoose-app
bun init
```
--------------------------------
### Create and Initialize Bun Project
Source: https://bun.sh/docs/guides/ecosystem/prisma
Start a new project using Bun and initialize it. This sets up the basic project structure.
```bash
mkdir prisma-app
cd prisma-app
bun init
```
--------------------------------
### Initialize Bun Project
Source: https://bun.sh/docs/guides/ecosystem/gel
Create a new Bun project and initialize it with default settings.
```sh
mkdir my-edgedb-app
cd my-edgedb-app
bun init -y
```
--------------------------------
### Omit Dependencies During Installation
Source: https://bun.sh/docs/pm/cli/install
Use the `--omit` flag to exclude specific dependency types like `dev`, `peer`, or `optional`. This example shows excluding `devDependencies`.
```bash
# Exclude "devDependencies" from the installation. This will apply to the
# root package and workspaces if they exist. Transitive dependencies will
# not have "devDependencies".
bun install --omit dev
# Install only dependencies from "dependencies"
bun install --omit=dev --omit=peer --omit=optional
```
--------------------------------
### Gel Project Initialization Output
Source: https://bun.sh/docs/guides/ecosystem/gel
Example output from `gel project init`, showing project configuration details.
```txt
No `gel.toml` found in `/Users/colinmcd94/Documents/bun/fun/examples/my-gel-app` or above
Do you want to initialize a new project? [Y/n]
> Y
Specify the name of Gel instance to use with this project [default: my_gel_app]:
> my_gel_app
Checking Gel versions...
Specify the version of Gel to use with this project [default: x.y]:
> x.y
┌─────────────────────┬──────────────────────────────────────────────────────────────────┐
│ Project directory │ /Users/colinmcd94/Documents/bun/fun/examples/my-gel-app │
│ Project config │ /Users/colinmcd94/Documents/bun/fun/examples/my-gel-app/gel.toml│
│ Schema dir (empty) │ /Users/colinmcd94/Documents/bun/fun/examples/my-gel-app/dbschema│
│ Installation method │ portable package │
│ Version │ x.y+6d5921b │
│ Instance name │ my_gel_app │
└─────────────────────┴──────────────────────────────────────────────────────────────────┘
Version x.y+6d5921b is already downloaded
Initializing Gel instance...
Applying migrations...
Everything is up to date. Revision initial
Project initialized.
To connect to my_gel_app, run `gel`
```
--------------------------------
### Define an HTTP route and start a server with Express
Source: https://bun.sh/docs/guides/ecosystem/express
This TypeScript code defines a basic Express server that listens on port 8080 and responds with 'Hello World!' to requests on the root path. Ensure you have Express installed.
```typescript
import express from "express";
const app = express();
const port = 8080;
app.get("/", (req, res) => {
res.send("Hello World!");
});
app.listen(port, () => {
console.log(`Listening on port ${port}...`);
});
```
--------------------------------
### Initialize a new Bun project
Source: https://bun.sh/docs/guides/ecosystem/upstash
Create a new project directory and initialize it with Bun. Navigate into the project directory.
```sh
bun init bun-upstash-redis
cd bun-upstash-redis
```
--------------------------------
### Initialize a Qwik project
Source: https://bun.sh/docs/guides/ecosystem/qwik
Use this command to scaffold a new Qwik application. The installer automatically detects Bun and uses it for dependency management.
```sh
bun create qwik
```
--------------------------------
### Dockerfile for Bun application
Source: https://bun.sh/docs/guides/deployment/digital-ocean
This Dockerfile uses the official Bun image to build and run your Bun application. It copies project files, installs production dependencies, exposes the application port, and sets the default command to start the application.
```docker
# Use the official Bun image to run the application
FROM oven/bun:debian
# Set the work directory to `/app`
WORKDIR /app
# Copy the package.json and bun.lock into the container
COPY package.json bun.lock ./
# Install the dependencies
RUN bun install --production --frozen-lockfile
# Copy the rest of the application into the container
COPY . .
# Expose the port (DigitalOcean will set PORT env var)
EXPOSE 8080
# Run the application
CMD ["bun", "index.ts"]
```
--------------------------------
### Initialize Bun Project
Source: https://bun.sh/docs/guides/ecosystem/prisma-postgres
Create a new directory and initialize a Bun project using `bun init`. This sets up the basic project structure.
```bash
mkdir prisma-postgres-app
cd prisma-postgres-app
bun init
```
--------------------------------
### Custom Module Resolution with onResolve
Source: https://bun.sh/docs/bundler/plugins
Implement custom module resolution logic using `build.onResolve()`. This example redirects imports starting with `images/` to a different path, demonstrating how to filter imports and return a new path for Bun to resolve.
```typescript
import { plugin } from "bun";
plugin({
name: "onResolve example",
setup(build) {
build.onResolve({ filter: /.*/, namespace: "file" }, args => {
if (args.path.startsWith("images/")) {
return {
path: args.path.replace("images/", "./public/images/"),
};
}
});
},
});
```
--------------------------------
### Define a basic HTTP route with Elysia
Source: https://bun.sh/docs/guides/ecosystem/elysia
This TypeScript code defines a simple Elysia application that listens on port 8080. It includes a GET route for the root path that returns 'Hello Elysia'. Ensure Elysia is installed as a dependency.
```typescript
import { Elysia } from "elysia";
const app = new Elysia().get("/", () => "Hello Elysia").listen(8080);
console.log(`🦊 Elysia is running at on port ${app.server?.port}...`);
```
--------------------------------
### Native Plugin Setup and Implementation
Source: https://bun.sh/docs/runtime/plugins
Steps to set up a Rust project for a Bun native plugin and implement the `onBeforeParse` lifecycle hook.
```APIDOC
## Creating a Native Plugin in Rust
Native plugins are NAPI modules which expose lifecycle hooks as C ABI functions.
### Setup
1. Install the NAPI CLI globally:
```bash
bun add -g @napi-rs/cli
napi new
```
2. Add the `bun-native-plugin` crate to your project:
```bash
cargo add bun-native-plugin
```
### Implementing `onBeforeParse` Hook
Use the `bun_native_plugin::bun` proc macro to define a function that implements a native lifecycle hook. The `onBeforeParse` hook is demonstrated below, replacing "foo" with "bar" in source code.
```rust
use bun_native_plugin::{define_bun_plugin, OnBeforeParse, bun, Result, anyhow, BunLoader};
use napi_derive::napi;
/// Define the plugin and its name
define_bun_plugin!("replace-foo-with-bar");
/// Implements the `onBeforeParse` hook to replace "foo" with "bar".
/// The #[bun] macro generates boilerplate code.
/// The function argument `handle: &mut OnBeforeParse` indicates implementation of the `onBeforeParse` hook.
#[bun]
pub fn replace_foo_with_bar(handle: &mut OnBeforeParse) -> Result<()> {
// Fetch the input source code.
let input_source_code = handle.input_source_code()?;
// Get the Loader for the file
let loader = handle.output_loader();
let output_source_code = input_source_code.replace("foo", "bar");
handle.set_output_source_code(output_source_code, BunLoader::BUN_LOADER_JSX);
Ok(())
}
```
### Usage in `Bun.build()`
Integrate the native plugin into your Bun build process.
```typescript
import myNativeAddon from "./my-native-addon";
Bun.build({
entrypoints: ["./app.tsx"],
plugins: [
{
name: "my-plugin",
setup(build) {
build.onBeforeParse(
{
namespace: "file",
filter: "**/*.tsx",
},
{
napiModule: myNativeAddon,
symbol: "replace_foo_with_bar",
// external: myNativeAddon.getSharedState()
},
);
},
},
],
});
```
```
--------------------------------
### Define API Endpoints with HTTP Method Handlers
Source: https://bun.sh/docs/bundler/fullstack
Define API endpoints by specifying handlers for different HTTP methods (GET, POST, PUT, DELETE) within the `routes` object of `Bun.serve()`. This example demonstrates basic CRUD operations for users.
```typescript
import { serve } from "bun";
serve({
routes: {
"/api/users": {
async GET(req) {
// Handle GET requests
const users = await getUsers();
return Response.json(users);
},
async POST(req) {
// Handle POST requests
const userData = await req.json();
const user = await createUser(userData);
return Response.json(user, { status: 201 });
},
async PUT(req) {
// Handle PUT requests
const userData = await req.json();
const user = await updateUser(userData);
return Response.json(user);
},
async DELETE(req) {
// Handle DELETE requests
await deleteUser(req.params.id);
return new Response(null, { status: 204 });
},
},
},
});
```
--------------------------------
### Initialize StricJS Project and Add Dependencies
Source: https://bun.sh/docs/guides/ecosystem/stric
Use these commands to create a new project directory, initialize it with Bun, and install the necessary StricJS packages.
```bash
mkdir myapp
cd myapp
bun init
bun add @stricjs/router @stricjs/utils
```
--------------------------------
### Store and Retrieve GitHub Token with Bun Secrets
Source: https://bun.sh/docs/runtime/secrets
This example demonstrates how to securely store and retrieve a GitHub token using Bun's secrets API. It first attempts to get the token, prompts the user if it's not found, and then stores it. Finally, it uses the token to make an authenticated API call.
```typescript
import { secrets } from "bun";
let githubToken: string | null = await secrets.get({
service: "my-cli-tool",
name: "github-token",
});
if (!githubToken) {
githubToken = prompt("Please enter your GitHub token");
await secrets.set({
service: "my-cli-tool",
name: "github-token",
value: githubToken,
});
console.log("GitHub token stored");
}
const response = await fetch("https://api.github.com/user", {
headers: { Authorization: `token ${githubToken}` },
});
console.log(`Logged in as ${(await response.json()).login}`);
```
--------------------------------
### Start the development server
Source: https://bun.sh/docs/guides/ecosystem/nextjs
Run the Next.js development server using the Bun runtime.
```sh
cd my-bun-app
bun --bun run dev
```
--------------------------------
### Start the production server
Source: https://bun.sh/docs/guides/ecosystem/remix
Run the production server using the built application files.
```sh
bun start
```
```txt
$ remix-serve ./build/index.js
[remix-serve] http://localhost:3000 (http://192.168.86.237:3000)
```
--------------------------------
### Install Security Scanner
Source: https://bun.sh/docs/runtime/bunfig
Installs a security scanner package for vulnerability scanning before installation.
```bash
bun add -d @acme/bun-security-scanner
```
--------------------------------
### Create a TanStack Start app
Source: https://bun.sh/docs/guides/ecosystem/tanstack-start
Initialize a new project using the interactive TanStack CLI.
```sh
bunx @tanstack/cli create my-tanstack-app
```
--------------------------------
### Install packages with bun install
Source: https://bun.sh/docs/pm/cli/install
Install specific packages or all dependencies defined in package.json.
```bash
bun install react
bun install react@19.1.1 # specific version
bun install react@latest # specific tag
```
```bash
bun install
```
--------------------------------
### Use Isolated Installs via Command Line
Source: https://bun.sh/docs/pm/isolated-installs
Specify the installation strategy using the --linker flag. Use 'isolated' for isolated installs or 'hoisted' for traditional installs.
```bash
bun install --linker isolated
```
```bash
bun install --linker hoisted
```
--------------------------------
### Inherit Install Settings in Tests
Source: https://bun.sh/docs/test/configuration
Tests can inherit network and installation configurations defined in the [install] section.
```toml
[install]
# These settings are inherited by bun test
registry = "https://npm.company.com/"
exact = true
prefer = "offline"
[test]
# Test-specific configuration
coverage = true
timeout = 10000
```
--------------------------------
### Install specific Bun version
Source: https://bun.sh/docs/guides/util/upgrade
Installs a specific version of Bun using platform-specific installation scripts.
```bash
curl -fsSL https://bun.sh/install | bash -s "bun-v1.3.3"
```
```powershell
iex "& {$(irm https://bun.sh/install.ps1)} -Version 1.3.3"
```
--------------------------------
### Initialize a native plugin project
Source: https://bun.sh/docs/runtime/plugins
Use the NAPI CLI to scaffold a new native module project.
```bash
bun add -g @napi-rs/cli
napi new
```
--------------------------------
### Initialize a new Bun project
Source: https://bun.sh/docs/guides/ecosystem/discordjs
Use `bun init` to create a new project directory and initialize it with Bun. This sets up the basic project structure.
```sh
mkdir my-bot
cd my-bot
bun init
```
--------------------------------
### Perform a Dry Run Installation
Source: https://bun.sh/docs/pm/cli/install
Use the `--dry-run` flag to simulate an installation without actually installing any packages.
```bash
bun install --dry-run
```
--------------------------------
### Preload setup files
Source: https://bun.sh/docs/test
Use the --preload flag to execute setup files before running tests, useful for defining lifecycle hooks.
```sh
bun test --preload ./setup.ts
```
--------------------------------
### Install Bun with cURL on macOS/Linux
Source: https://bun.sh/docs/installation
Use this command to install Bun on macOS and Linux systems. Ensure you have cURL installed.
```bash
curl -fsSL https://bun.sh/install | bash
```
--------------------------------
### Install LLVM on macOS
Source: https://bun.sh/docs/project/contributing
Installs LLVM version 21 using Homebrew on macOS. Ensure LLVM 21 is in your PATH after installation.
```bash
brew install llvm@21
```
--------------------------------
### Install Bun in GitHub Actions
Source: https://bun.sh/docs/pm/cli/install
Use the official setup-bun action to install Bun and run dependencies in a GitHub Actions workflow.
```yaml
name: bun-types
jobs:
build:
name: build-app
runs-on: ubuntu-latest
steps:
- name: Checkout repo
uses: actions/checkout@v4
- name: Install bun
uses: oven-sh/setup-bun@v2
- name: Install dependencies
run: bun install
- name: Build app
run: bun run build
```
--------------------------------
### Switch to Hoisted Installs
Source: https://bun.sh/docs/pm/isolated-installs
If encountering compatibility issues with isolated installs, you can switch a specific project to use the hoisted install linker.
```bash
bun install --linker hoisted
```
--------------------------------
### Start a WebSocket Server
Source: https://bun.sh/docs/runtime/http/websockets
This snippet demonstrates how to start a WebSocket server using Bun.serve(). Incoming requests are upgraded to WebSocket connections in the fetch handler.
```typescript
Bun.serve({
fetch(req, server) {
// upgrade the request to a WebSocket
if (server.upgrade(req)) {
return;
}
return new Response("Upgrade failed", { status: 500 });
},
websocket: {}, // handlers
});
```
--------------------------------
### Configure Dry Run for Installation
Source: https://bun.sh/docs/runtime/bunfig
Set whether 'bun install' will actually install dependencies. Defaults to false. Equivalent to --dry-run.
```toml
[install]
dryRun = false
```
--------------------------------
### Example output paths
Source: https://bun.sh/docs/guides/util/main
The expected output when printing the absolute path of the entrypoint.
```txt
/path/to/index.ts
```
```txt
/path/to/foo.ts
```
--------------------------------
### Install Bun using Homebrew
Source: https://bun.sh/docs/installation
Install Bun on macOS or Linux using the Homebrew package manager. Ensure Homebrew is installed and configured.
```bash
brew install oven-sh/bun/bun
```
--------------------------------
### Install LLVM on Ubuntu/Debian
Source: https://bun.sh/docs/project/contributing
Installs LLVM version 21 on Ubuntu/Debian systems using an automatic installation script. This script is compatible with all Ubuntu versions.
```bash
wget https://apt.llvm.org/llvm.sh -O - | sudo bash -s -- 21 all
```
--------------------------------
### Initialize a new Bun project
Source: https://bun.sh/docs/quickstart
Creates a new directory with a basic project structure.
```bash
bun init my-app
```
--------------------------------
### Install Specific Bun Version (Windows)
Source: https://bun.sh/docs/installation
Use the PowerShell install script with the `-Version` parameter to install a particular older version of Bun on Windows.
```powershell
iex "& {$(irm https://bun.com/install.ps1)} -Version 1.3.3"
```
--------------------------------
### Create a SvelteKit project
Source: https://bun.sh/docs/guides/ecosystem/sveltekit
Use the Svelte CLI to scaffold a new project. Select Bun as the package manager during the setup prompts.
```sh
bunx sv create my-app
```
--------------------------------
### Serve Static Site with Bun
Source: https://bun.sh/docs/bundler/html-static
Use the `bun` command to serve a static HTML file. Bun automatically bundles assets and starts a development server.
```bash
bun ./index.html
```
--------------------------------
### Install Package from Tarball
Source: https://bun.sh/docs/pm/cli/add
Bun allows installing packages directly from a tarball URL. This bypasses the package registry and installs the package from the specified tarball.
```APIDOC
## Install Package from Tarball
### Description
Install a package directly from a tarball URL. Bun will download and install the package from the specified tarball, not from the package registry.
### Command Example
```sh
bun add zod@https://registry.npmjs.org/zod/-/zod-3.21.4.tgz
```
### package.json Update
This command will update your `package.json` to include the tarball URL as the dependency.
```json
{
"dependencies": {
"zod": "https://registry.npmjs.org/zod/-/zod-3.21.4.tgz"
}
}
```
```
--------------------------------
### Plugin Hooks Implementation
Source: https://bun.sh/docs/bundler/esbuild
Demonstrates how to implement the `onStart`, `onResolve`, `onLoad`, and `onEnd` hooks within a Bun plugin's `setup` function.
```APIDOC
## Plugin Hooks Implementation
```ts
import type { BunPlugin } from "bun";
const myPlugin: BunPlugin = {
name: "my-plugin",
setup(builder) {
builder.onStart(() => {
/* called when the bundle starts */
});
builder.onResolve(
{
/* onResolve.options */
},
args => {
return {
/* onResolve.results */
};
},
);
builder.onLoad(
{
/* onLoad.options */
},
args => {
return {
/* onLoad.results */
};
},
);
builder.onEnd(result => {
/* called when the bundle is complete */
});
},
};
```
```
--------------------------------
### Migrate to bun install
Source: https://bun.sh/docs/guides/install/from-npm-install-to-bun-install
Use `bun install` as a direct replacement for `npm install`. It automatically converts `package-lock.json` to `bun.lock` and supports `.npmrc` configurations.
```bash
bun i
# To add dependencies:
bun i @types/bun
# To add devDependencies:
bun i -d @types/bun
# To remove a dependency:
bun rm @types/bun
```
--------------------------------
### Initialize a new Bun project
Source: https://bun.sh/docs/runtime/templating/init
Scaffolds a new Bun project in the specified directory. Press enter to accept defaults or use `-y` to auto-accept.
```bash
bun init my-app
```
--------------------------------
### Install Sentry Bun SDK
Source: https://bun.sh/docs/guides/ecosystem/sentry
Install the Sentry SDK for Bun using the bun add command. This command fetches and installs the necessary package.
```sh
bun add @sentry/bun
```
--------------------------------
### Install Specific Bun Version (Linux/macOS)
Source: https://bun.sh/docs/installation
Re-run the installer script, passing the desired version tag as an argument to install a specific older version of Bun.
```bash
curl -fsSL https://bun.com/install | bash -s "bun-v1.3.3"
```
--------------------------------
### Verify Bun Installation
Source: https://bun.sh/docs/installation
After installation, verify that Bun is installed correctly by checking its version and revision. Open a new terminal window to ensure the PATH is updated.
```bash
bun --version
# Output: 1.x.y
# See the precise commit of `oven-sh/bun` that you're using
bun --revision
```
--------------------------------
### Build with CLI Entrypoints
Source: https://bun.sh/docs/bundler
Initiate the build process directly from the command line by specifying the entrypoint file.
```bash
bun build ./index.ts
```
--------------------------------
### Install Development Tools using Scoop (x64)
Source: https://bun.sh/docs/project/building-windows
Installs essential development tools including Node.js LTS, Go, Rust, NASM, Ruby, Perl, and Ccache using Scoop. LLVM is installed separately due to potential bugs when installing multiple packages at once.
```powershell
irm https://get.scoop.sh | iex
scoop install nodejs-lts go rustup nasm ruby perl ccache
# scoop seems to be buggy if you install llvm and the rest at the same time
scoop install llvm@21.1.8
```
--------------------------------
### Initialize a Vite project with Bun
Source: https://bun.sh/docs/guides/ecosystem/vite
Use the Vite scaffolding tool via Bun to create a new project.
```bash
bun create vite my-app
```
```txt
✔ Select a framework: › React
✔ Select a variant: › TypeScript + SWC
Scaffolding project in /path/to/my-app...
```
--------------------------------
### Initialize Prisma with SQLite
Source: https://bun.sh/docs/guides/ecosystem/prisma
Use `bunx` to initialize Prisma with a SQLite datasource. This creates the initial schema file.
```bash
bunx --bun prisma init --datasource-provider sqlite
```
--------------------------------
### Update package.json Scripts for Build and Start
Source: https://bun.sh/docs/guides/ecosystem/tanstack-start
Ensure your package.json includes 'build' and 'start' scripts. The 'build' script uses Vite with Bun, and the 'start' script points to the Nitro output server file. Note: The custom 'start' script is not needed for Vercel deployments.
```json
{
"scripts": {
"build": "bun --bun vite build", // [!code ++]
// The .output files are created by Nitro when you run `bun run build`.
// Not necessary when deploying to Vercel.
"start": "bun run .output/server/index.mjs" // [!code ++]
}
}
```
--------------------------------
### Install React dependencies
Source: https://bun.sh/docs/bundler/standalone-html
Install the necessary React packages for your project.
```bash
bun install react react-dom
```
--------------------------------
### Running CLI with Arguments
Source: https://bun.sh/docs/guides/process/argv
Example command execution and the resulting output array.
```sh
bun run cli.ts --flag1 --flag2 value
```
```txt
[ '/path/to/bun', '/path/to/cli.ts', '--flag1', '--flag2', 'value' ]
```
--------------------------------
### Install Vanilla SQLite on macOS
Source: https://bun.sh/docs/runtime/sqlite
On macOS, install a vanilla build of SQLite using Homebrew if extensions are not supported by the default build. This command installs SQLite and shows the path to the binary.
```bash
brew install sqlite
which sqlite # get path to binary
```
--------------------------------
### Create a local template directory structure
Source: https://bun.sh/docs/runtime/templating/create
Set up a local template by creating a directory within `$HOME/.bun-create/` or `/.bun-create/`. The `BUN_CREATE_DIR` environment variable can customize the global path.
```bash
cd $HOME/.bun-create
mkdir foo
cd foo
```
--------------------------------
### Reproducible Installs with Frozen Lockfile
Source: https://bun.sh/docs/pm/cli/install
Ensure reproducible installs by using `--frozen-lockfile`. This installs exact versions from the lockfile and exits with an error if `package.json` and `bun.lock` disagree. The lockfile will not be updated.
```bash
bun install --frozen-lockfile
```
--------------------------------
### Installation Process Control Options
Source: https://bun.sh/docs/pm/cli/install
Options to control the behavior of the installation process.
```APIDOC
### Installation Process Control
Don't install anything
Always request the latest versions from the registry & reinstall all dependencies
Install globally
Platform-specific optimizations: "clonefile", "hardlink", "symlink", "copyfile"
Install packages for the matching workspaces
Analyze & install all dependencies of files passed as arguments recursively
```
--------------------------------
### General Configuration Options
Source: https://bun.sh/docs/pm/cli/install
Options for configuring the installation process.
```APIDOC
### General Configuration
Specify path to config file (bunfig.toml)
Set a specific cwd
```
--------------------------------
### Install without creating a lockfile
Source: https://bun.sh/docs/pm/lockfile
Prevents the creation or update of a lockfile during installation.
```bash
bun install --no-save
```
--------------------------------
### Initialize Native Plugin Project
Source: https://bun.sh/docs/bundler/plugins
Commands to scaffold a new NAPI project and add the required Bun native plugin crate.
```bash
bun add -g @napi-rs/cli
napi new
```
```bash
cargo add bun-native-plugin
```
--------------------------------
### Build for production
Source: https://bun.sh/docs/guides/ecosystem/sveltekit
Run the build command to generate a production-ready bundle using the configured adapter.
```sh
bun --bun run build
```
--------------------------------
### Install Railway CLI
Source: https://bun.sh/docs/guides/deployment/railway
Installs the Railway CLI globally using Bun.
```bash
bun install -g @railway/cli
```
--------------------------------
### Execute a complete build with plugins and compilation
Source: https://bun.sh/docs/bundler/executables
A full example showing how to use Bun.build with a custom plugin, compilation settings, and build result handling.
```typescript
import type { BunPlugin } from "bun";
const myPlugin: BunPlugin = {
name: "my-plugin",
setup(build) {
// Plugin implementation
},
};
const result = await Bun.build({
entrypoints: ["./src/cli.ts"],
compile: {
target: "bun-linux-x64",
outfile: "./dist/mycli",
execArgv: ["--smol"],
autoloadDotenv: false,
autoloadBunfig: false,
},
minify: true,
sourcemap: "linked",
bytecode: true,
define: {
"process.env.NODE_ENV": JSON.stringify("production"),
VERSION: JSON.stringify("1.0.0"),
},
plugins: [myPlugin],
});
if (result.success) {
console.log("Build successful:", result.outputs[0].path);
}
```
--------------------------------
### Configure installation backends
Source: https://bun.sh/docs/pm/cli/install
Force specific system call backends for dependency installation to optimize performance based on the OS.
```bash
rm -rf node_modules
bun install --backend hardlink
```
```bash
rm -rf node_modules
bun install --backend clonefile
```
```bash
rm -rf node_modules
bun install --backend clonefile_each_dir
```
```bash
rm -rf node_modules
bun install --backend copyfile
```
```bash
rm -rf node_modules
bun install --backend symlink
bun --preserve-symlinks ./my-file.js
node --preserve-symlinks ./my-file.js # https://nodejs.org/api/cli.html#--preserve-symlinks
```
--------------------------------
### Start the systemd service
Source: https://bun.sh/docs/guides/ecosystem/systemd
Manually start the service without requiring a reboot.
```bash
systemctl start my-app
```
--------------------------------
### Initialize a Remix project
Source: https://bun.sh/docs/guides/ecosystem/remix
Use the create-remix command to scaffold a new project directory with Bun.
```sh
bun create remix
```
```txt
remix v1.19.3 💿 Let's build a better website...
dir Where should we create your new project?
./my-app
◼ Using basic template See https://remix.run/docs/en/main/guides/templates#templates for more
✔ Template copied
git Initialize a new git repository?
Yes
deps Install dependencies with bun?
Yes
✔ Dependencies installed
✔ Git initialized
done That's it!
Enter your project directory using cd ./my-app
Check out README.md for development and deploy instructions.
```