Loading...
Sign In
Toggle theme
Browse
Prompts
Rules
Directory
AI Prompt | Promptexify
Directory
Vibe Coding
Back
Vibe Coding
Prisma with Astro Integration Setup Guide
Copy Prompt
Share
Prompt:
6825 characters
# Prisma with Astro Integration Setup Guide This guide provides step-by-step instructions for integrating Prisma ORM with an Astro application. ## Prerequisites - Node.js and npm installed - Astro project initialized - PostgreSQL database (or any other supported database) ## Installation 1. Install Prisma and its dependencies: ```bash npm install @prisma/client npm install -D prisma ``` 2. Initialize Prisma in your project: ```bash npx prisma init ``` ## Database Schema 1. Define your schema in `prisma/schema.prisma`: ```prisma datasource db { provider = "postgresql" url = env("DATABASE_URL") } generator client { provider = "prisma-client-js" } model User { id Int @id @default(autoincrement()) email String @unique name String? posts Post[] createdAt DateTime @default(now()) updatedAt DateTime @updatedAt } model Post { id Int @id @default(autoincrement()) title String content String? published Boolean @default(false) author User @relation(fields: [authorId], references: [id]) authorId Int createdAt DateTime @default(now()) updatedAt DateTime @updatedAt } ``` ## Database Client Setup 1. Create a database client file `src/lib/prisma.ts`: ```typescript import { PrismaClient } from '@prisma/client' let prisma: PrismaClient declare global { var prisma: PrismaClient } if (process.env.NODE_ENV === 'production') { prisma = new PrismaClient() } else { if (!global.prisma) { global.prisma = new PrismaClient() } prisma = global.prisma } export { prisma } ``` ## API Endpoints Implementation 1. Create an API endpoint for users `src/pages/api/users/index.ts`: ```typescript import type { APIRoute } from 'astro' import { prisma } from '../../../lib/prisma' export const get: APIRoute = async () => { try { const users = await prisma.user.findMany({ include: { posts: true } }) return new Response(JSON.stringify(users), { status: 200, headers: { 'Content-Type': 'application/json' } }) } catch (error) { return new Response(JSON.stringify({ error: 'Failed to fetch users' }), { status: 500, headers: { 'Content-Type': 'application/json' } }) } } export const post: APIRoute = async ({ request }) => { try { const body = await request.json() const { email, name } = body const user = await prisma.user.create({ data: { email, name }, include: { posts: true } }) return new Response(JSON.stringify(user), { status: 201, headers: { 'Content-Type': 'application/json' } }) } catch (error) { return new Response(JSON.stringify({ error: 'Failed to create user' }), { status: 500, headers: { 'Content-Type': 'application/json' } }) } } ``` 2. Create an API endpoint for posts `src/pages/api/posts/index.ts`: ```typescript import type { APIRoute } from 'astro' import { prisma } from '../../../lib/prisma' export const get: APIRoute = async () => { try { const posts = await prisma.post.findMany({ include: { author: true } }) return new Response(JSON.stringify(posts), { status: 200, headers: { 'Content-Type': 'application/json' } }) } catch (error) { return new Response(JSON.stringify({ error: 'Failed to fetch posts' }), { status: 500, headers: { 'Content-Type': 'application/json' } }) } } export const post: APIRoute = async ({ request }) => { try { const body = await request.json() const { title, content, authorId } = body const post = await prisma.post.create({ data: { title, content, authorId: parseInt(authorId) }, include: { author: true } }) return new Response(JSON.stringify(post), { status: 201, headers: { 'Content-Type': 'application/json' } }) } catch (error) { return new Response(JSON.stringify({ error: 'Failed to create post' }), { status: 500, headers: { 'Content-Type': 'application/json' } }) } } ``` ## Frontend Implementation 1. Create a users page `src/pages/users.astro`: ```astro --- import Layout from '../layouts/Layout.astro' import { prisma } from '../lib/prisma' const users = await prisma.user.findMany({ include: { posts: true } }) --- Users Add User {users.map((user) => ( {user.name} ({user.email}) Delete ))} ``` 2. Create a posts page `src/pages/posts.astro`: ```astro --- import Layout from '../layouts/Layout.astro' import { prisma } from '../lib/prisma' const posts = await prisma.post.findMany({ include: { author: true } }) --- Posts Add Post {posts.map((post) => ( {post.title} {post.published ? 'Unpublish' : 'Publish'} Delete {post.content} By: {post.author.name} ))} ``` ## Environment Setup 1. Create `.env` file: ```env DATABASE_URL="postgresql://user:password@localhost:5432/dbname?schema=public" ``` 2. Add `.env` to `.gitignore`: ``` .env ``` ## Database Migration 1. Generate Prisma Client: ```bash npx prisma generate ``` 2. Create and apply migrations: ```bash npx prisma migrate dev --name init ``` ## Best Practices 1. Database Connection - Use connection pooling in production - Keep environment variables secure - Use migrations for schema changes 2. Error Handling - Implement proper error handling in API routes - Show user-friendly error messages - Log errors for debugging 3. Type Safety - Use TypeScript for better type safety - Leverage Prisma's generated types - Define proper interfaces for data structures 4. Performance - Use proper indexes in schema - Implement pagination for large datasets - Cache frequently accessed data 5. Astro Best Practices - Use server-side rendering when possible - Implement proper client-side hydration - Follow Astro conventions 6. Security - Validate input data - Implement proper authentication - Use prepared statements (handled by Prisma) ## Development Workflow 1. Make schema changes in `schema.prisma` 2. Generate migration: ```bash npx prisma migrate dev --name ``` 3. Update Prisma Client: ```bash npx prisma generate ``` 4. Use Prisma Studio for database management: ```bash npx prisma studio ```
No preview available
By Promptexify
|
7/19/2025
3 views
Related Prompts
Vite and Tailwind CSS v4 Installation Guide
Vibe Coding
12 views
Coding Standards & Rules for React apps with Supabase
Vibe Coding
11 views
Guidelines for writing Next.js apps with Supabase Authentication
Vibe Coding
10 views
ShadCN UI Installation Guide
Vibe Coding
10 views
Prisma with Vue.js Integration Setup Guide
Vibe Coding
10 views
Coding Standards & Rules for Vue 3
Vibe Coding
9 views
Discover More Prompts