apps/docs/content/docs/guides/runtimes/bun.mdx
Bun is a fast JavaScript runtime that includes a bundler, test runner, and package manager. In this guide, you will set up a Bun project with Prisma ORM and a Prisma Postgres database. You will create a simple HTTP server and build a Bun executable for deployment.
<Youtube videoId="gE6l4eX0v_I" title="How to use Prisma ORM with Bun and Prisma Postgres" />First, create a directory for your project and navigate to it:
mkdir bun-prisma
cd bun-prisma
Then, initialise a new Bun project:
bun init -y
This creates a basic Bun project that includes a package.json file and an index.ts file.
Install the required Prisma packages and other dependencies:
bun add -d prisma @types/pg
bun add @prisma/client @prisma/adapter-pg pg
:::info
If you are using a different database provider (MySQL, SQL Server, SQLite), install the corresponding driver adapter package instead of @prisma/adapter-pg. For more information, see Database drivers.
:::
Initialize Prisma ORM with Prisma Postgres in your project:
bunx --bun prisma init --db
:::note
The --bun flag is required to ensure Prisma runs with the Bun runtime. Without it, Prisma falls back to Node.js due to the #!/usr/bin/env node shebang in the CLI.
:::
:::info
You'll need to answer a few questions while setting up your Prisma Postgres database. Select the region closest to your location and a memorable name for your database like "My Bun Project"
:::
This command creates:
prisma/ directory with your schema.prisma fileprisma.config.ts file.env file with your DATABASE_URLWe're going to use a direct connection string for connecting to Prisma Postgres. To get your direct connection string:
postgres://Update your .env file to replace the DATABASE_URL with the new connection string:
DATABASE_URL="your_database_url_here" // [!code --]
DATABASE_URL="your_direct_connection_string_here" // [!code ++]
Open prisma/schema.prisma and update it to include your data model:
generator client {
provider = "prisma-client"
output = "../generated/prisma"
}
datasource db {
provider = "postgresql"
}
model User { // [!code ++]
id Int @id @default(autoincrement()) // [!code ++]
email String @unique // [!code ++]
name String? // [!code ++]
} // [!code ++]
Generate the Prisma client and apply your schema to the database:
bunx --bun prisma migrate dev --name init
bunx --bun prisma generate
This command:
generated/prisma directoryCreate a db.ts file in your project root to configure PrismaClient:
import { PrismaClient } from "./generated/prisma/client";
import { PrismaPg } from "@prisma/adapter-pg";
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL!,
});
export const prisma = new PrismaClient({
adapter,
});
Create a seed script in the prisma folder to populate your database with sample data:
import { PrismaClient } from "../generated/prisma/client";
import { PrismaPg } from "@prisma/adapter-pg";
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL!,
});
const prisma = new PrismaClient({
adapter,
});
async function main() {
// Create multiple users
await prisma.user.createMany({
data: [
{ email: "[email protected]", name: "Alice" },
{ email: "[email protected]", name: "Bob" },
{ email: "[email protected]", name: "Charlie" },
{ email: "[email protected]", name: "Diana" },
{ email: "[email protected]", name: "Eve" },
{ email: "[email protected]", name: "Frank" },
{ email: "[email protected]", name: "Grace" },
{ email: "[email protected]", name: "Henry" },
{ email: "[email protected]", name: "Isabella" },
{ email: "[email protected]", name: "Jack" },
],
skipDuplicates: true, // prevents errors if you run the seed multiple times
});
console.log("Seed data inserted!");
}
main()
.catch((e) => {
console.error(e);
process.exit(1);
})
.finally(async () => {
await prisma.$disconnect();
});
Add the following content to the file:
import { defineConfig, env } from "prisma/config";
export default defineConfig({
schema: "prisma/schema.prisma",
migrations: {
path: "prisma/migrations",
seed: `bun run prisma/seed.ts`, // [!code ++]
},
datasource: {
url: env("DATABASE_URL"),
},
});
:::note
Unlike Node.js, Bun automatically loads .env files, so the import 'dotenv/config' line is not needed. If you see this import in your generated prisma.config.ts, you can safely remove it.
:::
Run the seed script to populate your database:
bunx --bun prisma db seed
Replace the index.ts file contents with the following code to build a simple HTTP server that uses Prisma ORM to fetch and display users:
import { prisma } from "./db";
const server = Bun.serve({
port: 3000,
async fetch(req) {
const { pathname } = new URL(req.url);
// Skip favicon route
if (pathname === "/favicon.ico") {
return new Response(null, { status: 204 }); // or serve an icon if you have one
}
// Return all users
const users = await prisma.user.findMany();
// Count all users
const count = await prisma.user.count();
// Format the response with JSON
return new Response(
JSON.stringify({
users: users,
totalUsers: count,
}),
{ headers: { "Content-Type": "application/json" } },
);
},
});
console.log(`Listening on http://localhost:${server.port}`);
Start your Bun server:
bun run index.ts
You should see Listening on http://localhost:3000 in the console. When you visit http://localhost:3000 in your browser, you'll see a JSON response with all the users in your database and the total count.
Bun can compile your TypeScript application into a single executable file, which is useful for deployment and distribution.
Build your application into an executable:
bun build --compile index.ts
This creates an executable file named index (or index.exe on Windows) in your project directory.
Run the compiled executable:
./index
You should see the same Listening on http://localhost:3000 message, and your application will work exactly the same as before. The executable includes all dependencies and can be deployed to any compatible system without requiring Bun or Node.js to be installed.
:::note
Bun executables are useful for:
:::
You can explore this example to see a sample application built with Bun and Prisma.
Now that you have a Bun application connected to a Prisma Postgres database, you can continue by: