-
Notifications
You must be signed in to change notification settings - Fork 988
feat: add bun guide #7092
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+331
−0
Merged
feat: add bun guide #7092
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
5479912
feat: add bun guide
ankur-arch 41da55e
Optimised images with calibre/image-actions
github-actions[bot] 0342ee5
Merge branch 'main' into DC-4955
ankur-arch 9c380e9
Optimised images with calibre/image-actions
github-actions[bot] 7ad5a09
Update content/800-guides/370-bun.mdx
ankur-arch ea51c63
Optimised images with calibre/image-actions
github-actions[bot] 5b18660
fix: change image name
ankur-arch 1999d7d
fix: numbering of thesections
ankur-arch 11ea75c
fix: internal link
ankur-arch File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,330 @@ | ||
| --- | ||
| title: 'How to use Prisma ORM in Bun' | ||
| metaTitle: 'How to use Prisma ORM and Prisma Postgres with Bun' | ||
| description: 'Learn how to use Prisma ORM in a Bun application with driver adapters and Prisma Postgres' | ||
| sidebar_label: 'Bun' | ||
| image: '/img/guides/prisma-bun-cover-image.png' | ||
| completion_time: '10 min' | ||
| community_section: true | ||
| --- | ||
|
|
||
| ## 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 configure Prisma driver adapters, create a simple HTTP server, and build a Bun executable for deployment. | ||
|
|
||
| ## 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 | ||
|
|
||
| First, create a directory for your project and navigate to it: | ||
|
|
||
| ```terminal | ||
| mkdir bun-prisma | ||
| cd bun-prisma | ||
| ``` | ||
|
|
||
| Then, initialise a new Bun project: | ||
|
|
||
| ```terminal | ||
| 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.1. Install dependencies | ||
|
|
||
| Install the required Prisma packages and other dependencies: | ||
|
|
||
| ```terminal | ||
| bun add -d prisma | ||
| bun add @prisma/client @prisma/adapter-pg dotenv | ||
| ``` | ||
|
|
||
| ### 2.2. Initialize Prisma ORM with Prisma Postgres | ||
|
|
||
| Initialize Prisma ORM with Prisma Postgres in your project: | ||
|
|
||
| ```terminal | ||
| bun prisma init --db | ||
| ``` | ||
|
ankur-arch marked this conversation as resolved.
|
||
|
|
||
| :::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: | ||
|
|
||
| - A `prisma/` directory with your `schema.prisma` file | ||
| - A new Prisma Postgres database | ||
| - A `.env` file with your `DATABASE_URL` | ||
|
|
||
| ### 2.3. Configure environment variables for driver adapters | ||
|
|
||
| We are going to use the [`node-postgres` driver adapter](/orm/overview/databases/postgresql#using-the-node-postgres-driver) to perform queries to our database. | ||
|
|
||
| When using the `node-postgres` driver adapter with Prisma Postgres, you need to add a `DIRECT_URL` environment variable. This provides a direct connection to your PostgreSQL database. | ||
|
|
||
| To get your [direct connection string](/postgres/database/direct-connections#how-to-connect-to-prisma-postgres-via-direct-tcp): | ||
|
|
||
| 1. Navigate to your recently created Prisma Postgres project dashboard (e.g. "My Bun Project") | ||
| 2. Click the **API Keys** tab in the project's sidebar | ||
| 3. Click the **Create API key** button | ||
| 4. Provide a name for the API key and click **Create** | ||
| 5. Copy the connection string starting with `postgres://` | ||
|
|
||
| Update your `.env` file to include both URLs: | ||
|
|
||
| ```env file=.env | ||
| DATABASE_URL="your_database_url_here" | ||
| //add-start | ||
| DIRECT_URL="your_direct_connection_string_here" | ||
| //add-end | ||
| ``` | ||
|
ankur-arch marked this conversation as resolved.
|
||
|
|
||
| ### 2.4. Update your Prisma schema | ||
|
|
||
| Open `prisma/schema.prisma` and update it to use driver adapters with Bun runtime: | ||
|
|
||
| ```prisma file=prisma/schema.prisma | ||
| generator client { | ||
| //delete-start | ||
| provider = "prisma-client-js" | ||
| //delete-end | ||
| //add-start | ||
| provider = "prisma-client" | ||
| //add-end | ||
| output = "../generated/prisma" | ||
| //add-start | ||
| previewFeatures = ["driverAdapters", "queryCompiler"] | ||
| runtime = "bun" | ||
| //add-end | ||
| } | ||
|
|
||
| datasource db { | ||
| provider = "postgresql" | ||
| url = env("DATABASE_URL") | ||
| } | ||
|
|
||
| //add-start | ||
| model User { | ||
| id Int @id @default(autoincrement()) | ||
| email String @unique | ||
| name String? | ||
| } | ||
| //add-end | ||
| ``` | ||
|
|
||
| ## 3. Setting up database configuration and creating a seed script | ||
|
|
||
| ### 3.1. Create a database utility file | ||
|
|
||
| Create a `db.ts` file in your project root to configure `PrismaClient` with the `node-postgres` adapter: | ||
|
|
||
| ```typescript file=db.ts | ||
| import "dotenv/config"; | ||
| import { PrismaClient } from "./generated/prisma/client"; | ||
| import { PrismaPg } from "@prisma/adapter-pg"; | ||
|
|
||
| const connectionString = `${process.env.DIRECT_URL}`; | ||
|
|
||
| const adapter = new PrismaPg({ connectionString }); | ||
|
|
||
| export const prisma = new PrismaClient({ adapter }); | ||
| ``` | ||
|
ankur-arch marked this conversation as resolved.
|
||
|
|
||
| ### 3.2. Create a seed script | ||
|
|
||
| Create a seed script in the `prisma` folder to populate your database with sample data: | ||
|
|
||
| ```typescript file=prisma/seed.ts | ||
| import { PrismaClient } from "../generated/prisma/client"; | ||
|
|
||
| const prisma = new PrismaClient(); | ||
|
|
||
|
ankur-arch marked this conversation as resolved.
|
||
| 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. Create Prisma Config file to run the seed script | ||
|
|
||
| Create a [`prisma.config.ts` file](/orm/reference/prisma-config-reference#migrationsseed) to configure Prisma's seed command: | ||
|
|
||
| ```terminal | ||
| touch prisma.config.ts | ||
| ``` | ||
|
|
||
| Then add the following content to the file: | ||
|
|
||
| ```typescript file=prisma.config.ts | ||
| import 'dotenv/config' | ||
| import { defineConfig } from 'prisma/config' | ||
|
|
||
| export default defineConfig({ | ||
| migrations: { | ||
| seed: `bun run prisma/seed.ts`, | ||
| }, | ||
| }) | ||
| ``` | ||
|
|
||
| ## 4. Generate Prisma client and run migrations | ||
|
|
||
| Generate the Prisma client and apply your schema to the database: | ||
|
|
||
| ```terminal | ||
| bun prisma migrate dev --name init | ||
| ``` | ||
|
|
||
| This command: | ||
|
|
||
| - Creates the database tables based on your schema | ||
| - Generates the Prisma client in the `generated/prisma` directory | ||
|
|
||
| Because you are using the `node-postgres` driver adapter, you will need to generate the `PrismaClient` again. The client automatically produced by `migrate dev` is optimized for Prisma Postgres, but the adapter requires a client built specifically for the driver: | ||
|
|
||
| ```terminal | ||
| bun prisma generate | ||
| ``` | ||
|
|
||
| Run the seed script to populate your database: | ||
|
ankur-arch marked this conversation as resolved.
|
||
|
|
||
| ```terminal | ||
| bun prisma db seed | ||
| ``` | ||
|
|
||
| ## 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 file=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 | ||
|
|
||
| Start your Bun server: | ||
|
|
||
| ```terminal | ||
| 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 | ||
|
|
||
| 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 | ||
|
|
||
| Build your application into an executable: | ||
|
|
||
| ```terminal | ||
| 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 | ||
|
|
||
| Run the compiled executable: | ||
|
|
||
| ```terminal | ||
| ./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 | ||
|
|
||
| You can explore the [sample app here](https://pris.ly/bun-guide-example) to see what you will build by following this guide. If you would like to add caching to your application, check out [this example](https://pris.ly/bun_ppg_example). | ||
|
|
||
| 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 | ||
|
|
||
| - [Bun Documentation](https://bun.sh/docs) | ||
| - [Prisma Driver Adapters](/orm/overview/databases/database-drivers) | ||
| - [Prisma Config File](/orm/reference/prisma-config-reference) | ||
| - [Prisma Client without the Rust engine](/orm/prisma-client/setup-and-configuration/no-rust-engine) | ||
| - [Prisma Postgres](/postgres) | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.