Skip to main content
Prisma Documentation Docs

Search documentation

Type to search this documentation.

On this pageOverview

Bun

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 small HTTP server and build a Bun executable for deployment.

https://www.youtube.com/embed/gE6l4eX0v_I

First, create a directory for your project and navigate to it:

mkdir bun-prisma

cd bun-prisma

Then, initialise a new Bun project:

title="bun"
bun init
pnpm
pnpm init
yarn
yarn init
npm
npm init

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 prisma@prev @types/pg --dev

bun add @prisma/client@7 @prisma/adapter-pg pg
Bash
pnpm add prisma@prev @types/pg --save-dev
pnpm add @prisma/client@7 @prisma/adapter-pg pg
Bash
yarn add prisma@prev @types/pg --dev
yarn add @prisma/client@7 @prisma/adapter-pg pg
Bash
npm install prisma@prev @types/pg --save-dev
npm install @prisma/client@7 @prisma/adapter-pg pg

[!NOTE] 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
Bash
pnpm prisma init
Bash
yarn prisma init
Bash
npx prisma init

[!NOTE] When using the Bun tab for prisma init, the --bun flag ensures Prisma runs with the Bun runtime instead of falling back to Node.js due to the #!/usr/bin/env node shebang in the CLI.

[!NOTE] prisma init creates the Prisma scaffolding and a local DATABASE_URL. In the next step, you will create a Prisma Postgres database and replace that value with a direct postgres://... connection string.

This command creates:

  • A prisma/ directory with your schema.prisma file
  • A prisma.config.ts file
  • A .env file with your DATABASE_URL

This command creates:

  • A prisma/ directory with your schema.prisma file
  • A prisma.config.ts file
  • A .env file with your DATABASE_URL

Create a Prisma Postgres database and replace the generated DATABASE_URL in your .env file with the postgres://... connection string from the CLI output:

title="bun"
bunx create-db
pnpm
pnpm dlx create-db
yarn
yarn dlx create-db
npm
npx create-db

Update your .env file:

title=".env"
DATABASE_URL="postgres://..."

Open prisma/schema.prisma and update it to include your data model:

title="prisma/schema.prisma"
generator client {

  provider = "prisma-client"

  output   = "../generated/prisma"

}

datasource db {

  provider = "postgresql"

}

model User { 

  id    Int     @id @default(autoincrement()) 

  email String  @unique

  name  String?

} 

Generate the Prisma client and apply your schema to the database:

title="bun"
bunx prisma migrate dev --name init

bunx prisma generate
pnpm
pnpm prisma migrate dev --name init
pnpm prisma generate
yarn
yarn prisma migrate dev --name init
yarn prisma generate
npm
npx prisma migrate dev --name init
npx prisma generate

This command:

  • Creates the database tables based on your schema
  • Generates the Prisma client in the generated/prisma directory

Create a db.ts file in your project root to configure PrismaClient:

title="db.ts"
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:

title="prisma/seed.ts"
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: "alice@example.com", name: "Alice" },

      { email: "bob@example.com", name: "Bob" },

      { email: "charlie@example.com", name: "Charlie" },

      { email: "diana@example.com", name: "Diana" },

      { email: "eve@example.com", name: "Eve" },

      { email: "frank@example.com", name: "Frank" },

      { email: "grace@example.com", name: "Grace" },

      { email: "henry@example.com", name: "Henry" },

      { email: "isabella@example.com", name: "Isabella" },

      { email: "jack@example.com", 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:

title="prisma.config.ts"
import { defineConfig, env } from "prisma/config";

export default defineConfig({

  schema: "prisma/schema.prisma",

  migrations: {

    path: "prisma/migrations",

    seed: `bun run prisma/seed.ts`, 

  },

  datasource: {

    url: env("DATABASE_URL"),

  },

});

Run the seed script to populate your database:

title="bun"
bunx prisma db seed
pnpm
pnpm prisma db seed
yarn
yarn prisma db seed
npm
npx prisma db seed

Replace the index.ts file contents with the following code to build a small HTTP server that uses Prisma ORM to fetch and display users:

title="index.ts"
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.

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:

  • Extending your Prisma schema with additional models and relationships
  • Implementing authentication and authorization
  • Adding input validation and error handling
  • Exploring Bun's built-in testing tools
  • Deploying your executable to production servers
Suggest an edit

Propose a replacement for this page. The site team reviews it before applying any changes.

Export
Documentation menu