Building a Realtime Backend with Supabase: PostgreSQL, Built-in Auth, and Row Level Security

Database tutorial - IT technology blog
Database tutorial - IT technology blog

The Hidden Overhead of Traditional Backends

Spinning up a production backend used to demand a tedious setup ritual. You provisioned a Linux droplet, tuned a Postgres instance, wired JWT verification middleware, salted passwords with bcrypt, and hand-coded dozens of boilerplate CRUD routes. When product managers requested live collaboration, the complexity ballooned: standing up Redis pub/sub clusters, wrangling socket.io servers, and managing reconnect backoffs.

This boilerplate routinely burns 40 to 80 engineering hours before anyone builds user-facing value. Worse, teams often end up maintaining hundreds of fragile Node.js or Python endpoints that merely pass client JSON payloads directly to an SQL query.

A faster path exists: move authorization and event streaming directly into the database engine. Supabase achieves this by combining managed PostgreSQL with integrated authentication, auto-generated REST APIs via PostgREST, and realtime change streams.

Under the Hood: Supabase Architecture

Rather than locking you into a proprietary cloud framework like Firebase, Supabase stitches together proven open-source components around core PostgreSQL. You interact directly with standard SQL, and your data remains completely portable.

1. PostgreSQL as a First-Class Citizen

Every Supabase project runs a dedicated PostgreSQL 15+ instance. You retain full database ownership: run raw DDL migrations, define triggers, query across foreign data wrappers, or load specialized extensions like pgvector for semantic vector search and pgcrypto for hashing.

2. Integrated GoTrue Authentication

Identity is handled by GoTrue, an open-source OAuth2/JWT engine written in Go. User records persist directly into the isolated auth.users database schema. When a user authenticates via magic link, password, or GitHub OAuth, GoTrue issues an RS256-signed JWT carrying their user UUID and metadata. Every client database query forwards this token directly in the HTTP Authorization header.

3. Declarative Row Level Security (RLS)

Row Level Security removes the need for an intermediate application server. In standard Express or Django stacks, your controller must manually check permissions:

if (req.user.id !== post.owner_id) {
  return res.status(403).json({ error: 'Forbidden' });
}

With Postgres RLS, authorization lives in declarative database rules. The Postgres query planner checks the incoming JWT claims against table policies, silently rejecting unauthorized writes and filtering unauthorized reads before rows leave disk.

4. Realtime Streaming via PostgreSQL WAL

Supabase streams change events by tailing PostgreSQL’s Write-Ahead Log (WAL) through native logical replication. An Elixir daemon reads the replication slot, filters events against user permissions, and fans out row insertions, updates, and deletions over WebSockets in under 100 milliseconds.

Hands-on Tutorial: Building a Live Message Feed

Let’s build a secure, real-time message feed. We will query Postgres directly from the browser without a single custom backend route.

Step 1: Define the Schema and Enforce RLS

Execute this DDL in your Supabase SQL Editor. Always enable RLS when creating tables; unshielded tables in the public schema allow anyone with your anon key to query or drop rows.

-- Create the messages table
CREATE TABLE public.messages (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID REFERENCES auth.users(id) ON DELETE CASCADE NOT NULL,
    content TEXT NOT NULL CHECK (char_length(content) BETWEEN 1 AND 500),
    is_pinned BOOLEAN DEFAULT FALSE NOT NULL,
    created_at TIMESTAMPTZ DEFAULT timezone('utc'::text, now()) NOT NULL
);

-- Index user_id and timestamp to avoid full-table scans during RLS filtering
CREATE INDEX idx_messages_user_id ON public.messages(user_id);
CREATE INDEX idx_messages_created_at ON public.messages(created_at DESC);

-- Lock down access immediately
ALTER TABLE public.messages ENABLE ROW LEVEL SECURITY;

Step 2: Write Granular Access Policies

RLS policies govern SELECT, INSERT, UPDATE, and DELETE statements. The built-in auth.uid() helper unpacks the sub claim from the active JWT session.

-- Read: Any authenticated user can view the channel feed
CREATE POLICY "Authenticated users can read messages"
ON public.messages
FOR SELECT
TO authenticated
USING (true);

-- Insert: Users can only write messages under their own identity
CREATE POLICY "Users can insert their own messages"
ON public.messages
FOR INSERT
TO authenticated
WITH CHECK (auth.uid() = user_id);

-- Update: Authors can modify their own content
CREATE POLICY "Users can update their own messages"
ON public.messages
FOR UPDATE
TO authenticated
USING (auth.uid() = user_id)
WITH CHECK (auth.uid() = user_id);

-- Delete: Authors can delete their own records
CREATE POLICY "Users can delete their own messages"
ON public.messages
FOR DELETE
TO authenticated
USING (auth.uid() = user_id);

Step 3: Publish to the Realtime Stream

PostgreSQL requires you to mark tables eligible for logical replication streaming:

-- Add the table to the Supabase replication publication
ALTER PUBLICATION supabase_realtime ADD TABLE public.messages;

Step 4: Initialize the Frontend Client

Install the official JavaScript client in your React, Vue, or Svelte project:

npm install @supabase/supabase-js

Instantiate the client with your project credentials. Your anonymous public key can safely ship in public client code; Postgres RLS policies, not secret API tokens, guard your data perimeter.

import { createClient } from '@supabase/supabase-js';

const supabaseUrl = 'https://xyzcompany.supabase.co';
const supabaseAnonKey = 'eyJhbGciOi...public-anon-key';

export const supabase = createClient(supabaseUrl, supabaseAnonKey);

Step 5: Authenticate, Write, and Subscribe

This snippet signs the user in, inserts a message directly via PostgREST, and subscribes to incoming live inserts over WebSockets:

// 1. Sign in with email and password
async function login(email, password) {
  const { data, error } = await supabase.auth.signInWithPassword({
    email,
    password,
  });
  if (error) throw error;
  return data.user;
}

// 2. Insert row directly to Postgres
async function postMessage(content, currentUserId) {
  const { data, error } = await supabase
    .from('messages')
    .insert([
      { content, user_id: currentUserId }
    ])
    .select();

  if (error) {
    console.error('Insert rejected by RLS or validation:', error.message);
    throw error;
  }
  return data[0];
}

// 3. Listen for incoming broadcasts
function subscribeToMessages(onNewMessage) {
  const channel = supabase
    .channel('public:messages')
    .on(
      'postgres_changes',
      {
        event: 'INSERT',
        schema: 'public',
        table: 'messages',
      },
      (payload) => {
        onNewMessage(payload.new);
      }
    )
    .subscribe((status) => {
      if (status === 'SUBSCRIBED') {
        console.info('Subscribed to live message feed');
      }
    });

  return () => {
    supabase.removeChannel(channel);
  };
}

Production Checklist and Traps

  • Index columns evaluated in RLS policies: If your policy evaluates auth.uid() = user_id across a table with 500,000 rows, a missing index forces a sequential scan on every request. Latency will spike from 5ms to over 800ms.
  • Guard your service_role secret: The service_role key bypasses every RLS rule. Bundle it exclusively into secure serverless functions or backend workers—never ship it to browser bundles or mobile apps.
  • Configure REPLICA IDENTITY for updates: By default, Postgres emits only changed column values or the primary key on deletes. To capture the full prior row payload, execute ALTER TABLE public.messages REPLICA IDENTITY FULL;.
  • Prevent connection exhaustion: Direct database connections tap out quickly under serverless spikes. Use Supavisor (Supabase’s built-in transaction pooler on port 6543) when connecting through Prisma, Drizzle, or serverless workers.

Wrapping Up

Delegating security checks to PostgreSQL policies saves you from maintaining hundreds of brittle API routes. By uniting managed Postgres, integrated identity, and WebSocket replication, Supabase cuts weeks of plumbing down to an afternoon of schema design.

When you encounter workflows that require private third-party secrets—such as Stripe webhooks or OpenAI completions—drop in a Supabase Edge Function (Deno-based). Let PostgreSQL handle the rest of your client data layer.

Share: