如何在 Next.js 应用中嵌入 Prisma Studio
可以使用 @prisma/studio-core
包将 Prisma Studio 直接嵌入到你的 Next.js 应用中。本指南将引导你完成设置,以便你可以从应用内部管理数据库,而无需单独运行 Prisma Studio。
¥Prisma Studio can be embedded directly into your Next.js application using the @prisma/studio-core
package. This guide walks you through the setup so you can manage your database from within your app instead of running Prisma Studio separately.
完成本指南后,你将拥有一个嵌入 Prisma Studio 的 Next.js 应用,允许你直接从应用界面浏览和编辑数据库:
¥After completing the guide, you'll have a Next.js app with Prisma Studio embedded, allowing you to browse and edit your database directly from your application interface:
嵌入式 Prisma Studio 在以下场景中非常有用:
¥Embedding Prisma Studio can be useful in scenarios such as:
-
构建用于编辑数据的快速管理仪表板
¥Building a quick admin dashboard for editing data
-
支持多租户应用,每个用户都有自己的数据库
¥Supporting multi-tenant applications where each user has their own database
-
方便用户查看和编辑数据
¥Giving users an easy way to view and edit their data
可嵌入的 Prisma Studio 是免费的,并遵循 Apache 2.0 许可。
¥Embeddable Prisma Studio is free and licensed under Apache 2.0.
✔️ 可在生产环境中免费使用 ⚠️ Prisma 品牌标识必须保持可见且不变 🔐 如需移除品牌标识或了解即将推出的仅限合作伙伴的功能,请联系 partnerships@prisma.io
¥✔️ Free to use in production ⚠️ Prisma branding must remain visible and unchanged 🔐 To remove branding or learn about upcoming partner-only features, reach out at partnerships@prisma.io
目前,嵌入式 Prisma Studio 支持 Prisma Postgres,更多数据库即将推出。
¥Currently, Embedded Prisma Studio supports Prisma Postgres, with additional databases coming soon.
先决条件
¥Prerequisites
-
React 和 Next.js 的基础知识
¥Basic knowledge of React and Next.js
-
Prisma Postgres 数据库
¥A Prisma Postgres database
1. 设置 Next.js
¥ Setting up Next.js
首先,在你要构建应用的目录中创建一个新的 Next.js 项目:
¥First, create a new Next.js project from the directory where you want to build your app:
npx create-next-app@latest nextjs-studio-embed
系统将提示你回答一些关于你项目的问题。选择所有默认值。
¥You will be prompted to answer a few questions about your project. Select all of the defaults.
作为参考,这些是:
¥For reference, those are:
-
TypeScript
-
ESLint
-
Tailwind CSS
-
无
src
目录¥No
src
directory -
应用路由
¥App Router
-
Turbopack
-
选择默认导入别名
¥Select default import alias
然后,导航到项目目录:
¥Then, navigate to the project directory:
cd nextjs-studio-embed
2. 设置 Prisma ORM 和 Prisma Postgres
¥ Setting up Prisma ORM and Prisma Postgres
2.1.安装 Prisma 依赖
¥2.1. Install Prisma dependencies
安装所需的 Prisma 包:
¥Install the required Prisma packages:
npm install prisma tsx --save-dev
npm install @prisma/extension-accelerate @prisma/client
2.2.使用 Prisma Postgres 初始化 Prisma
¥2.2. Initialize Prisma with Prisma Postgres
在你的项目中初始化 Prisma 并创建一个 Prisma Postgres 数据库:
¥Initialize Prisma in your project and create a Prisma Postgres database:
npx prisma init --db --output ../app/generated/prisma
在设置 Prisma Postgres 数据库时,你需要回答几个问题。选择离你最近的区域,并为数据库选择一个容易记住的名称,例如 "我的 __________ 项目"
¥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 __________ Project"
prisma init --db
命令创建:
¥The prisma init --db
command creates:
-
包含你的
schema.prisma
文件的prisma/
目录¥A
prisma/
directory with yourschema.prisma
file -
一个新的 Prisma Postgres 数据库
¥A new Prisma Postgres database
-
包含你的
DATABASE_URL
文件的.env
文件¥A
.env
file with yourDATABASE_URL
-
Prisma 客户端在
app/generated/prisma
的输出目录¥An output directory at
app/generated/prisma
for the Prisma Client
2.3.定义数据库模式
¥2.3. Define your database schema
打开 prisma/schema.prisma
文件并将内容替换为:
¥Open prisma/schema.prisma
and replace the content with:
generator client {
provider = "prisma-client-js"
output = "../app/generated/prisma"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model User {
id Int @id @default(autoincrement())
name String
email String @unique
posts Post[]
}
model Post {
id Int @id @default(autoincrement())
title String
content String?
published Boolean @default(false)
authorId Int
author User @relation(fields: [authorId], references: [id])
createdAt DateTime @default(now())
}
2.4.将模式应用到你的数据库
¥2.4. Apply the schema to your database
生成 Prisma 客户端并应用架构:
¥Generate the Prisma Client and apply the schema:
npx prisma migrate dev --name init
这将在你的 Prisma Postgres 数据库中创建表并生成 Prisma 客户端。
¥This creates the tables in your Prisma Postgres database and generates the Prisma Client.
2.5.为数据库填充种子(可选)
¥2.5. Seed your database (optional)
创建一个种子文件,用于添加一些示例数据。在 prisma
文件夹中创建一个 seed.ts
文件并添加以下代码:
¥Create a seed file to add some sample data. Create a seed.ts
file in the prisma
folder and add the following code:
import { PrismaClient } from '../app/generated/prisma'
const prisma = new PrismaClient()
async function main() {
// Create users
const user1 = await prisma.user.create({
data: {
name: 'Alice Johnson',
email: 'alice@example.com',
},
})
const user2 = await prisma.user.create({
data: {
name: 'Bob Smith',
email: 'bob@example.com',
},
})
// Create posts
await prisma.post.create({
data: {
title: 'Getting Started with Next.js',
content: 'Next.js is a powerful React framework...',
published: true,
authorId: user1.id,
},
})
await prisma.post.create({
data: {
title: 'Database Management with Prisma',
content: 'Prisma makes database management easy...',
published: false,
authorId: user2.id,
},
})
console.log('Database seeded successfully!')
}
main()
.catch((e) => {
console.error(e)
process.exit(1)
})
.finally(async () => {
await prisma.$disconnect()
})
向你的 package.json
文件添加种子脚本:
¥Add a seed script to your package.json
:
{
"name": "nextjs-studio-embed",
"version": "0.1.0",
"private": true,
"prisma": {
"seed": "tsx prisma/seed.ts"
},
"scripts": {
// ... existing scripts
}
// ... rest of package.json
}
运行种子脚本:
¥Run the seed script:
npx prisma db seed
3. 在你的应用中设置嵌入式 Prisma Studio
¥ Setting up the embedded Prisma Studio in your app
现在你已经设置好了 Prisma ORM 和 Prisma Postgres,你可以将 Prisma Studio 嵌入到你的 Next.js 应用中。
¥Now that you have Prisma ORM and Prisma Postgres set up, you can embed Prisma Studio in your Next.js app.
3.1.安装 Prisma Studio Core 包
¥3.1. Install the Prisma Studio Core package
安装提供可嵌入组件的 @prisma/studio-core
包:
¥Install the @prisma/studio-core
package that provides the embeddable components:
npm install @prisma/studio-core
如果你在安装 @prisma/studio-core
时遇到依赖解析错误,可以使用以下方法强制安装:
¥If you encounter a dependency resolution error while installing @prisma/studio-core
, you can force the install with:
npm install @prisma/studio-core --force
如果你正在使用 yarn、pnpm 或其他包管理器,请使用与你的工具对应的等效标志。
¥If you are using yarn, pnpm, or another package manager, use the equivalent flag for your tool.
@prisma/studio-core
提供了 Studio
,这是一个 React 组件,用于为你的数据库渲染 Prisma Studio。Studio
组件接受一个执行器,该执行器访问你后端的自定义端点。后端使用你的 API 密钥来识别正确的 Prisma Postgres 实例并向其发送 SQL 查询。
¥The @prisma/studio-core
provides Studio
, a React component which renders Prisma Studio for your database. The Studio
component accepts an executor which accesses a custom endpoint in your backend. The backend uses your API key to identify the correct Prisma Postgres instance and sends the SQL query to it.
3.2.创建 Studio 封装器组件
¥3.2. Create a Studio wrapper component
创建一个 components
文件夹并添加一个名为 StudioWrapper.tsx
的新文件。此文件将封装 Studio 组件并提供一致的布局:
¥Create a components
folder and add a new file called StudioWrapper.tsx
. This file will wrap the Studio component and provide a consistent layout:
'use client';
import "@prisma/studio-core/ui/index.css";
import { ReactNode } from 'react';
interface StudioWrapperProps {
children: ReactNode;
}
export default function StudioWrapper({ children }: StudioWrapperProps) {
return (
<div className="min-h-screen bg-gray-50">
<header className="bg-white shadow-sm border-b">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div className="flex justify-between items-center py-4">
<h1 className="text-2xl font-bold text-gray-900">
Database Studio
</h1>
<div className="text-sm text-gray-500">
Powered by Prisma Studio
</div>
</div>
</div>
</header>
<main className="max-w-7xl mx-auto">
<div className="h-[calc(100vh-80px)]">
{children}
</div>
</main>
</div>
);
}
3.3.创建 API 端点以将 SQL 查询发送到 Prisma Studio
¥3.3. Create an API endpoint to send the SQL queries to Prisma Studio
接下来,设置 Prisma Studio 可以与之通信的后端端点。此端点从嵌入式 Studio UI 接收 SQL 查询,将其转发到你的 Prisma Postgres 数据库,然后将结果(或错误)返回到前端。
¥Next, set up a backend endpoint that Prisma Studio can communicate with. This endpoint receives SQL queries from the embedded Studio UI, forwards them to your Prisma Postgres database, and then returns the results (or errors) back to the frontend.
为此,请在 app
目录中创建一个名为 api
的新文件夹。在其中,添加一个 studio
文件夹和一个 route.ts
文件。此文件将处理发送到 /api/studio
的所有请求,并充当前端 Studio 组件和后端数据库之间的桥梁:
¥To do this, create a new folder called api
inside the app
directory. Inside it, add a studio
folder with a route.ts
file. This file will handle all requests sent to /api/studio
and act as the bridge between the Studio component in your frontend and the database in your backend:
import { createPrismaPostgresHttpClient } from "@prisma/studio-core/data/ppg";
import { serializeError } from "@prisma/studio-core/data/bff";
const CORS_HEADERS = {
"Access-Control-Allow-Origin": "*", // Change to your domain in production
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization",
};
// Use dynamic rendering for database operations
export const dynamic = "force-dynamic";
export async function GET() {
return Response.json(
{ message: "Studio API endpoint is running" },
{ headers: CORS_HEADERS }
);
}
export async function POST(request: Request) {
try {
const body = await request.json();
const query = body.query;
if (!query) {
return Response.json([serializeError(new Error("Query is required"))], {
status: 400,
headers: CORS_HEADERS,
});
}
const url = process.env.DATABASE_URL;
if (!url) {
const message = "❌ Environment variable DATABASE_URL is missing.";
return Response.json([serializeError(new Error(message))], {
status: 500,
headers: CORS_HEADERS,
});
}
const [error, results] = await createPrismaPostgresHttpClient({
url,
}).execute(query);
if (error) {
return Response.json([serializeError(error)], {
headers: CORS_HEADERS,
});
}
return Response.json([null, results], { headers: CORS_HEADERS });
} catch (err) {
return Response.json([serializeError(err)], {
status: 400,
headers: CORS_HEADERS,
});
}
}
// Handle preflight requests for CORS
export async function OPTIONS() {
return new Response(null, { status: 204, headers: CORS_HEADERS });
}
3.4.创建 Studio 主页
¥3.4. Create the main Studio page
打开 app/page.tsx
文件,并将渲染嵌入式 Studio 的现有代码替换为:
¥Open the app/page.tsx
file and replace the existing code to render the embedded Studio with the following:
'use client';
import dynamic from "next/dynamic";
import { createPostgresAdapter } from "@prisma/studio-core/data/postgres-core";
import { createStudioBFFClient } from "@prisma/studio-core/data/bff";
import { useMemo, Suspense } from "react";
import StudioWrapper from "@/components/StudioWrapper";
// Dynamically import Studio with no SSR to avoid hydration issues
const Studio = dynamic(
() => import("@prisma/studio-core/ui").then(mod => mod.Studio),
{
ssr: false
}
);
// Loading component
const StudioLoading = () => (
<div className="flex items-center justify-center h-full">
<div className="text-center">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto"></div>
<p className="mt-4 text-gray-600">Loading Studio...</p>
</div>
</div>
);
// Client-only Studio component
const ClientOnlyStudio = () => {
const adapter = useMemo(() => {
// Create the HTTP client that communicates with our API endpoint
const executor = createStudioBFFClient({
url: "/api/studio",
});
// Create the Postgres adapter using the executor
return createPostgresAdapter({ executor });
}, []);
return <Studio adapter={adapter} />;
};
export default function App() {
return (
<StudioWrapper>
<Suspense fallback={<StudioLoading />}>
<ClientOnlyStudio />
</Suspense>
</StudioWrapper>
);
}
3.5.启动你的开发服务器并测试嵌入式 Studio
¥3.5. Start your development server and test the embedded Studio
启动 Next.js 开发服务器:
¥Start your Next.js development server:
npm run dev
打开浏览器并转到 http://localhost:3000
。现在你应该看到 Prisma Studio 在你的应用中运行:
¥Open your browser and go to http://localhost:3000
. You should now see Prisma Studio running inside your application:
以下是需要注意的事项:
¥Here's what to look for:
-
Prisma Studio 界面:完整的 Prisma Studio UI 应该会呈现在你的应用布局中。
¥Prisma Studio interface: The full Prisma Studio UI should render within your app layout.
-
你的数据:你定义的
User
和Post
表(以及任何种子数据)应该会出现。¥Your data: The
User
andPost
tables you defined (plus any seeded data) should appear. -
交互功能:
¥Interactive features:
-
浏览和筛选表中的记录
¥Browse and filter records in your tables
-
通过双击单元格内联编辑值
¥Edit values inline by double-clicking cells
-
使用 "添加记录" 按钮添加新记录
¥Add new records using the "Add record" button
-
删除不再需要的记录
¥Delete records you no longer need
-
通过在相关表之间导航来探索关系
¥Explore relationships by navigating between related tables
-
通过测试基本操作来验证一切是否正常:
¥Verify whether everything works by testing the basics:
-
点击不同的表格以确认数据加载。
¥Click on different tables to confirm your data loads.
-
更新记录以检查更改是否已保存。
¥Update a record to check that changes are saved.
-
添加一条新记录并确认其立即显示。
¥Add a new record and confirm it appears instantly.
-
尝试过滤数据以确保查询正确运行。
¥Try filtering data to make sure queries run correctly.
-
浏览关系(例如,查看用户的帖子)以确认关联有效。
¥Navigate through relationships (for example, view a user's posts) to confirm associations work.
这些操作按预期工作后,你的嵌入式 Prisma Studio 即已设置完毕并连接到你的 Prisma Postgres 数据库。
¥Once these actions work as expected, your embedded Prisma Studio is set up and connected to your Prisma Postgres database.
下一步
¥Next steps
此时,你的 Next.js 应用中已运行 Prisma Studio,并连接到 Prisma Postgres 数据库。你无需离开应用即可浏览、编辑和管理数据。为了使此设置可用于生产环境,请考虑以下改进:
¥At this point you have Prisma Studio running inside your Next.js application and connected to your Prisma Postgres database. You can browse, edit, and manage your data without leaving your app. To make this setup production-ready, consider these improvements:
-
添加身份验证:目前,任何可以打开你应用的人都可以访问 Prisma Studio。添加用户身份验证 仅允许特定角色(例如管理员)使用嵌入式 Studio。你可以通过在运行查询之前检查
/api/studio
端点中的身份验证令牌来执行此操作。¥Add authentication: Currently, anyone who can open your app has access to Prisma Studio. Add user authentication and only allow specific roles (for example, admins) to use the embedded Studio. You can do this by checking authentication tokens in your
/api/studio
endpoint before running queries. -
使用特定于环境的配置:在开发环境中,你可能需要一个测试数据库,而在生产环境中,你需要一个单独的实时数据库。更新你的
.env
文件,为每个环境使用不同的DATABASE_URL
值,并确认你的/api/studio
端点读取的是正确的值。¥Use environment-specific configuration: In development you may want a test database, while in production you'll need a separate live database. Update your
.env
file to use differentDATABASE_URL
values for each environment, and confirm that your/api/studio
endpoint is reading the correct one. -
应用自定义样式:Studio 组件附带默认外观。传入 你自己的主题 文件并调整颜色、字体或品牌标识以匹配应用的其余部分。这让 Studio 感觉像是应用的原生部分,而不是一个独立的工具。
¥Apply custom styling: The Studio component ships with a default look. Pass in your own theme and adjust colors, typography, or branding to match the rest of your application. This helps Studio feel like a native part of your app rather than a standalone tool.
通过添加身份验证、特定于环境的设置和样式,你可以从一个可运行的演示版本过渡到安全且完善的生产环境。
¥By adding authentication, environment-specific settings, and styling, you move from a working demo to a secure and polished production setup.
更多模式和示例,请参阅 Prisma Studio Core 演示仓库,其中包含使用 Hono.js 和 React 的替代实现。如果你更喜欢引导式演示,请观看 YouTube 视频:在你自己的应用中使用 Prisma Studio。
¥For more patterns and examples, see the Prisma Studio Core demo repository, which includes an alternative implementation using Hono.js and React. If you prefer a guided walkthrough, watch the YouTube video: **Use Prisma Studio in Your Own Applications **.
Stay connected with Prisma
Continue your Prisma journey by connecting with our active community. Stay informed, get involved, and collaborate with other developers:
- Follow us on X for announcements, live events and useful tips.
- Join our Discord to ask questions, talk to the community, and get active support through conversations.
- Subscribe on YouTube for tutorials, demos, and streams.
- Engage on GitHub by starring the repository, reporting issues, or contributing to an issue.