使用 Vercel 與 Prisma Postgres 進行即時應用程式部署
簡介
本指南將向您展示如何使用 Vercel 的 API 結合整合式 Prisma Postgres 資料庫來實作即時應用程式部署。您將學習如何透過單一 API 呼叫,以程式設計方式建立、部署並轉移全端應用程式。
即時應用程式部署解決了 AI 編碼平台、無程式碼工具和教育平台的一個關鍵問題:如何將產生的程式碼快速轉換為可上線、準備就緒的生產環境應用程式。您不需要要求使用者手動設定託管基礎架構,即可提供一鍵部署應用程式與資料庫的功能。
在本指南結束時,您將了解如何整合 Vercel 的部署 API 與 Prisma Postgres,為您的使用者創造順暢的部署體驗。
嘗試即時演示
透過我們的互動式演示體驗即時部署流程。您可以部署並領取真實的應用程式,親自見證完整的運作過程。

現有的範例
- Next.js + Prisma:具有資料庫整合的基本全端應用程式
- Next.js + Prisma + Better Auth:使用 Better Auth 的完整驗證應用程式
演示功能
- 一鍵部署應用程式
- 產生使用者轉移用的領取代碼 (Claim codes)
- 體驗完整的領取流程
- 查看原始碼與實作細節
適用對象
本指南專為開發以下專案的開發人員所設計:
- AI 驅動的開發平台:需要即時部署已生成完整應用程式的平台
- 無程式碼/低程式碼 (No-code/low-code) 工具:希望在無需管理基礎架構的情況下提供託管服務
- 教育平台:學生需要快速部署專案的學習環境
- CI/CD 系統:需要以程式化方式進行部署的系統
- 快速原型製作工具:將創意轉換為已部署應用程式的工具
核心概念
在實作部署流程之前,我們先了解幾個關鍵概念
Vercel 部署架構
- 專案 (Projects):存放應用程式程式碼與設定的容器
- 部署 (Deployments):部署至 Vercel 邊緣網路 (Edge Network) 的專案特定實例
- 團隊 (Teams):擁有專案並管理帳單的組織單位
- 整合 (Integrations):連接至您專案的第三方服務 (如 Prisma)
Prisma 整合元件
- 整合設定 (Integration configuration):您團隊與 Prisma 服務的連接
- 授權 (Authorization):代表您團隊建立資源的權限
- 資料庫儲存區 (Database stores):獨立的 Prisma Postgres 實例
- 資源連接 (Resource connections):資料庫與 Vercel 專案之間的連結
API 端點概覽
部署流程使用了幾個關鍵的 Vercel API 端點:
POST /v10/projects- 建立新的 Vercel 專案POST /v1/integrations/billing/authorization- 授權 Prisma 整合POST /v1/storage/stores/integration- 建立 Prisma Postgres 資料庫POST /v13/deployments- 部署應用程式程式碼POST /v9/projects/{id}/transfer-request- 為使用者轉移產生領取代碼
必要的 API 金鑰與環境變數
預設情況下,每位新合作夥伴皆處於我們的免費方案,限制每個帳號最多建立 5 個資料庫。如果您正在測試此 API 並需要更高的資料庫建立限制(我們預期大多數人都有此需求),請聯繫我們以獲取合作夥伴等級權限。
Vercel 存取權杖 (Access Token)
您呼叫 Vercel API 的主要驗證權杖。
如何取得
- 前往 Vercel 帳號設定
- 點擊 Create Token (建立權杖)
- 為其命名 (例如:"Instant Deployment API")
- 將作用域 (scope) 設定為您的 團隊 (而非個人帳號)
- 立即複製該權杖 (您之後將無法再次查看)
您需要擁有 Vercel 團隊的「Owner」(擁有者) 層級權限,以確保 ACCESS_TOKEN 能用於所有 API 呼叫。
ACCESS_TOKEN="vercel_token_here"
Vercel 要求帳號綁定信用卡 (即使是在 Hobby 方案中) 才能使用部署 API。在繼續之前,請確保在您的 Vercel 帳號設定中新增付款資訊。
團隊 ID (Team ID)
用於 API 請求的 Vercel 團隊識別碼。
如何取得
- 前往 Vercel 儀表板
- 切換至您的 團隊 (而非個人帳號)
- 前往 團隊設定 (Team Settings)
- 複製顯示在頂端的團隊 ID (格式:
team_abc123xyz)
TEAM_ID="team_abc123xyz"
Prisma 整合設定 ID (Config ID)
您團隊的 Prisma 整合設定識別碼。
如何取得
- 在 Vercel 儀表板中,前往您的 團隊
- 點擊 Integrations (整合) 分頁
- 找到 Prisma 並點擊 Manage (管理) (若尚未安裝請先安裝)
- 在瀏覽器網址列中,複製設定 ID:
https://vercel.com/teams/your-team/integrations/icfg_abc123xyz - 複製
icfg_abc123xyz部分
INTEGRATION_CONFIG_ID="icfg_abc123xyz"
Prisma 產品 ID
Prisma 產品 ID 用於在 Vercel API 中識別 Prisma 整合,其常數值為:iap_yVdbiKqs5fLkYDAB 或 prisma-postgres。
PRISMA_PRODUCT_ID="iap_yVdbiKqs5fLkYDAB"
Prisma Postgres 地區
部署 Prisma Postgres 資料庫的地區。請選擇靠近使用者的地區以獲得最佳效能。
可用地區
iad1- 美國東部 (維吉尼亞州)fra1- 歐洲 (法蘭克福)sfo1- 美國西部 (舊金山)sin1- 亞太地區 (新加坡)hnd1- 亞太地區 (東京)cdg1- 歐洲 (巴黎)
PRISMA_POSTGRES_REGION="iad1"
請參閱支援的 Prisma Postgres 地區完整列表及其對應的 Vercel 地區代碼。
Prisma 帳單方案
帳單方案決定了資料庫限制與功能。可用方案:
free- 限制 5 個資料庫,適用於開發環境pro- 更高的限制,包含連線池 (connection pooling) 與快取功能business- 企業級功能與優先支援enterprise- 自訂限制與專屬支援partnerEntry- 合作夥伴等級權限,具有極高的資料庫限制
PRISMA_BILLING_PLAN="partnerEntry"
對於需要多個資料庫的生產環境部署,我們建議使用 partnerEntry 方案,該方案提供更高的資料庫建立限制。申請合作夥伴權限以解鎖這些功能。
完整部署範例
下方的程式碼片段展示了完整的部署流程。
const CONFIG = {
ACCESS_TOKEN: process.env.ACCESS_TOKEN,
TEAM_ID: process.env.TEAM_ID,
INTEGRATION_CONFIG_ID: process.env.INTEGRATION_CONFIG_ID,
PRISMA_PRODUCT_ID: process.env.PRISMA_PRODUCT_ID || "iap_yVdbiKqs5fLkYDAB", // or can be `prisma-postgres`
PRISMA_POSTGRES_REGION: process.env.PRISMA_POSTGRES_REGION || "iad1",
PRISMA_BILLING_PLAN: process.env.PRISMA_BILLING_PLAN || "partnerEntry",
VERCEL_API_URL: "https://api.vercel.com",
};
async function deployApp() {
console.log("🚀 Starting instant deployment...");
// 1. Create project
const project = await createProject();
// 2. Authorize Prisma integration
const auth = await createPrismaAuthorization();
// 3. Create database
const database = await createPrismaDatabase(
project.name,
auth.id,
auth.configId
);
// 4. Connect database to project
await connectDatabaseToProject(project.id, database.id, auth.configId);
// 5. Deploy application (assumes files already uploaded)
const deployment = await deployApplication(project.name, fileSha);
// 6. Generate claim code
const transfer = await createProjectTransfer(project.id);
console.log("🎉 Deployment completed!");
console.log(`Live URL: https://${deployment.url}`);
console.log(`Claim URL: ${transfer.claimUrl}`);
return {
projectId: project.id,
deploymentUrl: `https://${deployment.url}`,
claimCode: transfer.code,
claimUrl: transfer.claimUrl,
};
}
逐步部署過程
上述完整範例示範了整個部署過程,現在讓我們詳細分解每個步驟。
步驟 1:建立 Vercel 專案
每次部署都從建立專案容器開始。
async function createProject(): Promise<{ id: string; name: string }> {
const projectName = `demo-project-${Date.now()}`;
const response = await fetch(
`${CONFIG.VERCEL_API_URL}/v10/projects?teamId=${CONFIG.TEAM_ID}`,
{
method: "POST",
headers: {
Authorization: `Bearer ${CONFIG.ACCESS_TOKEN}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ name: projectName }),
}
);
const project = await response.json();
console.log(`✅ Project created: ${project.name} (${project.id})`);
return { id: project.id, name: project.name };
}
關鍵參數
name: 唯一專案識別碼 (自動產生並帶有時間戳記)teamId: 您的團隊 ID,以確保專案擁有權正確
在 Vercel Projects API 文件 中了解更多。
步驟 2:授權 Prisma 整合
在建立資料庫之前,您需要授權以代表您的團隊使用 Prisma。
async function createPrismaAuthorization(): Promise<{
id: string;
configId: string;
}> {
const response = await fetch(
`${CONFIG.VERCEL_API_URL}/v1/integrations/billing/authorization?teamId=${CONFIG.TEAM_ID}`,
{
method: "POST",
headers: {
Authorization: `Bearer ${CONFIG.ACCESS_TOKEN}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
integrationIdOrSlug: "prisma",
productId: CONFIG.PRISMA_PRODUCT_ID,
billingPlanId: CONFIG.PRISMA_BILLING_PLAN,
metadata: JSON.stringify({ region: CONFIG.PRISMA_POSTGRES_REGION }),
integrationConfigurationId: CONFIG.INTEGRATION_CONFIG_ID,
}),
}
);
const authData = await response.json();
return {
id: authData.authorization.id,
configId: authData.authorization.integrationConfigurationId,
};
}
關鍵參數
billingPlanId: 帳單方案 (生產環境建議使用 "partnerEntry")region: 資料庫地區,以獲得最佳效能metadata: 包含地區與其他設定的 JSON 字串
在 Vercel Integrations API 文件 中了解更多。
步驟 3:提供 Prisma Postgres 資料庫
建立一個具有自動連線池與快取功能的新資料庫實例。
async function createPrismaDatabase(
projectName: string,
authId: string,
configId: string
): Promise<{ id: string; }> {
const response = await fetch(
`${CONFIG.VERCEL_API_URL}/v1/storage/stores/integration?teamId=${CONFIG.TEAM_ID}`,
{
method: "POST",
headers: {
Authorization: `Bearer ${CONFIG.ACCESS_TOKEN}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
metadata: { region: CONFIG.PRISMA_POSTGRES_REGION },
billingPlanId: CONFIG.PRISMA_BILLING_PLAN,
name: `postgres-${projectName}`,
integrationConfigurationId: configId,
integrationProductIdOrSlug: CONFIG.PRISMA_PRODUCT_ID,
authorizationId: authId,
source: "marketplace",
}),
}
);
const storageData = await response.json();
return {
id: storageData.store.id
};
}
關鍵參數
name: 資料庫識別碼 (通常與專案名稱一致)source: 用於 Vercel 市集整合的 "marketplace"billingPlanId: 決定功能與限制的帳單方案
在 Vercel Storage API 文件 中了解更多。
步驟 4:連接資料庫至專案
將資料庫連結至您的 Vercel 專案,以自動注入環境變數。
async function connectDatabaseToProject(
projectId: string,
storeId: string,
configId: string
): Promise<void> {
await fetch(
`${CONFIG.VERCEL_API_URL}/v1/integrations/installations/${configId}/products/${CONFIG.PRISMA_PRODUCT_ID}/resources/${storeId}/connections?teamId=${CONFIG.TEAM_ID}`,
{
method: "POST",
headers: {
Authorization: `Bearer ${CONFIG.ACCESS_TOKEN}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ projectId }),
}
);
console.log("✅ Database connected to project");
}
此連線會自動將 DATABASE_URL 與其他環境變數新增至您的專案。
在 Vercel Integration Resources 文件 中了解更多。
步驟 5:部署應用程式
將應用程式程式碼部署至 Vercel。
async function deployApplication(
projectName: string,
fileSha: string
): Promise<{ id: string; url: string }> {
const response = await fetch(
`${CONFIG.VERCEL_API_URL}/v13/deployments?teamId=${CONFIG.TEAM_ID}`,
{
method: "POST",
headers: {
Authorization: `Bearer ${CONFIG.ACCESS_TOKEN}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
files: [{ file: ".vercel/source.tgz", sha: fileSha }],
name: `deployment-${Date.now()}`,
projectSettings: { framework: "nextjs" },
project: projectName,
}),
}
);
const deploymentData = await response.json();
return {
id: deploymentData.id,
url: deploymentData.alias?.[0] || deploymentData.url,
};
}
關鍵參數
files: 已上傳檔案的陣列 (需要先以tgz格式上傳檔案)framework: "nextjs", "react", "vue" 等,用於自動設定projectSettings: 框架特定的建置與執行時期設定
在 Vercel Deployments API 文件 中了解更多,或參閱 Vercel API 參考。
步驟 6:產生使用者轉移用的領取代碼
建立一個轉移代碼,允許使用者領取該已部署專案的擁有權。
async function createProjectTransfer(
projectId: string
): Promise<{ code: string; claimUrl: string }> {
const response = await fetch(
`${CONFIG.VERCEL_API_URL}/v9/projects/${projectId}/transfer-request?teamId=${CONFIG.TEAM_ID}`,
{
method: "POST",
headers: {
Authorization: `Bearer ${CONFIG.ACCESS_TOKEN}`,
"Content-Type": "application/json",
},
body: JSON.stringify({}),
}
);
const transferData = await response.json();
const claimUrl = `https://vercel.com/claim-deployment?code=${transferData.code}&returnUrl=https://myapp.com/dashboard/projects`;
return {
code: transferData.code,
claimUrl,
};
}
關鍵細節
- 轉移代碼有效期為 24 小時
- 使用者可以將專案領取到其 Vercel 帳號中的任何團隊
- 如果領取網址無效或已過期,
returnUrl會將使用者重新導向至特定頁面
在 Vercel Claim Deployments 文件 中了解更多。
使用者領取流程
部署完成後,使用者可以透過安全的轉移過程領取擁有權
領取是如何運作的
- 使用者收到領取網址:您的平台提供產生的領取網址
- 使用者驗證:若尚未登入,Vercel 會提示使用者登入
- 選擇團隊:使用者選擇要由哪個 Vercel 團隊擁有該專案
- 完成轉移:專案與資料庫會轉移至使用者選擇的團隊
- 帳單轉移:使用者的團隊負責後續的託管費用
領取網址結構
https://vercel.com/claim-deployment?code=xxx&returnUrl=https://myapp.com/dashboard/projects
參數
code: 來自步驟 6 的轉移代碼 (有效期 24 小時)returnUrl: 如果領取網址無效或過期,將使用者重新導向至特定頁面
什麼內容會被轉移
當使用者領取部署時,他們會獲得:
- 完整的專案擁有權,包含所有原始碼與設定
- 資料庫擁有權,包含所有資料與連線字串
- 環境變數,會自動為新團隊進行更新
- 部署歷史記錄與建置日誌
在 Claim Deployments 文件 中了解更多。
錯誤處理與最佳實踐
常見錯誤情境
async function handleApiErrors(response: Response, operation: string) {
if (!response.ok) {
const errorData = await response.text();
// Handle specific error cases
switch (response.status) {
case 401:
throw new Error(`Authentication failed: Check your ACCESS_TOKEN`);
case 403:
throw new Error(`Permission denied: Verify team access and scopes`);
case 429:
throw new Error(`Rate limit exceeded: Implement retry logic`);
case 404:
throw new Error(`Resource not found: Check IDs and configuration`);
default:
throw new Error(`${operation} failed: ${response.status} - ${errorData}`);
}
}
}
正確的錯誤處理可防止部署失敗,並為您的使用者提供清晰的除錯資訊。
速率限制注意事項
Vercel 對 API 端點實施速率限制。您可以實作指數退避 (exponential backoff) 來處理速率限制。
async function apiCallWithRetry(url: string, options: RequestInit, maxRetries = 3) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
const response = await fetch(url, options);
if (response.status === 429) {
const waitTime = Math.pow(2, attempt) * 1000; // Exponential backoff
await new Promise(resolve => setTimeout(resolve, waitTime));
continue;
}
return response;
} catch (error) {
if (attempt === maxRetries) throw error;
}
}
}
重試邏輯確保您的部署服務在高流量期間保持穩定可靠。
在 Vercel API Limits 文件 中了解更多。
安全性最佳實踐
- 安全存放權杖:絕不要在用戶端程式碼中暴露 API 權杖
- 驗證輸入:清理專案名稱與使用者提供的資料
- 監控使用量:追蹤 API 呼叫以防止濫用
- 實作逾時:設定合理的請求逾時時間以確保可靠性
這些實踐能保護您的整合免受常見安全性漏洞的影響,並確保穩定運作。
生產環境注意事項
以下是您部署服務在生產環境中的一些考量:
與現有平台整合
您可以將部署服務與現有平台整合,為您的使用者提供順暢的體驗。
// Example integration with an AI coding platform
class DeploymentService {
async deployGeneratedApp(code: string, userId: string) {
// 1. Package generated code
const packagedCode = await this.packageCode(code);
// 2. Deploy with Vercel + Prisma
const deployment = await this.deployApp(packagedCode);
// 3. Store deployment info
await this.storeDeployment(userId, deployment);
// 4. Notify user
await this.notifyUser(userId, deployment.claimUrl);
return deployment;
}
}
監控與分析
追蹤您部署服務的關鍵指標:
- 部署成功率:監控 API 失敗與逾時情況
- 領取轉換率:追蹤有多少使用者領取了他們的部署
- 效能指標:測量部署時間與使用者體驗
- 成本分析:監控 Vercel 與 Prisma 的使用成本
後續步驟
現在您已了解如何使用 Vercel 與 Prisma Postgres 進行即時應用程式部署,您可以:
- 整合至您的平台:為您現有的應用程式新增部署功能
- 自訂流程:針對您特定的使用情境與使用者體驗調整流程
- 擴展您的實作:透過適當的排隊與錯誤處理機制處理大量部署
- 監控並優化:追蹤效能與使用者採用指標
額外資源
若對您的整合有任何問題或需要支援,請透過 Prisma 社群 Discord 或 Vercel 支援 聯繫我們。
與 Prisma 保持聯繫
透過以下方式與我們聯繫,繼續您的 Prisma 旅程: 我們的活躍社群。保持資訊靈通、參與其中,並與其他開發者合作
- 在 X 上關注我們 以獲取公告、現場活動和實用技巧。
- 加入我們的 Discord 提出問題、與社群對話,並透過對話獲得積極支援。
- 在 YouTube 上訂閱 查看教學、演示和直播。
- 在 GitHub 上交流 透過為存放庫加星標、報告問題或為 issue 做出貢獻。