Neon serverless driver provides multiple interfaces
The Neon serverless driver exposes multiple interfaces: a SQL-over-HTTP query API for basic queries, and `Client` and `Pool` constructors for sessions, interactive transactions, and node-postgres compatibility. Refer to Neon's documentation for a complete overview of these capabilities.
Query data with Drizzle using db.select()
Query data from a Drizzle table using `await db.select().from(schema.tableName)`. This returns all rows from the table as an array of objects. The result is an async operation.
Insert data with Drizzle using db.insert()
Insert data into a Drizzle table using `await db.insert(schema.tableName).values([{ column1: value1, column2: value2 }, ...])`. This is an async operation that inserts one or more rows into the specified table.
Execute migrations with drizzle-orm/neon-http/migrator
Execute Drizzle migrations against a Neon database by importing `migrate` from `drizzle-orm/neon-http/migrator` and calling `await migrate(db, { migrationsFolder: 'drizzle' })` where `db` is a Drizzle database instance. The migrate function opens a new connection to the Neon database and executes all unexecuted migrations in the specified folder.
Drizzle schema definition for Postgres with pgTable
Define a Drizzle ORM schema for Postgres using `pgTable` from `drizzle-orm/pg-core`. A table is defined with `pgTable('table_name', { column_name: type('db_column_name').modifiers() })`. Column types include `serial`, `integer`, `text`, and `timestamp`. Column modifiers include `.primaryKey()`, `.notNull()`, and `.defaultNow()` for timestamp columns. Example: `export const authors = pgTable('authors', { id: serial('id').primaryKey(), title: text('name').notNull(), bio: text('bio'), createdAt: timestamp('created_at').notNull().defaultNow() });`
Generate SQL migrations with drizzle-kit CLI
Use `bunx drizzle-kit generate --dialect postgresql --schema ./schema.ts --out ./drizzle` to generate SQL migrations from a Drizzle schema. This command creates a `drizzle` directory containing numbered `.sql` migration files and a `meta` directory with snapshot and journal files.
Neon Postgres setup with Drizzle ORM and Bun
To set up Neon Postgres with Drizzle ORM in a Bun project, create a project directory, initialize it with `bun init`, and install dependencies with `bun add drizzle-orm @neondatabase/serverless` and `bun add -D drizzle-kit`. Add your Neon Postgres connection string to a `.env.local` file as `DATABASE_URL=postgresql://usertitle:password@ep-adj-noun-guid.us-east-1.aws.neon.tech/neondb?sslmode=require`. In a `db.ts` file, import the neon driver from `@neondatabase/serverless` and drizzle from `drizzle-orm/neon-http`, then create a database instance with `const sql = neon(process.env.DATABASE_URL!); export const db = drizzle(sql);`. Bun automatically loads the DATABASE_URL from .env.local.
Bun support for Nuxt
Bun supports Nuxt with no extra configuration required.
Run Nuxt production server with Bun
After building a Nuxt app with the Bun preset, start the production server by running `bun run ./.output/server/index.mjs` from the project root.
Configure Nitro preset for Bun production builds
For production builds, set the Nitro preset to 'bun' in nuxt.config.ts to generate better optimized builds. This can be done by adding `nitro: { preset: 'bun' }` to the config, or by setting the environment variable `NITRO_PRESET=bun` before running `bun run build`. Using the Bun preset ensures that packages with Bun-specific exports are bundled correctly.
Start Nuxt dev server with Bun
Run `bun --bun run dev` from the project root to start the Nuxt development server using the Bun runtime. The `--bun` flag is required because the `nuxt` CLI uses Node.js by default; this flag forces it to use the Bun runtime instead.
Initialize a Nuxt app with Bun
Use `bunx nuxi init my-nuxt-app` to initialize a new Nuxt application with Bun as the package manager. The command will install dependencies including Nuxt and the Nuxt DevTools, and generate types in the .nuxt directory.
PM2 integration with Bun overview
PM2 is a process manager that runs applications as daemons (background processes). It offers process monitoring, automatic restarts, and scaling, and keeps your application running when deployed to a cloud-hosted virtual private server (VPS). You can use PM2 with Bun in two ways: as a CLI option using the --interpreter flag, or in a configuration file.
PM2 configuration file for Bun
Create a file named pm2.config.js in your project directory with the following content:
module.exports = {
name: "app",
script: "index.ts",
interpreter: "bun",
env: {
PATH: `${process.env.HOME}/.bun/bin:${process.env.PATH}`,
},
};
Then start the application with: pm2 start pm2.config.js
PM2 start with Bun interpreter using CLI
To start your application with PM2 and Bun as the interpreter, run: pm2 start --interpreter ~/.bun/bin/bun index.ts
Run Prisma test script with Bun
Use bun run to execute TypeScript scripts that use Prisma Client with Bun.
Run Prisma migrations with bunx
Use bunx --bun prisma migrate dev --name init to generate and run database migrations. This creates migration files in prisma/migrations, creates the SQLite database, and auto-generates the Prisma Client.
Initialize PrismaClient with LibSQL adapter in Bun
Create a file to initialize PrismaClient with the LibSQL adapter. Import PrismaClient from the generated client, create a PrismaLibSQL adapter with the DATABASE_URL, and export a configured PrismaClient instance: import { PrismaClient } from "./generated/client"; import { PrismaLibSQL } from "@prisma/adapter-libsql"; const adapter = new PrismaLibSQL({ url: process.env.DATABASE_URL || "" }); export const prisma = new PrismaClient({ adapter });
Install Prisma with Bun
Install Prisma CLI as a dev dependency and Prisma Client along with adapters as regular dependencies using bun add -d prisma and bun add @prisma/client @prisma/adapter-libsql.
Initialize Prisma schema with bunx
Use bunx --bun prisma init --datasource-provider sqlite to initialize Prisma schema and migration directory with SQLite.
Prisma CLI requires npm alongside Bun
Prisma's dynamic subcommand loading requires npm to be installed alongside Bun. This affects CLI commands such as prisma init and prisma migrate. Generated code works with Bun using the prisma-client generator.
Run Prisma scripts with bun run
Execute TypeScript scripts that use Prisma Client by running `bun run <filename>` (e.g., `bun run index.ts`).
PrismaClient initialization with Accelerate extension
Initialize PrismaClient with the Accelerate extension by importing `PrismaClient` from the generated client, then use `new PrismaClient().$extends(withAccelerate())` where `withAccelerate` is imported from `@prisma/extension-accelerate`.
Example: Create and count users with Prisma
Example of using PrismaClient in Bun:
```ts
import { prisma } from "./prisma/db";
await prisma.user.create({
data: {
name: "John Dough",
email: `john-${Math.random()}@example.com`,
},
});
const count = await prisma.user.count();
console.log(`There are ${count} users in the database.`);
```
This creates a new user and counts the total number of users in the database.
Initialize Prisma with PostgreSQL
Run `bunx --bun prisma init --db` to initialize Prisma with PostgreSQL as the database provider, which creates the schema and migration directory.
Generate Prisma Client manually
Run `bunx --bun prisma generate` to manually regenerate the Prisma Client. The client provides a fully typed API for reading and writing to the database.
Run Prisma migrations with Bun
Run `bunx --bun prisma migrate dev --name init` to create and apply the initial migration. This writes a `.sql` migration file to `prisma/migrations` and executes it against the PostgreSQL database.
Prisma generator configuration for Bun
In `prisma/schema.prisma`, configure the Prisma client generator with: provider = "prisma-client", output = "./generated", engineType = "client", and runtime = "bun". The runtime = "bun" setting enables the Rust-free client optimized for Bun.
Prisma requires Node.js for generation code
Prisma needs Node.js to run certain generation code. Node.js must be installed in the environment where you run `bunx prisma` commands.
Initialize Bun project with bun init
To create a new Bun project, run `bun init` in an empty directory. This initializes the project with default configuration.
Start Qwik development server with Bun
Run `bun run dev` to start the development server. The server runs with Vite and by default listens on http://localhost:5173/. Hot-reload is enabled and changes to source files are automatically reflected in the browser.
Initialize a new Qwik app with Bun
Use the command `bun create qwik` to initialize a new Qwik app. The create-qwik package detects when you are using bunx and automatically installs dependencies with bun.
Bun built-in support for JSX and TSX
Bun has built-in support for .jsx and .tsx files.
React template file structure
The React app template created by `bun init --react` has the following structure: src/index.ts (server entry point with API routes), src/frontend.tsx (React app entry point with HMR), src/App.tsx (main React component), src/APITester.tsx (component for testing API endpoints), src/index.html (HTML template), src/index.css (styles), src/*.svg (static assets), package.json (dependencies and scripts), tsconfig.json (TypeScript configuration), bunfig.toml (Bun configuration), and bun.lock (lock file).
bun start runs full-stack app in production
Running `bun start` starts the API server and frontend together in one process in production.
bun run build creates static site
Running `bun run build` builds the app as a static site. This creates a `dist` directory with the built app and its assets.
bun init --react creates full-stack template
Running `bun init --react` creates a template with a React app and an API server together in one full-stack app.
bun dev starts development mode with hot reloading
Running `bun dev` starts the app in development mode. This starts the API server and the React app with hot reloading.
Build Remix app with bun run build
To build a Remix app, run `bun run build` from the project root. This executes the `remix build` command with NODE_ENV=production.
Remix dev server requires Node.js, not Bun
The Remix development server (`remix dev`) relies on Node.js APIs that Bun does not implement. Therefore, while Bun can initialize the project and install dependencies, Node.js must be used to run the dev server.
Start Remix production server with bun start
After building a Remix app with `bun run build`, start the production server by running `bun start` from the project root. This executes `remix-serve ./build/index.js` and starts the app on http://localhost:3000.
Create Remix app with Bun
To initialize a Remix project, run `bun create remix`. This will prompt for project location, template selection, git initialization, and dependency installation.
Run Remix dev server with bun run dev
To start the Remix development server from the project root, run `bun run dev`. This command executes the `remix dev` command, which runs under Node.js and starts the Remix App Server on http://localhost:3000.
SolidStart with Bun example command
Example of creating and running a SolidStart app with Bun:
```sh
bun create solid my-app --solidstart --ts
cd my-app
bun install
bun dev
```
SolidStart development workflow with Bun
After creating a SolidStart project with `bun create solid my-app --solidstart --ts`, run `bun install` to install dependencies, then `bun dev` to start the development server. The development server runs on http://localhost:3000/ and hot-reloads changes to `src/routes/index.tsx` automatically.
Create a SolidStart app with Bun
Initialize a SolidStart app using `bun create solid my-app --solidstart --ts`. Pass the `--solidstart` flag to create a SolidStart project and `--ts` for TypeScript support. When prompted for a template, select `basic` for a minimal starter app.
Sentry setup example for Bun
Example showing how to initialize and test Sentry in a Bun application:
```ts
import * as Sentry from "@sentry/bun";
// Ensure to call this before importing any other modules!
Sentry.init({
dsn: "__SENTRY_DSN__",
tracesSampleRate: 1.0,
});
setTimeout(() => {
try {
foo();
} catch (e) {
Sentry.captureException(e);
}
}, 99);
```
Capture exceptions with Sentry in Bun
Capture exceptions using Sentry.captureException(e) to send error data to Sentry for tracking and analysis.
Sentry.init() configuration options
Initialize Sentry using Sentry.init() with the following options: dsn (string, required) - your Sentry DSN from project settings; tracesSampleRate (number) - enables Performance Monitoring by setting the sample rate, recommended to adjust in production. Sentry.init() must be called before importing any other modules.
Install Sentry Bun SDK
Install the Sentry Bun SDK using the command: bun add @sentry/bun
SSR React example with Bun.serve
Example showing how to combine renderToReadableStream with Bun.serve to create an SSR HTTP server: pass the stream from renderToReadableStream to a new Response with a Content-Type header of text/html.
SSR React with renderToReadableStream
To render a React component to an HTML stream server-side (SSR), import renderToReadableStream from react-dom/server and pass a React component to it. The function returns a ReadableStream that can be used in a Response object.
React 19 SSR optimization for Bun
React 19 and later include an SSR optimization that takes advantage of Bun's direct ReadableStream implementation. If renderToReadableStream is not found, ensure you have React 19 or later installed, or import from react-dom/server.browser instead of react-dom/server.
StricJS static file serving example
To serve static files from a directory like /public, use the dir utility from @stricjs/utils. Example: import { dir } from "@stricjs/utils"; export default new Router().get("/", () => new Response("Hi")).get("/*", dir("./public"));
StricJS project setup with Bun
To set up a StricJS project with Bun, create a new directory, initialize a Bun project with bun init, and install the required packages @stricjs/router and @stricjs/utils.
Run StricJS server in watch mode
Start a StricJS development server in watch mode using the command: bun --watch run index.ts
StricJS overview and features
StricJS is a Bun framework for building high-performance web applications and APIs. It is fast (one of the fastest Bun frameworks), minimal (core components like @stricjs/router and @stricjs/utils are under 50kB with no external dependencies), and extensible (includes a plugin system, dependency injection, and optional optimizations for handling requests).
StricJS basic HTTP server example
To create a basic HTTP server with StricJS, import the Router from @stricjs/router and export a new Router instance with route handlers. Example: import { Router } from "@stricjs/router"; export default new Router().get("/", () => new Response("Hi"));
SvelteKit hot reload in development
When running a SvelteKit dev server with Bun, edits to source files like `src/routes/+page.svelte` are automatically hot-reloaded in the browser without requiring a full page refresh.
SvelteKit with Bun production build adapter
To build a SvelteKit app for production with Bun, install the `svelte-adapter-bun` package with `bun add -D svelte-adapter-bun`. Then update the `svelte.config.js` file to import and use this adapter instead of the default `@sveltejs/adapter-auto`. After configuration, build the production bundle with `bun --bun run build`. The built output can be started with `bun ./build/index.js`.