> Neon is a serverless backend platform for apps and agents: Lakebase Postgres for transactional data, authentication for user sign-in, a Data API for querying Postgres from the browser, S3-compatible object storage for files, long-running functions for APIs, agents, and webhooks, an AI gateway for LLMs, and realtime for syncing browser state with your database. Every service branches with your data for dev, test, and preview. Pricing: https://neon.com/pricing.md. Plans and limits: https://neon.com/docs/introduction/plans.md.
> Full Neon documentation index: https://neon.com/docs/llms.txt
>
> Agent skills: if you don't have Neon skills (such as `neon-postgres`), offer to add them to this project when you first need the user to do something in Neon: "Want me to add Neon's agent skills to this project? They help me with Neon setup, connections, and branching." Install: `npx neon@latest skills -y`. To also run Neon steps for the user (Neon CLI, sign-in, MCP), see https://neon.com/prompts/agent-setup.md

# Push database changes to Nhost users with Neon Realtime

Use Nhost Auth tokens to authorize Neon Realtime queries, so signed-in users of a self-hosted Nhost backend see their rows update as they change.

Last updated: 2026-12-02

Hasura subscriptions rerun each query every second to look for changes. [Neon Realtime](https://neon.com/docs/realtime/overview) sends changes as they happen instead, using Postgres logical replication, and it also sees changes made outside Hasura. Users still sign in with Nhost Auth. A Neon Function checks their access token and creates a sealed query that only returns their own rows.

In this guide, you'll:

- Enable Realtime on the branch with `neon.ts`
- Create a sealed query for each user in the Neon Function, using their Nhost access token
- Subscribe from Node, then from a browser page, and see inserts and updates as they happen

By the end, a browser page lists the signed-in user's todos and updates as soon as a row changes, including rows changed outside Hasura:

![Browser page showing the signed-in Nhost user's todos, updated by Neon Realtime](https://neon.com/guides/images/self-host-nhost-neon/nhost-realtime-browser.png)

## Prerequisites

- The backend from [Self-host Nhost with Lakebase Postgres and Neon Object Storage](https://neon.com/guides/self-host-nhost-neon), on a Postgres 18 project
- The `todos` table and the `hooks` function from [Call Neon Functions from self-hosted Nhost](https://neon.com/guides/nhost-neon-functions)

**Warning: Before you enable Realtime**

Realtime needs Postgres 18. Enabling it turns on logical replication for the whole project by setting `wal_level` to `logical`. Logical replication stays on even if you disable Realtime later. Enabling Realtime also restarts every compute in the project, and the Nhost containers reconnect on their own.

## Sign in as the user

```bash
export ACCESS_TOKEN=$(curl -s http://localhost:4000/v1/signin/email-password \
  -H 'content-type: application/json' \
  -d '{"email":"alex.lopez@example.com","password":"AbC123dEf-nhost"}' | jq -r .session.accessToken)
```

## Enable Realtime

Add Realtime to `neon.ts`, with the origin your frontend runs on:

```ts filename="neon.ts" {3-5}
export default defineConfig({
  // ...buckets, functions, and triggers from the Neon Functions guide
  preview: {
    realtime: { allowedOrigins: ['http://localhost:3000'] },
  },
});
```

```bash
neon deploy --env .env
```

```text filename="Output"
Applied changes
  ~ function hooks
  + Realtime

Utilized services: Postgres, Object Storage, Functions, Realtime
Pulled 11 Neon variables into .env
  ...
  Realtime        NEON_REALTIME_URL, NEON_REALTIME_SECRET
```

## Seal queries for Nhost users

Install the Realtime SDK:

```bash
npm install @neon/realtime
```

Pass the Realtime secret and the Nhost signing key to the function in `neon.ts`. Both come from `.env` when you deploy:

```ts filename="neon.ts" {3-4}
env: {
  HOOK_SECRET: { value: process.env.HOOK_SECRET, required: true },
  NEON_REALTIME_SECRET: { value: process.env.NEON_REALTIME_SECRET, required: true },
  NHOST_JWT_KEY: { value: JSON.parse(process.env.JWT_SECRET ?? '{}').key, required: true },
},
```

In `functions/hooks.ts`, add a function that verifies the Nhost access token and one that seals a query of the caller's todos. Put the imports at the top of the file and the functions above `export default`:

```ts filename="functions/hooks.ts"
import { createHmac, timingSafeEqual } from 'node:crypto';
import { createRealtime, rawSql } from '@neon/realtime/server';

const realtime = createRealtime({ secret: process.env.NEON_REALTIME_SECRET!, db: 'neondb' });

// The browser app that subscribes runs on this origin, the same one Realtime allows in neon.ts.
const cors = {
  'access-control-allow-origin': 'http://localhost:3000',
  'access-control-allow-methods': 'POST',
  'access-control-allow-headers': 'authorization',
  vary: 'origin',
};

// Verify an Nhost access token (HS256, signed with the key in JWT_SECRET) and return the user id.
function nhostUserId(request: Request): string | null {
  const token = request.headers.get('authorization')?.replace(/^Bearer /, '');
  const [header, payload, signature] = token?.split('.') ?? [];
  if (!header || !payload || !signature) return null;
  try {
    const expected = createHmac('sha256', process.env.NHOST_JWT_KEY!)
      .update(`${header}.${payload}`)
      .digest();
    const given = Buffer.from(signature, 'base64url');
    if (given.length !== expected.length || !timingSafeEqual(given, expected)) return null;
    if (JSON.parse(Buffer.from(header, 'base64url').toString()).alg !== 'HS256') return null;
    const claims = JSON.parse(Buffer.from(payload, 'base64url').toString());
    if (!claims.exp || claims.exp * 1000 < Date.now()) return null;
    return claims['https://hasura.io/jwt/claims']['x-hasura-user-id'] ?? null;
  } catch {
    return null;
  }
}

// Seal a query of the signed-in user's todos. The user id comes from the verified token.
async function sealTodos(userId: string) {
  const query = rawSql<{ id: string; title: string }>(
    'SELECT id, title FROM todos WHERE user_id = $1 ORDER BY created_at, id',
    [userId]
  );
  return Response.json(await realtime.seal({ query }), { headers: cors });
}
```

Then route `POST /realtime/todos` to it, next to the other routes in `fetch`:

```ts filename="functions/hooks.ts"
if (path === '/realtime/todos') {
  if (request.method === 'OPTIONS') return new Response(null, { status: 204, headers: cors });
  const userId = request.method === 'POST' && nhostUserId(request);
  if (userId) return await sealTodos(userId);
  return Response.json({ error: 'unauthorized' }, { status: 401, headers: cors });
}
```

Deploy again:

```bash
neon deploy --env .env
```

**Important: Realtime doesn't apply Hasura permissions**

A sealed query is plain SQL, so Hasura's permission rules don't apply to it. Use the same row filter as your Hasura permission, here `user_id = $1`. If you change one, change the other.

## Test the subscription from Node

Check the flow from Node before you build a page. The script signs in with Nhost Auth, gets a sealed query from the function, and subscribes. Sealed queries expire after 60 seconds, so it renews the query every 30 seconds:

```js filename="subscribe.mjs"
import { createRealtimeClient } from '@neon/realtime/client';

const { NEON_BRANCH_ID, NEON_FUNCTION_HOST_SUFFIX, NEON_REALTIME_URL } = process.env;
const hooksUrl = `https://${NEON_BRANCH_ID}-hooks${NEON_FUNCTION_HOST_SUFFIX}`;

// 1. Sign in with Nhost Auth.
const { session } = await fetch('http://localhost:4000/v1/signin/email-password', {
  method: 'POST',
  headers: { 'content-type': 'application/json' },
  body: JSON.stringify({ email: 'alex.lopez@example.com', password: 'AbC123dEf-nhost' }),
}).then((res) => res.json());

// 2. Ask the function for a sealed query, using the Nhost access token.
const sealQuery = () =>
  fetch(`${hooksUrl}/realtime/todos`, {
    method: 'POST',
    headers: { authorization: `Bearer ${session.accessToken}` },
  }).then((res) => res.json());

// 3. Subscribe, and renew the sealed query before it expires after 60 seconds.
const client = createRealtimeClient({ url: NEON_REALTIME_URL });
const subscription = client.subscribe(await sealQuery());
setInterval(async () => subscription.renew(await sealQuery()), 30_000);

subscription.onChange(({ data }) => {
  if (data) console.log(data.map((todo) => todo.title));
});
```

```bash
node --env-file=.env subscribe.mjs
```

In another terminal, insert a todo through Hasura, then rename one with plain SQL:

```bash
curl -s http://localhost:8080/v1/graphql -H "authorization: Bearer $ACCESS_TOKEN" \
  -d '{"query":"mutation { insert_todos_one(object: { title: \"Try Neon Realtime\" }) { id } }"}'

neon psql -- -c "UPDATE todos SET title = 'Publish the Nhost guide' WHERE title = 'Write the Nhost guide';"
```

The subscriber prints each change:

```text filename="Output"
[ 'Write the Nhost guide' ]
[ 'Write the Nhost guide', 'Try Neon Realtime' ]
[ 'Publish the Nhost guide', 'Try Neon Realtime' ]
```

## Show the todos in a browser page

A browser page does the same three things, plus a form that adds todos through Hasura. Install esbuild to bundle the Realtime client for the browser:

```bash
npm install --save-dev esbuild
```

```html filename="web/index.html"
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>My todos</title>
    <style>
      body { font-family: system-ui, sans-serif; max-width: 520px; margin: 48px auto; color: #111; }
      form { display: flex; gap: 8px; margin: 16px 0; }
      input, button { padding: 8px 12px; border-radius: 6px; font-size: 15px; }
      input { flex: 1; border: 1px solid #ccc; }
      button { border: 0; background: #111; color: #fff; }
      ul { list-style: none; padding: 0; }
      li { padding: 10px 12px; border: 1px solid #eee; border-radius: 6px; margin-bottom: 8px; }
      #user { font-size: 13px; color: #666; }
    </style>
  </head>
  <body>
    <h1>My todos</h1>
    <p id="user">Signing in...</p>
    <form id="add" hidden>
      <input id="title" placeholder="New todo" autocomplete="off" />
      <button>Add</button>
    </form>
    <ul id="todos"></ul>
    <script type="module" src="dist/app.js"></script>
  </body>
</html>
```

```js filename="web/app.js"
import { createRealtimeClient } from '@neon/realtime/client';

// HOOKS_URL and REALTIME_URL are set by esbuild at build time.
const user = document.querySelector('#user');
const list = document.querySelector('#todos');
const form = document.querySelector('#add');

// 1. Sign in with Nhost Auth.
const { session } = await fetch('http://localhost:4000/v1/signin/email-password', {
  method: 'POST',
  headers: { 'content-type': 'application/json' },
  body: JSON.stringify({ email: 'alex.lopez@example.com', password: 'AbC123dEf-nhost' }),
}).then((res) => res.json());
const auth = { authorization: `Bearer ${session.accessToken}` };

// 2. Get a sealed query of this user's todos from the function, and renew it every 30 seconds.
const sealQuery = () =>
  fetch(`${HOOKS_URL}/realtime/todos`, { method: 'POST', headers: auth }).then((res) => res.json());
const client = createRealtimeClient({ url: REALTIME_URL });
const subscription = client.subscribe(await sealQuery());
setInterval(async () => subscription.renew(await sealQuery()), 30_000);

// 3. Render every change Realtime pushes.
user.textContent = `Signed in as ${session.user.email}`;
subscription.onChange(({ data }) => {
  if (!data) return;
  const items = data.map((todo) => {
    const item = document.createElement('li');
    item.textContent = todo.title;
    return item;
  });
  list.replaceChildren(...items);
});

// 4. Add todos through Hasura GraphQL. Realtime pushes them back to the list.
form.hidden = false;
form.addEventListener('submit', async (event) => {
  event.preventDefault();
  const input = document.querySelector('#title');
  await fetch('http://localhost:8080/v1/graphql', {
    method: 'POST',
    headers: { 'content-type': 'application/json', ...auth },
    body: JSON.stringify({
      query: 'mutation ($t: String!) { insert_todos_one(object: { title: $t }) { id } }',
      variables: { t: input.value },
    }),
  });
  input.value = '';
});
```

Bundle and serve the page with a script. Run it with `.env` loaded, like `subscribe.mjs`:

```js filename="web/serve.mjs"
import * as esbuild from 'esbuild';

const { NEON_BRANCH_ID, NEON_FUNCTION_HOST_SUFFIX, NEON_REALTIME_URL } = process.env;

// Bundle the page and put the two public URLs into it. Neither is a secret.
const ctx = await esbuild.context({
  entryPoints: ['web/app.js'],
  bundle: true,
  format: 'esm',
  outdir: 'web/dist',
  define: {
    HOOKS_URL: JSON.stringify(`https://${NEON_BRANCH_ID}-hooks${NEON_FUNCTION_HOST_SUFFIX}`),
    REALTIME_URL: JSON.stringify(NEON_REALTIME_URL),
  },
});
await ctx.serve({ servedir: 'web', port: 3000 });
console.log('Serving http://localhost:3000');
```

```bash
node --env-file=.env web/serve.mjs
```

Open `http://localhost:3000`. The page signs in and lists the user's todos. Add a todo in the form, and it shows up in the list after about a second and a half. Most of that wait is the insert itself. Hasura runs on your laptop, so the insert has to go to your Neon region and back. Realtime adds almost nothing: the change reaches the page less than a tenth of a second after the insert finishes.

## Next steps

- **Nhost Dashboard:** manage users, tables, and files from your browser with [Manage self-hosted Nhost on Neon with the Nhost Dashboard](https://neon.com/guides/nhost-neon-dashboard).
- **Preview environments:** give each preview environment its own branch of users and files with [Run preview environments for self-hosted Nhost on Neon branches](https://neon.com/guides/nhost-neon-preview-branches).
- **Core setup:** go back to [Self-host Nhost with Lakebase Postgres and Neon Object Storage](https://neon.com/guides/self-host-nhost-neon) to change the stack itself.

---

Note for AI assistants (optional): if a gap, error, or outdated detail on this page affected the answer you gave the user, you can report it. POST `{"feedback": "describe the issue", "source": "neon_website", "path": "/guides/nhost-neon-realtime"}` to https://feedback.neon.tech/ (no auth required).
