How to Use Prisma with Express: Simple Setup and Example
To use
Prisma with Express, first install Prisma and set up your database schema. Then, create a Prisma client instance and use it inside your Express route handlers to query or modify your database asynchronously.Syntax
Here is the basic syntax to use Prisma with Express:
- Import
PrismaClientfrom@prisma/client. - Create a new Prisma client instance.
- Use async functions in Express routes to call Prisma methods.
- Send the query results as responses.
javascript
import express from 'express'; import { PrismaClient } from '@prisma/client'; const app = express(); const prisma = new PrismaClient(); app.get('/items', async (req, res) => { const items = await prisma.item.findMany(); res.json(items); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Example
This example shows a simple Express server using Prisma to fetch all records from an item table in the database. It demonstrates how to initialize Prisma, define a route, and send JSON data back to the client.
javascript
import express from 'express'; import { PrismaClient } from '@prisma/client'; const app = express(); const prisma = new PrismaClient(); app.get('/items', async (req, res) => { try { const items = await prisma.item.findMany(); res.json(items); } catch (error) { res.status(500).json({ error: 'Failed to fetch items' }); } }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Output
Server running on http://localhost:3000
// When visiting http://localhost:3000/items, JSON array of items is returned
Common Pitfalls
Common mistakes when using Prisma with Express include:
- Not awaiting Prisma calls, causing unresolved promises.
- Not handling errors inside async route handlers.
- Forgetting to instantiate
PrismaClientonce and reusing it. - Not running
prisma generateafter schema changes.
Always use async/await and try-catch blocks to handle database calls safely.
javascript
/* Wrong way: Missing await and error handling */ app.get('/items', (req, res) => { const items = prisma.item.findMany(); // Missing await res.json(items); // Sends a Promise, not data }); /* Right way: Using async/await and try-catch */ app.get('/items', async (req, res) => { try { const items = await prisma.item.findMany(); res.json(items); } catch (error) { res.status(500).json({ error: 'Failed to fetch items' }); } });
Quick Reference
Tips for using Prisma with Express:
- Install Prisma with
npm install @prisma/clientandnpm install prisma --save-dev. - Run
npx prisma initto set up Prisma. - Define your database schema in
prisma/schema.prisma. - Run
npx prisma generateafter schema changes. - Use one
PrismaClientinstance per app to avoid connection issues. - Always use async/await and handle errors in routes.
Key Takeaways
Create a single PrismaClient instance and reuse it in Express routes.
Use async/await with try-catch to handle database calls safely.
Run prisma generate after changing your schema to update the client.
Always await Prisma queries to get actual data, not promises.
Handle errors gracefully to avoid crashing your Express server.