Skip to content

Commit 7397e67

Browse files
committed
DA-5233 Hono Guide Created
1 parent 09ceaf5 commit 7397e67

File tree

2 files changed

+365
-0
lines changed

2 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-astro-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 tsx --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+
output = "../src/generated/prisma"
79+
}
80+
81+
datasource db {
82+
provider = "postgresql"
83+
url = env("DATABASE_URL")
84+
}
85+
86+
//add-start
87+
model User {
88+
id Int @id @default(autoincrement())
89+
email String @unique
90+
name String?
91+
posts Post[]
92+
}
93+
94+
model Post {
95+
id Int @id @default(autoincrement())
96+
title String
97+
content String?
98+
published Boolean @default(false)
99+
authorId Int
100+
author User @relation(fields: [authorId], references: [id])
101+
}
102+
//add-end
103+
```
104+
105+
This creates two models: `User` and `Post`, with a one-to-many relationship between them.
106+
107+
### 2.3. Configure the Prisma Client generator
108+
109+
Now, run the following command to create the database tables and generate the Prisma Client:
110+
111+
```terminal
112+
npx prisma migrate dev --name init
113+
```
114+
### 2.4. Seed the database
115+
116+
Let's add some seed data to populate the database with sample users and posts.
117+
118+
Create a new file called `seed.ts` in the `prisma/` directory:
119+
120+
```typescript file=prisma/seed.ts
121+
import { PrismaClient, Prisma } from "../src/generated/prisma/client.js";
122+
123+
const prisma = new PrismaClient();
124+
125+
const userData: Prisma.UserCreateInput[] = [
126+
{
127+
name: "Alice",
128+
129+
posts: {
130+
create: [
131+
{
132+
title: "Join the Prisma Discord",
133+
content: "https://pris.ly/discord",
134+
published: true,
135+
},
136+
{
137+
title: "Prisma on YouTube",
138+
content: "https://pris.ly/youtube",
139+
},
140+
],
141+
},
142+
},
143+
{
144+
name: "Bob",
145+
146+
posts: {
147+
create: [
148+
{
149+
title: "Follow Prisma on Twitter",
150+
content: "https://www.twitter.com/prisma",
151+
published: true,
152+
},
153+
],
154+
},
155+
},
156+
];
157+
158+
export async function main() {
159+
for (const u of userData) {
160+
await prisma.user.create({ data: u });
161+
}
162+
}
163+
164+
main();
165+
```
166+
167+
Now, tell Prisma how to run this script by updating your `package.json`:
168+
169+
```json file=package.json
170+
{
171+
"name": "my-app",
172+
"type": "module",
173+
"scripts": {
174+
"dev": "tsx watch src/index.ts",
175+
"build": "tsc",
176+
"start": "node dist/index.js"
177+
},
178+
//add-start
179+
"prisma": {
180+
"seed": "tsx prisma/seed.ts"
181+
},
182+
//add-end
183+
"dependencies": {
184+
"@hono/node-server": "^1.19.5",
185+
"@prisma/client": "^6.16.3",
186+
"@prisma/extension-accelerate": "^2.0.2",
187+
"dotenv": "^17.2.3",
188+
"hono": "^4.9.9"
189+
},
190+
"devDependencies": {
191+
"@types/node": "^20.11.17",
192+
"prisma": "^6.16.3",
193+
"tsx": "^4.20.6",
194+
"typescript": "^5.8.3"
195+
}
196+
}
197+
```
198+
199+
Run the seed script:
200+
201+
```terminal
202+
npx prisma db seed
203+
```
204+
205+
And open Prisma Studio to inspect your data:
206+
207+
```terminal
208+
npx prisma studio
209+
```
210+
211+
## 3. Integrate Prisma Into Hono
212+
213+
### 3.1. Create a Prisma Middleware
214+
215+
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.
216+
217+
```terminal
218+
mkdir src/lib
219+
touch src/lib/prisma.ts
220+
```
221+
222+
223+
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 Astro 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",

0 commit comments

Comments
 (0)