# Bun (/docs/guides/runtimes/bun)

Location: Guides > Runtimes > Bun

Introduction [#introduction]

[Bun](https://bun.sh) 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.

[How to use Prisma ORM with Bun and Prisma Postgres](https://www.youtube.com/watch?v=gE6l4eX0v_I)

Prerequisites [#prerequisites]

* [Bun](https://bun.sh/docs/installation) installed in your system
* A [Prisma Postgres database](/postgres) (created during setup)
* Basic knowledge of JavaScript/TypeScript

1. Setting up your Bun project [#1-setting-up-your-bun-project]

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

```bash
mkdir bun-prisma
cd bun-prisma
```

Then, initialise a new Bun project:

```bash
bun init -y
```

This creates a basic Bun project that includes a `package.json` file and an `index.ts` file.

2. Installing and configuring Prisma [#2-installing-and-configuring-prisma]

2.1. Install dependencies [#21-install-dependencies]

Install the required Prisma packages and other dependencies:

```bash
bun add -d prisma @types/pg
bun add @prisma/client @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](/orm/core-concepts/supported-databases/database-drivers).

2.2. Initialize Prisma ORM with Prisma Postgres [#22-initialize-prisma-orm-with-prisma-postgres]

Initialize Prisma ORM with Prisma Postgres in your project:

```bash
bunx --bun prisma init
```

> [!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.

> [!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`

2.3. Create a Prisma Postgres database [#23-create-a-prisma-postgres-database]

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

```bash
npx create-db
```

Update your `.env` file:

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

2.4. Update your Prisma schema [#24-update-your-prisma-schema]

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

```prisma title="prisma/schema.prisma"
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 ++]
```

3. Generate Prisma Client and run migrations [#3-generate-prisma-client-and-run-migrations]

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

```bash
bunx --bun prisma migrate dev --name init
bunx --bun prisma generate
```

This command:

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

4. Setting up database configuration and creating a seed script [#4-setting-up-database-configuration-and-creating-a-seed-script]

4.1. Create a database utility file [#41-create-a-database-utility-file]

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

```typescript 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,
});
```

4.2. Create a seed script [#42-create-a-seed-script]

Create a seed script in the `prisma` folder to populate your database with sample data:

```typescript 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();
  });
```

3.3. Add the seed script to Prisma Config [#33-add-the-seed-script-to-prisma-config]

Add the following content to the file:

```typescript 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`, // [!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:

```bash
bunx --bun prisma db seed
```

5. Creating your Bun server [#5-creating-your-bun-server]

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:

```typescript 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}`);
```

6. Running your application [#6-running-your-application]

Start your Bun server:

```bash
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.

7. Building and running a Bun executable [#7-building-and-running-a-bun-executable]

Bun can compile your [TypeScript application into a single executable file](https://bun.com/docs/bundler/executables), which is useful for deployment and distribution.

7.1. Build the executable [#71-build-the-executable]

Build your application into an executable:

```bash
bun build --compile index.ts
```

This creates an executable file named `index` (or `index.exe` on Windows) in your project directory.

7.2. Run the executable [#72-run-the-executable]

Run the compiled executable:

```bash
./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:
> 
> * **Deployment**: Ship a single file instead of managing dependencies
> * **Distribution**: Share your application without requiring users to install Bun
> * **Performance**: Faster startup times compared to running TypeScript files
> * **Security**: Your source code is compiled and not easily readable

Next steps [#next-steps]

You can explore [this example](https://pris.ly/bun_ppg_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

More info [#more-info]

* [Bun Documentation](https://bun.sh/docs)
* [Prisma Config File](/orm/reference/prisma-config-reference)
* [Prisma Postgres](/postgres)

## Related pages

- [`Deno`](https://www.prisma.io/docs/guides/runtimes/deno): Learn how to use Prisma ORM in a Deno application with Prisma Postgres