PostgreSQL (Prisma)
developer-ready Express.js and Prisma ORM integration for PostgreSQL with modular REST APIs, CRUD-ready schema, and fully extensible data access layer.
Overview
A scalable PostgreSQL database integration built with Prisma ORM and Express.js. It provides a clean REST API for data access, automatic schema migrations, and modular service layers for rapid backend development.
Installation
What This Does
Installs a Prisma + Express setup with a connected PostgreSQL schema and modular routes for data operations.
Files & Folders Created
| File / Path | Description |
|---|---|
| /prisma/schema.prisma | Prisma schema with a sample User model |
| /src/config/prismaClient.js | Initializes Prisma client |
| /src/services/userService.js | Handles Prisma data operations (CRUD) |
| /src/routes/user.js | Express routes for user endpoints |
| /server.js.example | Example Express server |
| /.env.example | Environment configuration for PostgreSQL |
Files to be modified
| File / Path | Description |
|---|---|
| server.js | Adds /api/user route integration |
| .env | Adds DATABASE_URL configuration |
Configuration
# Database Configuration DATABASE_URL=postgresql://USER:PASSWORD@HOST:PORT/DATABASE?schema=public PORT=8000
Frontend Integration
This frontend example shows how to interact with the Prisma + PostgreSQL backend API endpoints to create and view users. It demonstrates dynamic data fetching, form handling, and live updates using Next.js.
Fetches all users stored in the PostgreSQL database via Prisma.
Creates a new user record in the database.
Fetches a single user by ID.
Example
1// app/components/PrismaUserManager.jsx
2'use client';
3import { useState, useEffect } from 'react';
4
5export default function PrismaUserManager() {
6 const [users, setUsers] = useState([]);
7 const [form, setForm] = useState({ name: '', email: '' });
8 const [loading, setLoading] = useState(false);
9 const [message, setMessage] = useState('');
10
11 async function fetchUsers() {
12 try {
13 const res = await fetch('/api/user');
14 const data = await res.json();
15 if (data.success) setUsers(data.users);
16 } catch (err) {
17 console.error('Failed to fetch users:', err);
18 }
19 }
20
21 useEffect(() => {
22 fetchUsers();
23 }, []);
24
25 async function handleSubmit(e) {
26 e.preventDefault();
27 setLoading(true);
28 setMessage('');
29
30 try {
31 const res = await fetch('/api/user', {
32 method: 'POST',
33 headers: { 'Content-Type': 'application/json' },
34 body: JSON.stringify(form)
35 });
36 const data = await res.json();
37
38 if (res.ok && data.success) {
39 setMessage('✅ User created successfully');
40 setForm({ name: '', email: '' });
41 fetchUsers();
42 } else {
43 setMessage('❌ ' + (data.error || 'Error creating user'));
44 }
45 } catch (error) {
46 setMessage('Error: ' + error.message);
47 } finally {
48 setLoading(false);
49 }
50 }
51
52 return (
53 <div className="max-w-md mx-auto bg-black/20 border border-white/10 rounded-xl p-6 text-white space-y-5">
54 <h2 className="text-xl font-semibold">PostgreSQL + Prisma User Manager</h2>
55
56 <form onSubmit={handleSubmit} className="space-y-3">
57 <input
58 type="text"
59 placeholder="Name"
60 value={form.name}
61 onChange={(e) => setForm({ ...form, name: e.target.value })}
62 className="w-full px-3 py-2 rounded-md bg-white/10 border border-white/20 focus:outline-none"
63 required
64 />
65 <input
66 type="email"
67 placeholder="Email"
68 value={form.email}
69 onChange={(e) => setForm({ ...form, email: e.target.value })}
70 className="w-full px-3 py-2 rounded-md bg-white/10 border border-white/20 focus:outline-none"
71 required
72 />
73 <button
74 type="submit"
75 disabled={loading}
76 className="w-full bg-emerald-500 hover:bg-emerald-600 text-white font-semibold py-2 rounded-md transition-colors"
77 >
78 {loading ? 'Creating...' : 'Add User'}
79 </button>
80 </form>
81
82 {message && <p className="text-sm text-amber-300">{message}</p>}
83
84 <div className="space-y-2">
85 <h3 className="text-lg font-semibold border-b border-white/10 pb-1">All Users</h3>
86 <ul className="divide-y divide-white/10">
87 {users.length > 0 ? (
88 users.map((u) => (
89 <li key={u.id} className="py-2 flex justify-between">
90 <span>{u.name}</span>
91 <span className="text-white/70 text-sm">{u.email}</span>
92 </li>
93 ))
94 ) : (
95 <li className="text-sm text-white/50">No users found.</li>
96 )}
97 </ul>
98 </div>
99 </div>
100 );
101}Usage
1// Example server-side usage
2const { getUsers, createUser, getUserById } = require('./src/services/userService');
3
4(async () => {
5 const newUser = await createUser({ name: 'John Doe', email: 'john@example.com' });
6 console.log('Created user:', newUser);
7
8 const users = await getUsers();
9 console.log('All users:', users);
10})();