Skip to content

Commit 6d0445a

Browse files
committed
DA-5233 Hono Guide Created
1 parent 09ceaf5 commit 6d0445a

File tree

3 files changed

+365
-0
lines changed

3 files changed

+365
-0
lines changed

content/800-guides/390-hono.mdx

Lines changed: 364 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,364 @@
1+
---
2+
title: 'How to use Prisma ORM with Hono'
3+
metaTitle: 'How to use Prisma ORM and Prisma Postgres with Hono'
4+
description: 'Learn how to use Prisma ORM in a Hono app'
5+
sidebar_label: 'Hono'
6+
image: '/img/guides/prisma-hono-cover.png'
7+
completion_time: '15 min'
8+
community_section: true
9+
---
10+
11+
## Introduction
12+
13+
Prisma ORM offers type-safe database access, and [Hono](https://hono.dev/) is built for fast, lightweight web apps. Together with [Prisma Postgres](https://www.prisma.io/postgres), you get a fast, lightweight backend, that can be deployed through Node.js, Cloudflare, or many other runtimes.
14+
15+
In this guide, you'll learn to integrate Prisma ORM with a Prisma Postgres database in a Hono backend application. You can find a complete example of this guide on [GitHub](https://github.com/prisma/prisma-examples/tree/latest/orm/node).
16+
17+
## Prerequisites
18+
- [Node.js 20+](https://nodejs.org)
19+
20+
## 1. Set up your project
21+
22+
Create a new Hono project:
23+
24+
```terminal
25+
npm create hono@latest
26+
```
27+
28+
:::info
29+
- *Target directory?* `my-app`
30+
- *Which template do you want to use?* `nodejs`
31+
- *Install dependencies? (recommended)* `Yes`
32+
- *Do you want to install project dependencies?* `Yes`
33+
- *Which package manager do you want to use?* `npm`
34+
:::
35+
36+
## 2. Install and Configure Prisma
37+
38+
### 2.1. Install dependencies
39+
40+
To get started with Prisma, you'll need to install a few dependencies:
41+
42+
<TabbedContent code>
43+
<TabItem value="Prisma Postgres (recommended)">
44+
```terminal
45+
npm install prisma dotenv --save-dev
46+
npm install @prisma/extension-accelerate @prisma/client
47+
```
48+
</TabItem>
49+
<TabItem value="Other databases">
50+
```terminal
51+
npm install prisma dotenv --save-dev
52+
npm install @prisma/client
53+
```
54+
</TabItem>
55+
</TabbedContent>
56+
57+
Once installed, initialize Prisma in your project:
58+
59+
```terminal
60+
npx prisma init --db --output ../src/generated/prisma
61+
```
62+
:::info
63+
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 Hono Project"
64+
:::
65+
This will create:
66+
67+
- A `prisma/` directory with a `schema.prisma` file
68+
- A `.env` file with a `DATABASE_URL` already set
69+
70+
### 2.2. Define your Prisma Schema
71+
72+
In the `prisma/schema.prisma` file, add the following models and change the generator to use the `prisma-client` provider:
73+
74+
```prisma file=prisma/schema.prisma
75+
generator client {
76+
//edit-next-line
77+
provider = "prisma-client"
78+
engineType = "client"
79+
output = "../src/generated/prisma"
80+
}
81+
82+
datasource db {
83+
provider = "postgresql"
84+
url = env("DATABASE_URL")
85+
}
86+
87+
//add-start
88+
model User {
89+
id Int @id @default(autoincrement())
90+
email String @unique
91+
name String?
92+
posts Post[]
93+
}
94+
95+
model Post {
96+
id Int @id @default(autoincrement())
97+
title String
98+
content String?
99+
published Boolean @default(false)
100+
authorId Int
101+
author User @relation(fields: [authorId], references: [id])
102+
}
103+
//add-end
104+
```
105+
106+
This creates two models: `User` and `Post`, with a one-to-many relationship between them.
107+
108+
### 2.3. Configure the Prisma Client generator
109+
110+
Now, run the following command to create the database tables and generate the Prisma Client:
111+
112+
```terminal
113+
npx prisma migrate dev --name init
114+
```
115+
### 2.4. Seed the database
116+
117+
Let's add some seed data to populate the database with sample users and posts.
118+
119+
Create a new file called `seed.ts` in the `prisma/` directory:
120+
121+
```typescript file=prisma/seed.ts
122+
import { PrismaClient, Prisma } from "../src/generated/prisma/client.js";
123+
124+
const prisma = new PrismaClient();
125+
126+
const userData: Prisma.UserCreateInput[] = [
127+
{
128+
name: "Alice",
129+
email: "alice@prisma.io",
130+
posts: {
131+
create: [
132+
{
133+
title: "Join the Prisma Discord",
134+
content: "https://pris.ly/discord",
135+
published: true,
136+
},
137+
{
138+
title: "Prisma on YouTube",
139+
content: "https://pris.ly/youtube",
140+
},
141+
],
142+
},
143+
},
144+
{
145+
name: "Bob",
146+
email: "bob@prisma.io",
147+
posts: {
148+
create: [
149+
{
150+
title: "Follow Prisma on Twitter",
151+
content: "https://www.twitter.com/prisma",
152+
published: true,
153+
},
154+
],
155+
},
156+
},
157+
];
158+
159+
export async function main() {
160+
for (const u of userData) {
161+
await prisma.user.create({ data: u });
162+
}
163+
}
164+
165+
main()
166+
.catch((e) => {
167+
console.error(e);
168+
process.exit(1);
169+
})
170+
.finally(async () => {
171+
await prisma.$disconnect();
172+
});
173+
```
174+
175+
Now, tell Prisma how to run this script by updating your `package.json`:
176+
177+
```json file=package.json
178+
{
179+
"name": "my-app",
180+
"type": "module",
181+
"scripts": {
182+
"dev": "tsx watch src/index.ts",
183+
"build": "tsc",
184+
"start": "node dist/index.js"
185+
},
186+
//add-start
187+
"prisma": {
188+
"seed": "tsx prisma/seed.ts"
189+
},
190+
//add-end
191+
"dependencies": {
192+
"@hono/node-server": "^1.19.5",
193+
"@prisma/client": "^6.16.3",
194+
"@prisma/extension-accelerate": "^2.0.2",
195+
"dotenv": "^17.2.3",
196+
"hono": "^4.9.9"
197+
},
198+
"devDependencies": {
199+
"@types/node": "^20.11.17",
200+
"prisma": "^6.16.3",
201+
"tsx": "^4.20.6",
202+
"typescript": "^5.8.3"
203+
}
204+
}
205+
```
206+
207+
Run the seed script:
208+
209+
```terminal
210+
npx prisma db seed
211+
```
212+
213+
And open Prisma Studio to inspect your data:
214+
215+
```terminal
216+
npx prisma studio
217+
```
218+
219+
## 3. Integrate Prisma Into Hono
220+
221+
### 3.1. Create a Prisma Middleware
222+
223+
Inside of `/src`, create a `lib` directory and a `prisma.ts` file inside it. This file will be used to create and export your Prisma Client instance. Set up the Prisma client like this:
224+
225+
<TabbedContent code>
226+
<TabItem value="Prisma Postgres (recommended)">
227+
```tsx file=src/lib/prisma.ts
228+
import type { Context, Next } from 'hono';
229+
import { PrismaClient } from '../generated/prisma/client.js';
230+
import { withAccelerate } from '@prisma/extension-accelerate';
231+
232+
function withPrisma(c: Context, next: Next) {
233+
if (!c.get('prisma')) {
234+
const databaseUrl = process.env.DATABASE_URL;
235+
236+
if (!databaseUrl) {
237+
throw new Error('DATABASE_URL is not set');
238+
}
239+
const prisma = new PrismaClient({ datasourceUrl: databaseUrl })
240+
.$extends(withAccelerate());
241+
242+
c.set('prisma', prisma);
243+
}
244+
return next();
245+
}
246+
export default withPrisma;
247+
```
248+
</TabItem>
249+
250+
<TabItem value="Other databases">
251+
```tsx file=src/lib/prisma.ts
252+
import type { Context, Next } from 'hono';
253+
import { PrismaClient } from '../generated/prisma/client.js';
254+
255+
function withPrisma(c: Context, next: Next) {
256+
if (!c.get('prisma')) {
257+
const databaseUrl = process.env.DATABASE_URL;
258+
259+
if (!databaseUrl) {
260+
throw new Error('DATABASE_URL is not set');
261+
}
262+
const prisma = new PrismaClient({ datasourceUrl: databaseUrl })
263+
264+
c.set('prisma', prisma);
265+
}
266+
return next();
267+
}
268+
export default withPrisma;
269+
```
270+
</TabItem>
271+
</TabbedContent>
272+
273+
:::warning
274+
We recommend using a connection pooler (like [Prisma Accelerate](https://www.prisma.io/accelerate)) to manage database connections efficiently.
275+
276+
If you choose not to use one, **avoid** instantiating `PrismaClient` globally in long-lived environments. Instead, create and dispose of the client per request to prevent exhausting your database connections.
277+
:::
278+
279+
### 3.2 Environment Variables & Types
280+
281+
By default, Hono does not load any environment variables from a `.env`. `dotenv` handles this and
282+
will be read that file and expose them via `process.env`.
283+
284+
Edit the `src/index.ts` to import `dotenv` and call the `config` method on it.
285+
286+
```ts file=src/index.ts
287+
import { Hono } from 'hono';
288+
import { serve } from '@hono/node-server';
289+
290+
// Read .env and set variables to process.env
291+
import * as dotenv from 'dotenv';
292+
dotenv.config();
293+
```
294+
295+
Next, Hono needs additional types to to know that the `withPrisma` middleware will set a `prsima`
296+
key on the Hono Context
297+
298+
```ts file=src/index.ts
299+
import type { PrismaClient } from './generated/prisma/client.js';
300+
301+
type ContextWithPrisma = {
302+
Variables: {
303+
prisma: PrismaClient;
304+
};
305+
};
306+
307+
const app = new Hono<ContextWithPrisma>();
308+
```
309+
310+
311+
### 3.3. Create A GET Route
312+
313+
Fetch data from the database using Hono's `app.get` function. This will perform any database queries
314+
and return the data as JSON.
315+
316+
Create a new route inside of `src/index.ts`:
317+
318+
Now, create a GET route that fetches the `Users` data from your database, making sure to include each user's `Posts` by adding them to the `include` field:
319+
320+
```ts file=src/index.ts
321+
import withPrisma from './lib/prisma.js';
322+
323+
app.get('/users', withPrisma, async (c) => {
324+
const prisma = c.get('prisma');
325+
const users = await prisma.user.findMany({
326+
include: { posts: true },
327+
});
328+
return c.json({ users });
329+
});
330+
```
331+
332+
333+
### 3.4. Display The Data
334+
335+
Start the Hono app by call the `dev` script in the `package.json`
336+
337+
```terminal
338+
npm run dev
339+
```
340+
341+
There should be a "Server is running on http://localhost:3000" log printed out. From here, the data
342+
can be viewed by visting `http://localhost:3000/users` or by running `curl` from the command line
343+
344+
```terminal
345+
curl http://localhost:3000/users | jq
346+
```
347+
348+
You're done! You've created a Hono app with Prisma that's connected to a Prisma Postgres database.
349+
For next steps there are some resources below for you to explore as well as next steps for expanding
350+
your project.
351+
352+
## Next Steps
353+
354+
Now that you have a working Hono app connected to a Prisma Postgres database, you can:
355+
356+
- Extend your Prisma schema with more models and relationships
357+
- Add create/update/delete routes and forms
358+
- Explore authentication and validation
359+
- Enable query caching with [Prisma Postgres](/postgres/database/caching) for better performance
360+
361+
### More Info
362+
363+
- [Prisma Documentation](/orm/overview/introduction)
364+
- [Hono Documentation](https://hono.dev/docs/)

sidebars.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -418,6 +418,7 @@ const sidebars: SidebarsConfig = {
418418
"guides/nuxt",
419419
"guides/sveltekit",
420420
"guides/astro",
421+
"guides/hono",
421422
"guides/solid-start",
422423
"guides/react-router-7",
423424
"guides/tanstack-start",
390 KB
Loading

0 commit comments

Comments
 (0)