> 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

# Call Neon Functions from self-hosted Nhost

Replace the http, file_fdw, and pgmq Postgres extensions in a self-hosted Nhost backend with a Neon Function that Hasura and Neon triggers call.

Last updated: 2026-12-02

Self-hosted Nhost apps use Postgres extensions to call APIs from triggers, queue jobs, and read files. Lakebase Postgres doesn't support `http`, `file_fdw`, or `pgmq`, so this guide replaces them with a [Neon Function](https://neon.com/docs/compute/functions/overview) that Hasura and Neon triggers call.

In this guide, you'll:

- Write one Neon Function with a route per caller
- Call it from a Hasura event trigger and a Hasura action
- Import CSV files uploaded through Nhost Storage with a [storage trigger](https://neon.com/docs/compute/functions/triggers/object-storage)
- Process a job queue with a [scheduled trigger](https://neon.com/docs/compute/functions/triggers/schedule)

By the end, a CSV file uploaded through Nhost Storage is imported into a Lakebase Postgres table:

![Nhost Dashboard table browser showing the contacts table filled from an uploaded CSV](https://neon.com/guides/images/self-host-nhost-neon/nhost-dashboard-contacts.png)

The following table lists each extension and what replaces it on Neon:

| Extension | What it does in Nhost | On Neon |
| - | - | - |
| `http` | Calls an API from SQL or a trigger | A Hasura event trigger or action calls the function, which calls the API with `fetch()` |
| `file_fdw` | Reads files on the database server | A [storage trigger](https://neon.com/docs/compute/functions/triggers/object-storage) imports files from a bucket |
| `pgmq` | Message queue in Postgres | A queue table that a [scheduled trigger](https://neon.com/docs/compute/functions/triggers/schedule) drains, at most once a minute |

Neon injects `DATABASE_URL` and the Object Storage credentials into the function, so it uses the same branch as Nhost. Neon triggers don't fire on database changes, so Hasura [event triggers](https://hasura.io/docs/2.0/event-triggers/overview/) call the function when rows change. If you have Nhost Functions, rewrite each Express-style `(req, res)` handler as a `fetch(request)` handler.

## Prerequisites

- The backend from [Self-host Nhost with Lakebase Postgres and Neon Object Storage](https://neon.com/guides/self-host-nhost-neon), with its stack running
- Node.js 22 or later

## Set up your shell

Read the Hasura admin secret from `.env`, and sign in as the user you created in the [core setup](https://neon.com/guides/self-host-nhost-neon):

```bash
export ADMIN_SECRET=$(grep ^GRAPHQL_ADMIN_SECRET= .env | cut -d= -f2)

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)
```

## Create the app tables

The app uses four tables:

- `todos` holds each user's todos.
- `todo_events` records each call from the event trigger.
- `contacts` holds the rows imported from CSV files.
- `jobs` is the queue that replaces `pgmq`.

```sql filename="app.sql"
CREATE TABLE IF NOT EXISTS public.todos (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  user_id uuid NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
  title text NOT NULL,
  created_at timestamptz NOT NULL DEFAULT now()
);

CREATE TABLE IF NOT EXISTS public.todo_events (
  event_id text PRIMARY KEY,
  todo_id uuid NOT NULL,
  received_at timestamptz NOT NULL DEFAULT now()
);

CREATE TABLE IF NOT EXISTS public.contacts (
  file_id uuid NOT NULL,
  line int NOT NULL,
  user_id uuid NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
  name text NOT NULL,
  email text NOT NULL,
  PRIMARY KEY (file_id, line)
);

CREATE TABLE IF NOT EXISTS public.jobs (
  id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  payload jsonb NOT NULL,
  created_at timestamptz NOT NULL DEFAULT now(),
  done_at timestamptz
);
```

```bash
neon psql -- -f app.sql
```

## Write the function

Install the Postgres driver, the Neon Functions package, and the S3 client:

```bash
npm install pg @neon/functions @aws-sdk/client-s3
```

The function has one route for each caller. Function URLs are public, so each route first checks that Hasura or a Neon trigger sent the request. The `attachDatabasePool` call keeps the function running when Postgres closes an idle connection, for example after the compute scales to zero:

```ts filename="functions/hooks.ts"
import pg from 'pg';
import { attachDatabasePool } from '@neon/functions';
import { GetObjectCommand, S3Client } from '@aws-sdk/client-s3';

// Neon injects DATABASE_URL and the AWS_* Object Storage variables into every function.
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL, max: 3 });
attachDatabasePool(pool);
const s3 = new S3Client({
  region: process.env.AWS_REGION,
  endpoint: process.env.AWS_ENDPOINT_URL_S3,
  forcePathStyle: true,
});

const json = (body: unknown, status = 200) => Response.json(body, { status });

// Hasura event trigger: a todo was inserted.
async function onTodoCreated(body: any) {
  const todo = body.event.data.new;
  // Call an external API here with fetch(), as a trigger using the http extension would.
  await pool.query(
    `INSERT INTO todo_events (event_id, todo_id) VALUES ($1, $2) ON CONFLICT DO NOTHING`,
    [body.id, todo.id]
  );
  return json({ ok: true });
}

// Hasura action: a synchronous query that runs in the function.
async function todoSummary(body: any) {
  const userId = body.session_variables['x-hasura-user-id'];
  const { rows } = await pool.query(
    `SELECT count(*)::int AS total,
            (SELECT title FROM todos WHERE user_id = $1 ORDER BY created_at DESC LIMIT 1) AS latest
     FROM todos WHERE user_id = $1`,
    [userId]
  );
  return json(rows[0]);
}

// Storage trigger: an object was created in the nhost bucket.
async function importContacts(body: any) {
  const { bucket_name, object_key } = body.data;
  // Nhost Storage names each object after its file id, so look up the file first.
  const { rows } = await pool.query(
    `SELECT id, name, uploaded_by_user_id FROM storage.files WHERE id::text = $1`,
    [object_key]
  );
  const file = rows[0];
  if (!file?.name.endsWith('.csv')) return json({ skipped: true });

  const object = await s3.send(new GetObjectCommand({ Bucket: bucket_name, Key: object_key }));
  const lines = (await object.Body!.transformToString()).split(/\r?\n/).filter(Boolean).slice(1);
  for (const [i, line] of lines.entries()) {
    const [name, email] = line.split(',').map((v) => v.trim());
    await pool.query(
      `INSERT INTO contacts (file_id, line, user_id, name, email) VALUES ($1, $2, $3, $4, $5)
       ON CONFLICT DO NOTHING`,
      [file.id, i + 1, file.uploaded_by_user_id, name, email]
    );
  }
  return json({ imported: lines.length });
}

// Scheduled trigger: process the queued jobs, as a pgmq consumer would.
async function processJobs() {
  const client = await pool.connect();
  try {
    await client.query('BEGIN');
    // SKIP LOCKED lets two runs work at the same time without taking the same job.
    const { rows } = await client.query(
      `SELECT id, payload FROM jobs WHERE done_at IS NULL ORDER BY id LIMIT 20
       FOR UPDATE SKIP LOCKED`
    );
    for (const job of rows) {
      // Do the job's work here, for example call an API with fetch().
      await client.query(`UPDATE jobs SET done_at = now() WHERE id = $1`, [job.id]);
    }
    await client.query('COMMIT');
    return json({ processed: rows.length });
  } catch (err) {
    await client.query('ROLLBACK');
    throw err;
  } finally {
    client.release();
  }
}

export default {
  async fetch(request: Request): Promise<Response> {
    const path = new URL(request.url).pathname;
    // Hasura sends the shared secret. Neon strips X-Neon-* headers from outside callers,
    // so only a Neon trigger can send this header.
    const fromHasura = request.headers.get('x-hook-secret') === process.env.HOOK_SECRET;
    const fromTrigger = request.headers.has('x-neon-trigger-invocation-id');

    try {
      if (request.method === 'POST' && fromHasura && path === '/hasura/todo-created')
        return await onTodoCreated(await request.json());
      if (request.method === 'POST' && fromHasura && path === '/hasura/todo-summary')
        return await todoSummary(await request.json());
      if (request.method === 'POST' && fromTrigger && path === '/storage/import-contacts')
        return await importContacts(await request.json());
      if (request.method === 'POST' && fromTrigger && path === '/cron/process-jobs')
        return await processJobs();
      return json({ error: 'unauthorized' }, 401);
    } catch (err) {
      console.error(`hooks ${path} failed: ${(err as Error).message}`);
      return json({ error: 'internal error' }, 500);
    }
  },
};
```

## Declare the function and the triggers

Add a shared secret for Hasura to `.env`, generated with `openssl rand -hex 32`:

```bash filename=".env"
HOOK_SECRET=<random-hex>
```

Declare the function and its two triggers in `neon.ts`:

- The storage trigger runs on every upload to the `nhost` bucket. Nhost Storage names each file by its id, so the trigger can't filter by file name. Instead, the function skips files that aren't CSV files.
- The schedule trigger calls the function once a minute to process the queue.

```ts filename="neon.ts" {7-29}
import { defineConfig } from '@neon/config/v1';

export default defineConfig({
  buckets: {
    nhost: {},
  },
  functions: {
    hooks: {
      name: 'Nhost hooks',
      source: './functions/hooks.ts',
      env: {
        HOOK_SECRET: { value: process.env.HOOK_SECRET, required: true },
      },
    },
  },
  triggers: {
    'import-contacts': {
      type: 'storage_object_created',
      function: 'hooks',
      bucket: 'nhost',
      functionPath: '/storage/import-contacts',
    },
    'process-jobs': {
      type: 'schedule',
      function: 'hooks',
      cron: '* * * * *',
      functionPath: '/cron/process-jobs',
    },
  },
});
```

Deploy with `.env` loaded, so `neon.ts` can read `HOOK_SECRET`:

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

```text filename="Output"
→ Applying to branch main (br-icy-feather-bd73bdqp)
Waiting for Function builds to finish: hooks…
Applied changes
  + function hooks
      env set    HOOK_SECRET
  + trigger:hooks:import-contacts
  + trigger:hooks:process-jobs

Function URLs
  • hooks: https://br-icy-feather-bd73bdqp-hooks.compute.c-8.us-east-2.aws.neon.tech/
```

## Point Hasura at the function

The function URL is `https://<NEON_BRANCH_ID>-hooks<NEON_FUNCTION_HOST_SUFFIX>`, built from variables already in `.env`. Pass it and the secret to Hasura in `docker-compose.yaml`:

```yaml filename="docker-compose.yaml" {5-6}
services:
  graphql:
    environment:
      # ...the existing variables
      HOOKS_URL: https://${NEON_BRANCH_ID}-hooks${NEON_FUNCTION_HOST_SUFFIX}
      HOOK_SECRET: ${HOOK_SECRET:-}
```

Restart Hasura so it reads them:

```bash
docker compose up -d graphql
```

This request tracks the tables, gives the `user` role access, and creates the event trigger and the action. Hasura reads `{{HOOKS_URL}}` and the secret from its environment, so the secret isn't saved in its metadata:

```json filename="hasura-app.json"
{
  "type": "bulk",
  "args": [
    { "type": "pg_track_table", "args": { "source": "default", "table": "todos" } },
    { "type": "pg_track_table", "args": { "source": "default", "table": "contacts" } },
    {
      "type": "pg_create_insert_permission",
      "args": {
        "source": "default", "table": "todos", "role": "user",
        "permission": {
          "check": {}, "set": { "user_id": "X-Hasura-User-Id" }, "columns": ["title"]
        }
      }
    },
    {
      "type": "pg_create_select_permission",
      "args": {
        "source": "default", "table": "todos", "role": "user",
        "permission": {
          "filter": { "user_id": { "_eq": "X-Hasura-User-Id" } },
          "columns": ["id", "title", "created_at"]
        }
      }
    },
    {
      "type": "pg_create_select_permission",
      "args": {
        "source": "default", "table": "contacts", "role": "user",
        "permission": {
          "filter": { "user_id": { "_eq": "X-Hasura-User-Id" } },
          "columns": ["name", "email"]
        }
      }
    },
    {
      "type": "pg_create_event_trigger",
      "args": {
        "source": "default", "name": "todo_created", "table": "todos",
        "insert": { "columns": "*" },
        "webhook": "{{HOOKS_URL}}/hasura/todo-created",
        "headers": [{ "name": "x-hook-secret", "value_from_env": "HOOK_SECRET" }],
        "retry_conf": { "num_retries": 3, "interval_sec": 10, "timeout_sec": 60 }
      }
    },
    {
      "type": "set_custom_types",
      "args": {
        "objects": [
          {
            "name": "TodoSummary",
            "fields": [
              { "name": "total", "type": "Int!" },
              { "name": "latest", "type": "String" }
            ]
          }
        ]
      }
    },
    {
      "type": "create_action",
      "args": {
        "name": "todoSummary",
        "definition": {
          "kind": "synchronous", "type": "query", "output_type": "TodoSummary", "arguments": [],
          "handler": "{{HOOKS_URL}}/hasura/todo-summary",
          "headers": [{ "name": "x-hook-secret", "value_from_env": "HOOK_SECRET" }]
        }
      }
    },
    { "type": "create_action_permission", "args": { "action": "todoSummary", "role": "user" } }
  ]
}
```

```bash
curl -s http://localhost:8080/v1/metadata \
  -H "x-hasura-admin-secret: $ADMIN_SECRET" -d @hasura-app.json
```

## Test the event trigger and the action

Insert a todo as the signed-in user:

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

Hasura calls the function within a few seconds:

```bash
neon psql -- -x -c 'SELECT event_id, todo_id, received_at FROM todo_events;'
```

```text filename="Output"
-[ RECORD 1 ]-------------------------------------
event_id    | 43fb3e60-3d18-4fc3-bad2-b466772a7537
todo_id     | da10b832-5ab8-4196-9e87-69909b50db6e
received_at | 2026-11-30 14:44:28.296405+00
```

In the [Nhost Dashboard](https://neon.com/guides/nhost-neon-dashboard), the **Events** page for `todo_created` lists each delivery to the function:

![Nhost Dashboard Events page for the todo\_created event trigger, with each delivery to the Neon Function marked delivered after one try](https://neon.com/guides/images/self-host-nhost-neon/nhost-dashboard-event-trigger.png)

Call the action. Hasura forwards the caller's session, so the function returns that user's summary:

```bash
curl -s http://localhost:8080/v1/graphql -H "authorization: Bearer $ACCESS_TOKEN" \
  -d '{"query":"{ todoSummary { total latest } }"}'
```

```json filename="Output"
{"data":{"todoSummary":{"total":1,"latest":"Write the Nhost guide"}}}
```

## Import a CSV file

Upload a CSV through Nhost Storage:

```csv filename="contacts.csv"
name,email
Zhang Kai,zhang.kai@example.com
Dana Smith,dana.smith@example.com
```

```bash
curl -s http://localhost:5000/v1/files \
  -H "authorization: Bearer $ACCESS_TOKEN" -F 'file[]=@contacts.csv;type=text/csv'
```

The storage trigger imports the rows in under a second. Query them as the user who uploaded the file:

```bash
curl -s http://localhost:8080/v1/graphql -H "authorization: Bearer $ACCESS_TOKEN" \
  -d '{"query":"{ contacts { name email } }"}' | jq
```

```json filename="Output"
{
  "data": {
    "contacts": [
      { "name": "Zhang Kai", "email": "zhang.kai@example.com" },
      { "name": "Dana Smith", "email": "dana.smith@example.com" }
    ]
  }
}
```

## Process a job queue

With `pgmq`, you send a message to a queue and a worker reads it. Here, you insert a row into `jobs`, and the schedule trigger processes it within a minute:

```bash
neon psql -- -c "INSERT INTO jobs (payload) VALUES (jsonb_build_object('task', 'send-digest'));"
```

After a minute, check the job:

```bash
neon psql -- -x -c 'SELECT payload, done_at IS NOT NULL AS done FROM jobs;'
```

```text filename="Output"
-[ RECORD 1 ]--------------------
payload | {"task": "send-digest"}
done    | t
```

With more jobs in the queue, the Dashboard's SQL Console shows when the function processed each one:

![Nhost Dashboard SQL Console listing three jobs, each with a created\_at and a done\_at time set by the schedule trigger](https://neon.com/guides/images/self-host-nhost-neon/nhost-dashboard-jobs.png)

If a job fails, the function rolls back, so the job stays in the queue and the next run tries it again.

Each branch you create from now on gets its own copy of the `hooks` function, which works with that branch's data. Both triggers [start out disabled](https://neon.com/docs/compute/functions/triggers/overview#triggers-and-branching) on new branches. Turn them on with `neon triggers enable <trigger-id> --branch <branch>`.

If a branch was created before you added the function, deploy the function to it:

```bash
neon deploy --branch <branch> --env .env
```

This also replaces the connection details in `.env` with the branch's, so your main stack would connect to the branch the next time it starts. Point `.env` back at `main` afterward:

```bash
neon env pull --branch main --file .env
```

## Next steps

- **Realtime:** push rows to signed-in Nhost users as they change with [Push database changes to Nhost users with Neon Realtime](https://neon.com/guides/nhost-neon-realtime).
- **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).
- **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).

---

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-functions"}` to https://feedback.neon.tech/ (no auth required).
