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 스키마와 Row-Level Security 정책을 그대로 유지하면서 유럽 내 전용 PostgreSQL 18 인스턴스와 네이티브 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

배포할 준비가 되셨나요?

5분 만에 백엔드를 완성하세요.

신용카드 불필요 · 500MB 무료 · 50,000 MAU