廣告位招商中 歡迎洽談

連接 Vercel v0 與 Supabase:基於 Server Actions 打造持久化 Next.js 全端應用全指南

Serene Tay · 365Finds Editorial
已收錄 88,650 篇 Wiki 文章

讓你的 AI 用上 365 Wiki

複製下方的提示詞,貼給你常用的 AI,然後直接提問。

下載完整版 Skill

先用提示詞體驗;經常使用時,安裝完整版 365Wiki Skill,以後無需重複複製。沒有常用 AI?Gemini、Microsoft Copilot 等網頁版也可以。

365Wiki Skill

Vercel v0 的問世徹底顛覆了前端原型開發流程,工程師只需透過自然語言提示詞,便能在數秒內生成結構優雅、樣式精準的 React 與 Next.js 介面。然而,對於全端工程師與獨立開發者(Indie Hackers)而言,視覺上的 UI 原型僅僅是應用的骨架。若系統僅依賴暫態的 useState 狀態或靜態 Mock 資料,終究無法承載真實業務。一旦邁入使用者身分驗證、資料持久化與多租戶隔離階段,開發者往往面臨繁瑣的手動工程:建立雲端資料庫、手動配置環境變數、撰寫 RESTful CRUD API 以及重構前端表單提交邏輯。

365Finds 深入評測後給出明確的技術判斷:在 v0 中透過 Vercel Marketplace 原生整合 Supabase,並全面採用 Next.js App Router 的 Server Actions('use server')處理資料持久化,是目前全端交付效率最高且架構最穩固的最佳實踐。這個架構徹底省去了傳統 /api/* 路由處理器(Route Handlers)的冗餘層級,阻斷了前端直連資料庫引發的憑證洩漏隱患,完美串接了從自然語言介面生成到 PostgreSQL 正式生產落地的完整鏈路。

本文將帶領開發者一步步完成這套生產級架構:涵蓋市場一鍵整合、PostgreSQL 行級安全策略(RLS)權限防禦、Cookie 隔離的 SSR 用戶端設定,以及前端表單與 useTransition 狀態過渡的安全綁定。


架構選型比較:為什麼資料持久化首選 Server Actions

在將 v0 生成的原型轉化為持久化應用時,業界常見三種資料存取範式。365Finds 強烈建議:在現代 Next.js App Router 架構下,應全面淘汰用戶端 SDK 直連與傳統 API 路由。

架構模式網路往返與延遲用戶端打包體積影響安全與憑證隔離邊界維護與重構成本365Finds 評估推薦
用戶端直連 Supabase SDK偏高;用戶端身分驗證與多次握手增加前端 JS 體積;在前端程式碼中暴露資料表結構極高風險;若 RLS 規則配置不嚴密,用戶端容易遭受越權篡改中等;需在用戶端處理繁複的非同步狀態與手動資料重抓邏輯堅決避免用於寫入操作;僅適用於即時資料監聽(Realtime)
傳統 API 路由 (app/api/*)中等;表單提交 -> Fetch POST -> Route Handler -> 資料庫 -> JSON 回應良好;程式碼隔離於伺服器端良好;伺服器端環境變數隔離,但需開發者手動實作 CSRF 防護與入參校驗偏高;必須維護冗餘的 API 端點路由、請求序列化與錯誤狀態解析過渡期舊典範;在現代 App Router 中屬於多餘的樣板程式碼
Server Actions ('use server')最優;單次 HTTP 往返即可完成資料庫變更與 RSC 快取再驗證零用戶端體積增加;邏輯完全於 Vercel 邊緣或無伺服器環境執行原生具備同源 CSRF 防禦;在伺服器端完成嚴密的身分權限校驗最低;前端表單或過渡函式可直接非同步呼叫,完美契合 React 狀態強烈推薦;自然語言生成到全端持久化的最短閉環路徑

Server Actions 大幅優化了全端鏈路,因為 Next.js 能夠在單次網路往返中,依序執行伺服器端資料庫寫入、快取重新驗證(Revalidation),並將最新的 React Server Component(RSC)Payload 直接回傳至前端渲染。


步驟一:透過 v0 原生 Marketplace 一鍵接入 Supabase

手動建立資料庫並逐一複製貼上金鑰極易出錯。利用 Vercel 與 v0 原生串接的 Marketplace 機制,可以在操作介面中實現自動化佈署與金鑰注入。

在 v0 介面中啟動連結

  1. 在編輯中的 v0 對話介面或專案畫布右上角,點擊專案設定選單(...),進入 Settings > Integrations。亦可在對話框直接輸入 Prompt:“Connect my project to Supabase to persist user projects”,v0 會直接在對話流程中喚出整合面板。
  2. 在 Marketplace 列表中點選 Supabase。
  3. 選擇對應的 Supabase 組織,支援綁定既有資料庫專案或直接新建獨立資料庫實例。
  4. 授權並確認設定。

底層自動注入之環境變數

市集整合完成後,系統會自動將資料庫連線資訊注入 v0 即時預覽容器與綁定的 Vercel 專案中:

本地開發提醒:若後續使用 v0 CLI(npx v0@latest)或 Git 將程式碼匯出至本地,只需於專案目錄執行 vercel env pull .env.local,即可自動同步遠端環境變數。


步驟二:資料建模與行級安全策略(RLS)嚴格配置

開發者在使用 AI 生成全端系統時常忽略關鍵的安全防線:直接在資料庫中執行 v0 輸出的建表腳本,卻未啟用行級安全策略(RLS)。在 Supabase 架構下,若資料表未開啟 RLS,任何取得匿名 Key 的外部請求都能透過 PostgREST API 任意讀寫全表資料。

精確的 Prompt 提示語引導

要求 v0 生成兼顧資料約束與權限防禦的完整 SQL:

“為專案管理模組生成 PostgreSQL 建表腳本。要求外鍵關聯 auth.users(id),自動記錄時間戳記,並開啟嚴格的 Row Level Security(RLS),確保登入使用者僅能存取與修改屬於自己的資料。”

在 Supabase SQL Editor 中審核並套用

進入 Supabase 控制台的 SQL Editor,貼上並確認包含以下防護邏輯的 SQL 遷移語句:

-- 1. 建立 projects 資料表
create table if not exists public.projects (
  id uuid primary key default gen_random_uuid(),
  user_id uuid not null references auth.users(id) on delete cascade,
  title text not null check (char_length(title) >= 3),
  description text default '',
  status text not null default 'in_progress' check (status in ('in_progress', 'completed', 'archived')),
  created_at timestamp with time zone default timezone('utc'::text, now()) not null,
  updated_at timestamp with time zone default timezone('utc'::text, now()) not null
);

-- 2. 為外鍵建立索引,提升查詢效能
create index if not exists projects_user_id_idx on public.projects(user_id);

-- 3. 強制開啟行級安全策略(核心必備)
alter table public.projects enable row level security;

-- 4. 針對已登入使用者配置細緻的 RLS 策略
create policy "Users can select their own projects"
  on public.projects for select
  to authenticated
  using ((select auth.uid()) = user_id);

create policy "Users can insert their own projects"
  on public.projects for insert
  to authenticated
  with check ((select auth.uid()) = user_id);

create policy "Users can update their own projects"
  on public.projects for update
  to authenticated
  using ((select auth.uid()) = user_id)
  with check ((select auth.uid()) = user_id);

create policy "Users can delete their own projects"
  on public.projects for delete
  to authenticated
  using ((select auth.uid()) = user_id);

請特別留意,策略中採用 (select auth.uid()) 代替純粹的 auth.uid(),PostgreSQL 會將此子查詢結果快取於單次語句執行期間,避免逐行重新計算函數,在大規模資料檢索時效能顯著提升。


步驟三:初始化基於 Cookie 的 Supabase SSR 伺服器端用戶端

在 Next.js App Router 中,Server Actions 運作於無狀態的伺服器端環境,使用者 Session 仰賴 HTTP-only Cookies 維繫。若誤用傳統的 @supabase/supabase-js 用戶端,將無法正確解析 Request Cookies,進而導致身分驗證靜默失效。

先於專案中安裝官方套件:

npm install @supabase/ssr @supabase/supabase-js

建立伺服器端用戶端工廠函式 lib/supabase/server.ts:

// lib/supabase/server.ts
import { createServerClient } from '@supabase/ssr'
import { cookies } from 'next/headers'

export async function createClient() {
  const cookieStore = await cookies()

  return createServerClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
    {
      cookies: {
        getAll() {
          return cookieStore.getAll()
        },
        setAll(cookiesToSet) {
          try {
            cookiesToSet.forEach(({ name, value, options }) =>
              cookieStore.set(name, value, options)
            )
          } catch {
            // 當 setAll 從 Server Component 呼叫時可能觸發例外
            // 若應用已配置 Middleware 處理 Session 刷新,可安全忽略
          }
        },
      },
    }
  )
}

步驟四:撰寫具備快取自動再驗證的持久化 Server Action

將 v0 原先生成的假資料提交函式替換為生產級的 Server Action。在檔案頂部宣告 'use server',Next.js 會將其內部匯出的函式編譯為嚴格受控的伺服器端 RPC 端點。

建立 app/actions/projects.ts:

// app/actions/projects.ts
'use server'

import { createClient } from '@/lib/supabase/server'
import { revalidatePath } from 'next/cache'

export type ActionResponse = {
  success: boolean
  message?: string
  error?: string
}

export async function createProjectAction(
  prevState: ActionResponse | null,
  formData: FormData
): Promise<ActionResponse> {
  const supabase = await createClient()

  // 1. 於伺服器端嚴格驗證操作者身分
  const {
    data: { user },
    error: authError,
  } = await supabase.auth.getUser()

  if (authError || !user) {
    return {
      success: false,
      error: '未授權:請先登入後再建立專案',
    }
  }

  // 2. 嚴密驗證表單輸入參數
  const title = formData.get('title')?.toString().trim()
  const description = formData.get('description')?.toString().trim() || ''

  if (!title || title.length < 3) {
    return {
      success: false,
      error: '專案名稱長度至少需達 3 個字元',
    }
  }

  // 3. 寫入 Supabase 資料庫並綁定 user.id
  const { error: dbError } = await supabase.from('projects').insert({
    title,
    description,
    user_id: user.id,
  })

  if (dbError) {
    return {
      success: false,
      error: `資料庫寫入失敗: ${dbError.message}`,
    }
  }

  // 4. 清除路由快取以確保前端畫面即時呈現最新資料
  revalidatePath('/projects')

  return {
    success: true,
    message: '專案建立成功!',
  }
}

關鍵安全法則

Server Actions 編譯後本質上是向外開放的同源 HTTP POST 介面。絕不能輕信前端傳入的任何資料,更不可假定用戶端已完成權限審查。在 Action 開頭呼叫 supabase.auth.getUser() 重新驗證目前會話,並將資料庫的 user_id 強制綁定為該使用者,是杜絕水平越權攻擊的必要防護。


步驟五:改造 v0 前端表單,透過 useTransition 實現平滑互動

v0 產生的表單通常包含 <form onSubmit={...}> 並搭配本地 state。為了打造無需全頁重新載入且具備即時 Loading 反饋的現代體驗,我們應將 v0 表單改造為直連 Server Action,並運用 React 原生的 useTransition 管理過渡態。

建立組件 components/create-project-dialog.tsx:

// components/create-project-dialog.tsx
'use client'

import { useState, useTransition } from 'react'
import { createProjectAction, type ActionResponse } from '@/app/actions/projects'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { Label } from '@/components/ui/label'

export function CreateProjectForm({ onSuccess }: { onSuccess?: () => void }) {
  const [isPending, startTransition] = useTransition()
  const [state, setState] = useState<ActionResponse | null>(null)

  const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault()
    const form = event.currentTarget
    const formData = new FormData(form)

    startTransition(async () => {
      const response = await createProjectAction(state, formData)
      setState(response)

      if (response.success) {
        form.reset()
        onSuccess?.()
      }
    })
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      {state?.error && (
        <div className="rounded-md bg-destructive/15 p-3 text-sm text-destructive font-medium">
          {state.error}
        </div>
      )}

      {state?.success && (
        <div className="rounded-md bg-emerald-500/15 p-3 text-sm text-emerald-600 font-medium dark:text-emerald-400">
          {state.message}
        </div>
      )}

      <div className="space-y-2">
        <Label htmlFor="title">專案名稱</Label>
        <Input
          id="title"
          name="title"
          placeholder="例如:SaaS 官網改版方案"
          required
          disabled={isPending}
        />
      </div>

      <div className="space-y-2">
        <Label htmlFor="description">詳細描述</Label>
        <Textarea
          id="description"
          name="description"
          placeholder="填寫核心目標與關鍵里程碑..."
          disabled={isPending}
        />
      </div>

      <Button type="submit" className="w-full" disabled={isPending}>
        {isPending ? '正在寫入資料庫...' : '立即建立專案'}
      </Button>
    </form>
  )
}

藉助 useTransition,介面在執行伺服器寫入時不會出現卡頓,按鈕會即時切換至載入狀態;而伺服器端執行的 revalidatePath 會將最新的資料即時推回父層 Server Components,前端完全省去手動 Fetch 與重新渲染的繁複程式碼。


365Finds 工程架構避坑守則

在正式交付與維運基於 v0 與 Supabase 的全端專案時,務必注意以下三個架構陷阱:

  1. 嚴禁在 Server Action 中濫用 service_role 繞過權限:部分開發者在除錯時為了繞過權限報錯,在伺服器端直接呼叫高權限的 service_role 金鑰。此舉會徹底無視 PostgreSQL 所有的 RLS 策略。一旦 Action 參數過濾存在細微瑕疵,惡意使用者就能輕易竄改甚至清空全表。請務必在 createServerClient 中維持匿名 Key,將權限防線留給資料庫層級的 RLS。
  2. 避免過大範圍的快取失效:在 Server Action 中呼叫 revalidatePath('/', 'layout') 會強制讓全站所有路由與組件快取全數過期,引發 Serverless 運算成本驟增。應精確鎖定受影響的路由路徑(例如 revalidatePath('/projects'))。
  3. 注意用戶端 Action 的串行排隊機制:Next.js App Router 為了維護 UI 樹與伺服器狀態的一致性,在用戶端連續觸發多個 Server Action 時會自動排隊串行執行。請避免在前端使用 Promise.all 同時發起多個 Action;若有批次處理需求,應在伺服器端包裝單一事務 Action 統一處理。

結合 v0 的生成速度、Supabase 的 PostgreSQL 託管實力與 Next.js Server Actions 的優雅封裝,全端工程師得以在最短時間內完成從自然語言原型到高強韌度商業級系統的躍升。


參考資料