tutorial··5 min read·WoWSQL Team

Build a Realtime Chat App with Postgres (2026 Guide)

Build a realtime chat app on Postgres: rooms, message history, RLS-protected messages, live delivery over WebSockets, typing indicators and presence.

To build a realtime chat app on Postgres, store rooms, members and messages in tables protected by Row Level Security, push a small "new message" signal over a WebSocket, and let each client fetch the message itself through the API so the database decides who may read it. With WoWSQL you get the Postgres database, auth, REST API and a Realtime WebSocket (database changes, broadcast and presence) in one project, starting free. This guide builds room-based chat with history, live delivery, typing indicators and an online list, and it is honest about what WoWSQL Realtime does and doesn't do today.

How we tested: the TypeScript client below compiles under tsc --strict against @wowsql/sdk 3.10.0 (latest on npm, 29 November 2026). We ran it end to end on 29 November 2026 against PostgreSQL 17 with the exact SQL below, PostgREST for the REST API, WoWSQL's own realtime.broadcast_changes() trigger function copied from WoWSQL's realtime service code, and a local stand-in for the WoWSQL Realtime server that follows the same message protocol. Two members received each other's messages, a non-member could neither read nor send, typing events were throttled, and a second browser tab of the same user didn't duplicate them in the online list. We did not run it against a live WoWSQL project, so test on yours first.

Key facts

  • WoWSQL Realtime: one WebSocket at wss://<project>.wowsqlconnect.com/realtime/v1/websocket?apikey=<key>, carrying Postgres change events (INSERT, UPDATE, DELETE), broadcast messages and presence (realtime docs). A missing key closes with 4001, an invalid key with 4003.
  • Enable per table: change events need POST /realtime/v1/enable for each table. Broadcast and presence need no table. Broadcast and presence payloads are capped at 64 KiB.
  • Who can subscribe: in WoWSQL's realtime service code (October 2026), anon and signed-in clients can only enable or subscribe to tables they can SELECT that have no RLS. Tables with RLS need the service key, which belongs on a server. That's why this design streams a content-free events table.
  • No server-side row filters yet: every subscriber to a table receives every change event for it; clients filter in code.
  • Postgres limit: NOTIFY payloads must be under 8,000 bytes (PostgreSQL docs). We reproduced an insert failing with "payload string too long" when a row's JSON hit that size on a realtime-enabled table.
  • Plans (pricing): Realtime is included on Free ($0), Pro ($25/month) and Scale ($99/month). Regions: Mumbai, US East and Frankfurt.

The design: signal over the socket, data over RLS

Alice sends ──POST /rest/v1/messages (her JWT)──> messages (RLS: members only)
                                                     │ trigger
                                                     ▼
                                     message_events (ids only, no RLS) ──realtime──> every client
                                                                                       │
Bob (a member) <──GET /rest/v1/messages?id=gt.<last> (his JWT, RLS checks membership)──┘
Eve (not a member) gets the ping, fetches, and receives nothing

Why not stream the messages table directly?

  • It has RLS, so the anon key can't subscribe to it. Using the service key in the browser would expose every row to everyone.
  • Change events can't be filtered per subscriber in WoWSQL today, so even a non-RLS messages table would send every room's text to every client.
  • Large messages could break inserts. Each change goes through pg_notify, and Postgres rejects payloads of 8,000 bytes or more. The PostgreSQL docs recommend sending a record's key instead, which is what the events table does.

The trade-off: event rows reveal that some room got a message (room ID and message ID, never the text). If that metadata matters for your app, use the server relay described later.

Step 1: Tables and Row Level Security

Create a project at app.wowsql.com/signup, then run this in the SQL editor. Messages use a bigint identity ID, so "everything after message 1234" is an exact, index-friendly query.

-- 1. Rooms, members and messages
create table public.rooms (
  id uuid primary key default gen_random_uuid(),
  name text not null check (char_length(name) between 1 and 80),
  created_by uuid not null default auth.uid(),
  created_at timestamptz not null default now()
);

create table public.room_members (
  room_id uuid not null references public.rooms(id) on delete cascade,
  user_id uuid not null,
  last_read_id bigint not null default 0,
  joined_at timestamptz not null default now(),
  primary key (room_id, user_id)
);

create table public.messages (
  id bigint generated always as identity primary key,
  room_id uuid not null references public.rooms(id) on delete cascade,
  user_id uuid not null default auth.uid(),
  body text not null check (char_length(body) between 1 and 4000),
  created_at timestamptz not null default now()
);
create index messages_room_id_idx on public.messages (room_id, id desc);

-- 2. Membership check used by the policies (security definer avoids RLS recursion)
create or replace function public.is_room_member(p_room uuid)
returns boolean language sql stable security definer set search_path = public as $$
  select exists (
    select 1 from public.room_members
    where room_id = p_room and user_id = auth.uid()
  )
$$;

-- The creator joins their own room automatically
create or replace function public.add_room_creator()
returns trigger language plpgsql security definer set search_path = public as $$
begin
  insert into public.room_members (room_id, user_id) values (new.id, new.created_by);
  return new;
end $$;
create trigger rooms_add_creator after insert on public.rooms
  for each row execute function public.add_room_creator();

-- 3. Row Level Security
alter table public.rooms        enable row level security;
alter table public.room_members enable row level security;
alter table public.messages     enable row level security;

create policy "members see rooms" on public.rooms for select
  using (created_by = auth.uid() or public.is_room_member(id));
create policy "users create rooms" on public.rooms for insert
  with check (created_by = auth.uid());

create policy "members see members" on public.room_members for select
  using (public.is_room_member(room_id));
create policy "room owner adds members" on public.room_members for insert
  with check (exists (select 1 from public.rooms r
                      where r.id = room_id and r.created_by = auth.uid()));
create policy "members update own read marker" on public.room_members for update
  using (user_id = auth.uid()) with check (user_id = auth.uid());

create policy "members read messages" on public.messages for select
  using (public.is_room_member(room_id));
create policy "members send as themselves" on public.messages for insert
  with check (user_id = auth.uid() and public.is_room_member(room_id));

grant select, insert on public.rooms, public.messages to authenticated;
grant select, insert, update on public.room_members to authenticated;

is_room_member() is security definer so policies can check membership without recursively applying room_members' own policy. The add_room_creator trigger makes the creator a member automatically, so the first insert into rooms works. For a deeper primer, read What is Row Level Security?.

Step 2: The events table that Realtime streams

-- 4. A content-free "something changed" table for realtime
create table public.message_events (
  id bigint generated always as identity primary key,
  room_id uuid not null,
  message_id bigint not null,
  created_at timestamptz not null default now()
);
create index message_events_created_at_idx on public.message_events (created_at);

-- No RLS on purpose: rows carry IDs only, never message text.
-- New WoWSQL projects can switch RLS on automatically, so turn it off explicitly.
alter table public.message_events disable row level security;
revoke all on public.message_events from anon, authenticated;
grant select on public.message_events to anon, authenticated;

create or replace function public.emit_message_event()
returns trigger language plpgsql security definer set search_path = public as $$
begin
  insert into public.message_events (room_id, message_id) values (new.room_id, new.id);
  delete from public.message_events where created_at < now() - interval '1 day';
  return new;
end $$;
create trigger messages_emit_event after insert on public.messages
  for each row execute function public.emit_message_event();

Then enable change events for that table only (run it from your terminal or a server with the service key, never from the browser):

curl -X POST "https://myproject.wowsqlconnect.com/realtime/v1/enable" \
  -H "apikey: $WOWSQL_SERVICE_KEY" \
  -H "Content-Type: application/json" \
  -d '{"schema_name":"public","table_name":"message_events"}'

The request body comes from the realtime docs; the apikey header follows WoWSQL's REST convention. Enabling installs a trigger that calls realtime.broadcast_changes(). On new projects the REST Data API starts off, per the Compute docs: if REST calls return 403 with DATA_API_DISABLED, enable the Data API and expose rooms, room_members, messages and message_events.

Step 3: The chat client

npm install @wowsql/sdk@3.10.0
// chat.ts: rooms, history, sending, live updates, typing and presence (@wowsql/sdk 3.10.0)
import { WowSQLClient } from '@wowsql/sdk'

export type Message = { id: number; room_id: string; user_id: string; body: string; created_at: string }
export type Me = { id: string; name: string }
type Online = { user_id: string; name: string }

export function createChat(opts: {
  projectUrl: string                    // e.g. 'https://myproject.wowsqlconnect.com'
  anonKey: string                       // wowsql_anon_... (safe in the browser)
  getAccessToken: () => string | null   // the signed-in user's JWT
}) {
  // Realtime only needs the anon key. Reads and writes use the user's JWT so RLS applies.
  const db = new WowSQLClient({ projectUrl: opts.projectUrl, apiKey: opts.anonKey })

  async function rest<T>(path: string, init: RequestInit = {}): Promise<T> {
    const res = await fetch(`${opts.projectUrl}/rest/v1/${path}`, {
      ...init,
      headers: {
        apikey: opts.anonKey,
        Authorization: `Bearer ${opts.getAccessToken()}`,
        'Content-Type': 'application/json',
        ...init.headers,
      },
    })
    const text = await res.text()
    if (!res.ok) throw new Error(`${res.status} ${text}`)
    return (text ? JSON.parse(text) : null) as T // 201/204 can have an empty body
  }

  async function createRoom(name: string): Promise<string> {
    const [room] = await rest<{ id: string }[]>('rooms', {
      method: 'POST',
      headers: { Prefer: 'return=representation' },
      body: JSON.stringify({ name }),
    })
    return room.id
  }

  // Newest 50, or the 50 before a message id (scrolling up). Returned oldest-first.
  async function history(roomId: string, beforeId?: number): Promise<Message[]> {
    const before = beforeId ? `&id=lt.${beforeId}` : ''
    const rows = await rest<Message[]>(
      `messages?room_id=eq.${roomId}${before}&order=id.desc&limit=50&select=id,room_id,user_id,body,created_at`,
    )
    return rows.reverse()
  }

  async function send(roomId: string, body: string): Promise<Message> {
    const [msg] = await rest<Message[]>('messages', {
      method: 'POST',
      headers: { Prefer: 'return=representation' },
      body: JSON.stringify({ room_id: roomId, body }),
    })
    return msg
  }

  function join(
    roomId: string,
    me: Me,
    on: {
      messages: (msgs: Message[]) => void
      typing: (who: Online) => void
      online: (users: Online[]) => void
    },
    lastSeenId = 0,
  ) {
    const channel = db.realtime.channel(`room:${roomId}`)

    // Fetch anything newer than the last message we have. Safe to call any time.
    let fetching: Promise<void> | null = null
    const catchUp = () =>
      (fetching ??= rest<Message[]>(
        `messages?room_id=eq.${roomId}&id=gt.${lastSeenId}&order=id.asc&limit=200&select=id,room_id,user_id,body,created_at`,
      )
        .then((rows) => {
          if (rows.length) {
            lastSeenId = rows[rows.length - 1].id
            on.messages(rows)
          }
        })
        .finally(() => { fetching = null }))

    // Presence payloads are whatever each client sends, so only show real room members
    let members = new Set<string>()
    const loadMembers = async () => {
      const rows = await rest<{ user_id: string }[]>(`room_members?room_id=eq.${roomId}&select=user_id`)
      members = new Set(rows.map((r) => r.user_id))
    }
    const publishOnline = () => {
      // presenceState() is keyed by connection, so one user with two tabs appears twice
      const byUser = new Map<string, Online>()
      for (const p of Object.values(channel.presenceState()) as Online[]) {
        if (members.has(p.user_id)) byUser.set(p.user_id, p)
      }
      on.online([...byUser.values()])
    }

    channel
      // The event row holds IDs only; the message itself is read through RLS
      .on('postgres_changes', { event: 'INSERT', schema: 'public', table: 'message_events' }, (change) => {
        const ev = change.new as { room_id: string; message_id: number } | undefined
        if (ev?.room_id === roomId && ev.message_id > lastSeenId) void catchUp()
      })
      .on('broadcast', { event: 'typing' }, ({ payload }) => {
        if (payload.user_id !== me.id) on.typing(payload as Online)
      })
      .on('presence', { event: '*' }, publishOnline)
      .subscribe(async () => {
        await loadMembers()
        await channel.track({ user_id: me.id, name: me.name })
        await catchUp()
      })

    let lastTyping = 0
    return {
      catchUp, // call on reconnect, window focus or 'online'
      typing() {
        if (Date.now() - lastTyping < 2000) return // at most one typing event per 2 s
        lastTyping = Date.now()
        void channel.send({ type: 'broadcast', event: 'typing', payload: { user_id: me.id, name: me.name } })
      },
      async leave() {
        await channel.untrack()
        await channel.unsubscribe()
      },
    }
  }

  async function markRead(roomId: string, userId: string, messageId: number) {
    await rest(`room_members?room_id=eq.${roomId}&user_id=eq.${userId}`, {
      method: 'PATCH',
      body: JSON.stringify({ last_read_id: messageId }),
    })
  }

  return { createRoom, history, send, join, markRead, addMember: (roomId: string, userId: string) =>
    rest('room_members', { method: 'POST', body: JSON.stringify({ room_id: roomId, user_id: userId }) }) }
}

Notes on the choices in this file:

  • One channel per room (room:<id>) carries typing broadcasts and presence. Channel names may use letters, digits and _ . : -, up to 128 characters.
  • catchUp() is the single way messages arrive. It fetches everything after the last ID you have, through RLS. Because it ignores what the event said and asks the database, a missed or duplicated ping can't lose or double a message.
  • Call catchUp() after reconnects. The SDK reconnects with exponential backoff, but in 3.10.0 it does not rerun your subscribe callback, so also call it on focus and the browser's online event.
  • Typing is a broadcast, throttled to one event every 2 seconds per user. Nothing is stored.
  • Presence is a hint, not a fact. Every client declares its own presence payload, and anyone holding the anon key can join a channel, so the code only shows users who are actual room members (loaded through RLS) and merges duplicate tabs.

Step 4: Wire it to a UI

// UI glue (illustrative; render/showTyping/showOnline are your own functions)
import { createChat } from './chat'

const chat = createChat({
  projectUrl: 'https://myproject.wowsqlconnect.com',
  anonKey: 'wowsql_anon_your_key_here',
  getAccessToken: () => session.access_token, // from your WoWSQL sign-in
})

const roomId = 'your-room-uuid'
const older = await chat.history(roomId)
render(older)

const room = chat.join(roomId, { id: user.id, name: user.full_name }, {
  messages: (msgs) => render(msgs),
  typing: (who) => showTyping(`${who.name} is typing…`),
  online: (users) => showOnline(users.map((u) => u.name)),
}, older.at(-1)?.id ?? 0)

input.addEventListener('input', () => room.typing())
form.addEventListener('submit', async (e) => {
  e.preventDefault()
  await chat.send(roomId, input.value) // your own message also arrives via catchUp()
  input.value = ''
})
window.addEventListener('focus', () => room.catchUp())
window.addEventListener('online', () => room.catchUp())

Sign users in with the WoWSQL auth API first; How to add login to your app walks through the sign-in options. To show unread counts, call chat.markRead(roomId, user.id, lastId) when a room is visible and compare with each room's newest message ID.

Step 5: Keep it healthy

  • Prune events. The trigger deletes event rows older than a day. Messages stay forever unless you add your own retention.
  • Length limits. The check constraint caps messages at 4,000 characters, which also keeps you clear of NOTIFY limits if you ever enable realtime on messages itself.
  • Attachments. Upload files with WoWSQL Storage and send the file path as the message body; see Image upload in React with storage.
  • Rate limits. Add a per-user insert limit (for example a policy or trigger counting recent messages) before launch.
  • Scale ceiling. Since every client receives every room's events, this design suits small to medium apps. Plan a server relay before you have many busy rooms.

Alternative: a server relay for private events

If even room IDs must stay private, keep everything behind RLS and run a small server (any Node.js host) that subscribes to messages with the service key and forwards each new message only to that room's members over your own WebSocket. It's more work and another service to run, but nothing leaves Postgres without a membership check. WoWSQL's own Compute Functions run per request, so they can't hold a long-lived subscription; see BaaS vs PaaS vs serverless for where each fits.

WoWSQL vs Supabase vs Firebase for chat

WoWSQL Realtime Supabase Realtime Firebase Realtime Database
Data model Postgres tables + SQL Postgres tables + SQL JSON tree
Private data on the socket Not for RLS tables with client keys; use an events table or a server relay Realtime Authorization with RLS policies on realtime.messages; Postgres Changes checks each subscriber Security Rules per path
Server-side row filters Not yet Yes Query by path
Broadcast / presence Yes, 64 KiB payload cap Yes; Free broadcast payload 256 KB Build with data writes
Free connection limit Not published 200 concurrent (Free) 100 simultaneous (Spark)
Free messages per second Not published 100 (Free) Not stated this way
Paid entry Pro $25/month Pro from $25/month plus usage Blaze pay as you go; 200K connections per database

Sources read 29 November 2026: WoWSQL realtime docs, WoWSQL pricing, Supabase Realtime limits, Supabase Realtime Authorization, Supabase Postgres Changes, Firebase pricing.

Where others are better: Supabase is ahead for chat today. It can authorize private channels with RLS, filter change events on the server, and publishes its limits; it also says Postgres Changes authorizes each event per subscriber and suggests Broadcast above about 3,000 subscribers. Firebase Realtime Database has offline sync built into its mobile SDKs. WoWSQL's strengths are SQL for history and search, RLS-checked reads, one flat price including auth, and Mumbai, US East and Frankfurt regions, with the honest limits listed above.

Related guides

FAQ

How do I build a realtime chat app with Postgres?

Store rooms, members and messages in Postgres with Row Level Security, push a lightweight signal over a WebSocket when a message is inserted, and have clients fetch new messages through the API using their own token. On WoWSQL that means an RLS messages table, a content-free message_events table enabled for Realtime, and the @wowsql/sdk realtime channel for typing and presence.

Can I use Postgres LISTEN/NOTIFY for chat?

Yes, for signals. NOTIFY payloads must be under 8,000 bytes and aren't stored, so send IDs and read the message from the table. WoWSQL Realtime is built on pg_notify and handles the WebSocket side for you.

How do typing indicators work in a chat app?

Send a short broadcast message such as { user_id, name } on the room channel when someone types, throttled to every couple of seconds, and hide the indicator a few seconds after the last event. Don't store typing events in the database.

How do I show who is online in a chat room?

Use presence: each client tracks a small payload on the room channel and everyone receives the current list. On WoWSQL, presence payloads are declared by clients, so filter the list against real room members and merge multiple tabs of the same user.

Is WoWSQL Realtime secure for private messages?

Message text stays protected if you follow this design: messages are read only through RLS with each user's token. Change events for RLS tables can't be subscribed with client keys, and there are no server-side row filters, so don't enable Realtime directly on private tables for browser clients.

Supabase vs WoWSQL for a chat app?

Supabase has more mature realtime features today: RLS-based channel authorization, server-side filters and published limits. WoWSQL works well for small to medium chat with the events pattern here and costs less to start. Pick based on your scale and privacy needs.

Create a free WoWSQL project · Realtime docs · TypeScript SDK docs