VENTURESAurabase 收购并投资您的应用程序、初创公司、移动应用、SaaS 和软件。了解更多 →

工程 · 10 最小读取值

Next.js App Router + 主权 Postgres 18:Auth、RLS 与原生 AI 指南

Affane Daylami · Founder ·

返回博客

在 Next.js App Router 项目中将 @supabase/supabase-js 替换为 @aurabase/aurabase-js,可完整保留 SQL 模式与行级安全(RLS)策略,同时获得托管在欧洲的专属 PostgreSQL 18 实例以及原生 AST 验证 NL2SQL 与 pgvector RAG 端点。

自此翻译以来,英文来源已发生变化。某些信息可能已过时。
该页面已自动翻译。英文版具有权威性。

Modern full-stack TypeScript teams building on the Next.js App Router often start with a managed BaaS for speed, only to hit three architectural walls in production: US CLOUD Act exposure through American parent companies, connection saturation or serverless cold starts under bursty traffic, and fragmented third-party wiring when adding RAG or natural-language SQL querying. This guide walks through building (or migrating) a production Next.js App Router application on an always-on dedicated PostgreSQL 18 database hosted in Europe with native AI primitives.

#

建筑

Why pair Next.js App Router with a sovereign EU PostgreSQL 18 backend

When a Next.js Server Component or Server Action queries a database, every round-trip crosses both a network boundary and a legal boundary. Selecting an EU region on a US-headquartered cloud provider reduces network latency for European users, but does not exempt the provider from extraterritorial data requests under the US CLOUD Act (18 U.S.C. § 2713). Aurabase is operated in Europe on 100% European bare-metal and cloud infrastructure (Scaleway in Paris fr-par, Hetzner in Frankfurt/Falkenstein de-fra and Helsinki fi-hel).

On the runtime side, serverless Next.js functions can spawn hundreds of concurrent connections during traffic spikes. Aurabase routes all data-plane traffic through PgBouncer in transaction pooling mode ahead of your dedicated PostgreSQL 18 instance, while the unified Rust gateway (aura-gateway) handles JWT verification, rate limiting, and routing to native AI endpoints without Garbage Collector pauses.

Architectural LayerTraditional US BaaS StackAurabase Sovereign Stack
Primary DatabaseShared or scale-to-zero PostgresDedicated PostgreSQL 18 per project + PgBouncer transaction pooling
Core Services RuntimeHeterogeneous (Go, Elixir, Node.js, Haskell)Unified 100% Rust workspace (Axum, Tokio, SQLx, NATS, Wasmtime)
Legal JurisdictionUS parent company (CLOUD Act exposure)100% EU jurisdiction (Scaleway Paris, Hetzner Germany & Finland)
Vector Search & RAGManual chunking + external pipelineBuilt-in aura.ai.ragIngest() & aura.ai.rag() on pgvector HNSW
Natural Language to SQLExternal conversational connectorsNative aura.ai.nl2sql() validated by a Rust SQL AST parser
#

Step 1

Install @aurabase/aurabase-js and connect the MCP server

Install the official TypeScript SDK in your Next.js application and configure your project URL and keys. If you are migrating from an existing Supabase codebase, see our Aurabase vs Supabase technical comparison and the step-by-step Supabase migration guide.

# Install the official TypeScript SDK
npm install @aurabase/aurabase-js

# Optional: connect Claude Code or Cursor to your project via the 86-tool MCP server
npx -y -p @aurabase/mcp-server aurabase-mcp \
  --url https://<slug>.aurabase.cloud \
  --project-id <project-id> \
  --service-role-key aura_sk_<key>

Create a shared server/client initializer in lib/aurabase.ts. Note that AURA_SERVICE_ROLE_KEY must only ever be read inside server-only modules or Server Actions, never exposed to client bundles.

import { createClient } from '@aurabase/aurabase-js'

export const aura = createClient(
  process.env.NEXT_PUBLIC_AURA_URL!,
  process.env.NEXT_PUBLIC_AURA_ANON_KEY!,
)

export function createAdminClient() {
  return createClient(
    process.env.NEXT_PUBLIC_AURA_URL!,
    process.env.AURA_SERVICE_ROLE_KEY!,
  )
}
信息

You can inspect and manage your entire schema, RLS policies, and vector indexes directly from your AI IDE using the official Aurabase MCP server, which exposes 86 typed tools over stdio.

#

Step 2

OAuth2 PKCE authentication and Row-Level Security (RLS)

Every project runs on a dedicated PostgreSQL 18 database with standard auth.uid() and auth.role() SQL functions. Define your application tables and enable Row-Level Security so that each authenticated user can only access their own rows.

CREATE TABLE public.documents (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  owner_id uuid NOT NULL DEFAULT auth.uid(),
  title text NOT NULL,
  content text NOT NULL,
  created_at timestamptz NOT NULL DEFAULT now()
);

ALTER TABLE public.documents ENABLE ROW LEVEL SECURITY;

CREATE POLICY "Users can read their own documents"
  ON public.documents
  FOR SELECT
  USING (auth.uid() = owner_id);

CREATE POLICY "Users can insert their own documents"
  ON public.documents
  FOR INSERT
  WITH CHECK (auth.uid() = owner_id);

Inside a Next.js React Server Component, query the table using the chainable PostgREST-compatible builder. PostgreSQL enforces the RLS policy directly inside the database engine.

import { aura } from '@/lib/aurabase'

export default async function DocumentsPage() {
  const { data: documents, error } = await aura
    .from('documents')
    .select('id, title, created_at')
    .order('created_at', { ascending: false })
    .limit(20)

  if (error) {
    throw new Error(`Failed to load documents: ${error.message}`)
  }

  return (
    <ul>
      {(documents ?? []).map((doc) => (
        <li key={doc.id}>{doc.title}</li>
      ))}
    </ul>
  )
}
#

Step 3

Native pgvector RAG and AST-validated NL2SQL in Server Actions

Instead of stitching together an external vector database and a separate orchestration framework, aura-ai provides two native backend primitives backed directly by your PostgreSQL 18 instance and pgvector HNSW indexes:

  1. aura.ai.ragIngest() and aura.ai.rag(): automatically chunk text, compute embeddings (768, 1536, or 3072 dimensions), index them into pgvector, and synthesize grounded answers with source citations.
  2. aura.ai.nl2sql(): translates a natural-language question into a candidate SQL query, validates its Abstract Syntax Tree (AST) in Rust (sqlparser-rs) to guarantee a read-only SELECT with a bounded LIMIT, and returns both the verified SQL and the rows.
'use server'

import { createAdminClient } from '@/lib/aurabase'

export async function ingestKnowledgeDocument(docId: string, text: string) {
  const admin = createAdminClient()
  return await admin.ai.ragIngest({
    collection: 'product_docs',
    documentId: docId,
    content: text,
    metadata: { source: 'nextjs-server-action' },
  })
}

export async function askDatabaseQuestion(question: string) {
  const admin = createAdminClient()
  // The schema is introspected server-side; AST validation blocks any non-SELECT query
  const result = await admin.ai.nl2sql(question, {
    maxRows: 50,
  })
  return {
    sql: result.sql,
    rows: result.rows,
  }
}
#

Step 4

15-minute migration checklist from @supabase/supabase-js

If you are migrating an existing Next.js App Router application from Supabase to Aurabase, the client surface and SQL conventions map 1-to-1:

CapabilitySupabase (@supabase/supabase-js)Aurabase (@aurabase/aurabase-js)Migration Effort
Client InitializationcreateClient(url, anonKey)createClient(url, anonKey)Swap import & env vars
Relational Queriesclient.from('t').select('*').eq('id', x)aura.from('t').select('*').eq('id', x)Identical
Row-Level Securityauth.uid(), auth.role(), auth.jwt()auth.uid(), auth.role(), auth.jwt()Identical (pg_dump / pg_restore)
OAuth2 & PKCE Authauth.signInWithOAuth({ provider })auth.signInWithOAuth({ provider })Identical (15 providers + OIDC)
S3 Object Storagestorage.from('bucket').upload(path, file)storage.from('bucket').upload(path, file)Identical
Realtime CDCchannel('c').on('postgres_changes', ...)channel('c').on('postgres_changes', ...)Identical
Native AI (NL2SQL & RAG)Not built-in (external connectors)aura.ai.nl2sql(), aura.ai.ragIngest(), aura.ai.rag()Native upgrade

准备好部署了吗?

五分钟内完成您的后端。

无需信用卡 · 500 MB 免费 · 50,000 MAU