VENTURESAurabase przejmuje i inwestuje w Twoje aplikacje, startupy, aplikacje mobilne, SaaS i oprogramowanie.Czytaj więcej →

Inżynieria · 10 min odczytu

Next.js App Router + Suwerenny Postgres 18: Przewodnik Auth, RLS i Natywne AI

Affane Daylami · Founder ·

Powrót do bloga

Zastąpienie @supabase/supabase-js pakietem @aurabase/aurabase-js w projekcie Next.js App Router zachowuje schemat SQL i polityki Row-Level Security, dodając dedykowaną instancję PostgreSQL 18 w Europie oraz natywne endpointy NL2SQL i pgvector RAG.

Źródło angielskie uległo zmianie od czasu tego tłumaczenia. Niektóre informacje mogą być nieaktualne.
Ta strona została przetłumaczona automatycznie. Wersja angielska jest miarodajna.

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.

#

Architektura

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!,
  )
}
Informacje

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

GOTOWY DO WDROŻENIA?

Twój backend w pięć minut.

Karta kredytowa nie jest wymagana · 500 MB za darmo · 50 000 MAU