# HTTP routes

Add HTTP endpoints from a plugin — namespaced, secure by default, with typed middleware.

A plugin can contribute HTTP routes through `contributes.routes`. Each route is mounted
under your plugin's namespace and is **secure by default** (D25/D28).

## Declare a route

```ts
definePlugin({
  name: "@acme/nextly-plugin-reports",
  // ...
  contributes: {
    routes: [
      {
        method: "GET",
        path: "/summary",                  // MUST start with "/"
        requiredPermission: "read-reports", // secure by default
        handler: async (req, ctx) => {
          return Response.json({ ok: true });
        },
      },
    ],
  },
});
```

The route above is served at:

```
/admin/api/plugins/@acme/nextly-plugin-reports/summary
```

That address has two halves, and only the second one is Nextly's.

**The namespace** is `/plugins/<plugin-name><path>`, and the plugin name is the raw
package name rather than the admin slug: `@acme/p` answers at `/plugins/@acme/p/export`,
even though the admin addresses that plugin as `/admin/plugins/acme-p`.

**The mount** is wherever your app puts `createDynamicHandlers`, and Nextly cannot know
it: the handler is a route file in your app directory. A scaffolded project mounts it at
`src/app/admin/api/[[...params]]/route.ts`, which is where the `/admin/api` above comes
from. Move that file and every plugin route moves with it.

> [!WARNING]
> A bare `/api` prefix is **not** the mount in a scaffolded app. The base template puts only
> `health` and `media` under `/api`, with no catch-all, so a plugin route addressed there is
> a 404 with nothing to explain it. If your routes are not answering, check where your own
> `createDynamicHandlers` route file actually sits.

Paths support `:param` segments (`/items/:id`), captured into `ctx.params`.

## The handler context

A route handler receives the raw web `Request` plus a `PluginRouteContext` — your full
plugin `ctx` (services/db/events/logger/self/…) **plus** per-request fields:

| Field                    | Meaning                                                                                                                                                                                        |
| ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `ctx.user`               | The authenticated `AuthUser`, or `null` for a `public` route reached without a session.                                                                                                        |
| `ctx.authenticatedScope` | The caller's own grants when they arrived on an API key; `undefined` for a session or a `public` route.                                                                                        |
| `ctx.principal`          | `@experimental` The signed-in person of the kind the route asks for in `principal`, or `null`. See [Signed-in people of your own kind](https://nextlyhq.com/docs/plugins/signed-in-people.md). |

### How a permission is spelled

A permission is spelled one way everywhere: `read-posts`. The database, the
admin's permission matrix, `requiredPermission` on a route,
`ctx.authenticatedScope.permissions` and every code-defined `access` rule all
use it.

Rules were once handed `posts:read` instead. That spelling is no longer in a
rule's list, so a rule checking it does not allow; check `read-posts`.

`ctx.authenticatedScope.permissions` is derived from
`ctx.authenticatedScope.grants`, the permission rows the key resolved to, so
the two can never name different sets.

### Narrowing the scope before a sensitive call

A route may give up part of its own authority for one call. Use `narrowScope`;
the scope's arrays are frozen, so editing them is refused:

```ts
import { narrowScope, type PluginRoute } from "@nextlyhq/plugin-sdk";

const route: PluginRoute = {
  method: "PATCH",
  path: "/posts/:id",
  handler: async (req, ctx) => {
    // A SESSION caller carries no scope, so there is nothing to narrow. That is
    // safe to pass on — `narrowScope` answers `undefined` for `undefined`, and a
    // call with no scope resolves by the caller's own RBAC exactly as it would
    // have. Refused here anyway, because THIS route is for API keys: a session
    // reaching it would run unnarrowed, and the point of the narrowing is that
    // this call is restricted whoever makes it.
    const scope = ctx.authenticatedScope;
    if (scope === undefined) {
      return Response.json({ error: "this route requires an API key" }, {
        status: 403,
      });
    }

    const id = ctx.params.id;
    const data = (await req.json()) as Record<string, unknown>;
    const readOnly = narrowScope(scope, g => g.action === "read");

    await ctx.services.collections.updateEntry("posts", id, data, {
      as: "user",
      user: ctx.user ?? undefined,
      authenticatedScope: readOnly, // refused: the scope no longer holds the write
    });
    return Response.json({ ok: true });
  },
};
```

The narrowed scope applies for the whole call, so every check underneath sees
it — the collection gate, each field's `access` rule, and anything nested. It
can only ever remove authority; a scope cannot grant itself something the key
was not issued.

\| `ctx.params` | Path parameters captured from `:param` segments. |

Return a standard web `Response`. A thrown error is isolated into a JSON error response
— a handler failure never crashes the server.

## Secure by default (D28)

* **Default:** the request must be authenticated. Add `requiredPermission` to also
  enforce a permission (see [Permissions](https://nextlyhq.com/docs/plugins/permissions.md)).
* **Opt out:** set `public: true` to make a route callable without a session (e.g. a
  public sitemap or a webhook receiver). `ctx.user` will be `null`.
* **Your own signed-in people:** set `principal: { kind }` to serve a kind of
  signed-in person your plugin registers instead of staff. The route reads no staff
  session or API key, and refuses a request with nobody of that kind unless
  `required: false`. It cannot be combined with `public` or `requiredPermission`.
  See [Signed-in people of your own kind](https://nextlyhq.com/docs/plugins/signed-in-people.md).

A write the session cookie authenticates is also checked for cross-site forgery. Left
unset, `csrf` checks only the request's origin, which a same-origin write passes;
`csrf: true` also requires a CSRF token of such a write. A route your admin page writes to through
`usePluginRouteMutation` works either way, because that hook sends the token on every
write. A page that writes with its own `fetch` leaves `csrf` unset, or fetches
`/admin/api/auth/csrf` and sends the token as `x-csrf-token`.

`writePluginRoute({ plugin, path, method, body })` (experimental) makes one write
outside React, with the same session handling and token. Where
`usePluginRouteMutation` reports a failure on `error` at the next render,
`writePluginRoute` rejects with the parsed error. Use it when you need the reason
at the moment you await, such as to show it beside the field that was refused.

A write through `usePluginRouteMutation` refreshes the reads it names in
`invalidates`, in the same tab: a list your page reads with `usePluginRoute` shows
the change as soon as the write succeeds. `writePluginRoute` refreshes nothing.
Neither reaches another browser tab. Each tab keeps its own copy of what it read,
so a list open in another tab of the admin still shows what it read before the
write. Reloading that tab reads it again. Opening the page again reads it again
only once its copy is older than the read's `staleTime`, five minutes by default,
since the admin doesn't re-read on switching tabs. Pass `staleTime: 0` to
`usePluginRoute` for a read that is fetched afresh each time its page opens.

On a public route, `csrf: true` also checks the origin of a write no session
authenticates, without asking it for a token; only such a write that sends an
`Authorization: Bearer` token is exempt. A write a session authenticates is
checked as the session's, whatever header it carries. Set it on a public route that browsers
write to, above all one that keeps its own cookie for anonymous visitors, such as
a guest cart. A route for webhooks or other server callers leaves `csrf` unset.
See [Which callers each `csrf` setting checks](https://nextlyhq.com/docs/plugins/security.md#which-callers-each-csrf-setting-checks)
for the full table, and [Route protections](https://nextlyhq.com/docs/plugins/security.md#route-protections)
for `csrf: false` and the other options.

### Gating on one of your OWN collections

A permission slug spells a collection — and a host can rename your plugin's
collections. So a fixed `"create-patterns"` demands a grant that was seeded under
a different name on any install that renamed it, leaving a route nobody there can
call.

Give a function instead. It receives your plugin's resolved names and returns the
slug to require:

```ts
{
  method: "POST",
  path: "/patterns",
  // `collection()` resolves the rename AND composes the slug, so you never
  // spell one yourself.
  requiredPermission: ({ collection }) => collection("patterns", "create"),
  handler: savePattern,
}
```

`collection(declaredSlug, action)` takes the slug **you declared**, not the one
the host ended up with. `single(declaredSlug, action)` does the same for a
Single.

Keep the plain string for a permission that cannot move — one your plugin
declared itself, like `"export-submissions"`.

Two rules for the function:

* **It must be pure and synchronous.** It runs on every request to the route,
  before anything about the caller is known — so it is given your names and
  nothing about the request. Deciding on the caller is the access rule's job, and
  it runs after authentication rather than before it.
* **If it throws, the request is refused.** A gate that cannot be worked out
  never falls back to "no permission required".

```ts
{
  method: "GET",
  path: "/sitemap.xml",
  public: true, // no auth — public derived data
  handler: async (_req, ctx) => {
    const xml = await buildSitemap(ctx.services); // use { as: "system" } inside
    return new Response(xml, { headers: { "content-type": "application/xml" } });
  },
}
```

Pair `public: true` with `{ as: "system" }` service calls only for genuinely public,
derived data. For user data, keep the route authenticated and call services with
`{ as: "user", user, authenticatedScope }`.

### An API key is judged on its own grants

`ctx.user` names the ACCOUNT. When the request arrived on an API key that account is
the key's **owner**, so a service asked to judge `user.id` alone would resolve the
owner's roles — and a key scoped to read would be allowed whatever its owner can do.

**You do not have to do anything for this.** The dispatcher pins the caller's scope
for the length of the request, so an ordinary `{ as: "user", user }` call is judged on
the key's grants:

```ts
const posts = await ctx.services.collections.listEntries("posts", {}, {
  as: "user",
  user: ctx.user ?? undefined,
});
```

`ctx.authenticatedScope` is there when you want to read it — to log the grants, or to
NARROW them before a particularly sensitive call. Passing it explicitly wins over the
ambient one:

```ts
{ as: "user", user: ctx.user ?? undefined, authenticatedScope: ctx.authenticatedScope }
```

A session caller carries no scope at all, and resolves exactly as it always has —
super-admin bypass included.

## Reading and writing your own route from the admin

A plugin's admin components can call the routes the same plugin contributed
through helpers exported from `@nextlyhq/plugin-sdk/admin`, so neither half of
the plugin hand-rolls the session, its refresh or the error envelope:

```ts
import { usePluginRoute, readPluginRoute } from "@nextlyhq/plugin-sdk/admin";

// In a component: cached and deduplicated like every other admin read.
const list = usePluginRoute({ plugin: "@acme/p", path: "/summary" });
// list.pending until an answer arrives; list.error is `Error | null`.

// Outside React: one read per call. Abort the older read yourself when a
// newer one starts — nothing does it for you, and a stale slow answer that
// is never aborted can land last and overwrite the latest.
let searchRead: AbortController | undefined;

export async function searchPlugins(query: string) {
  searchRead?.abort();
  searchRead = new AbortController();
  return readPluginRoute({
    plugin: "@acme/p",
    path: `/search?q=${encodeURIComponent(query)}`,
    signal: searchRead.signal,
  });
}
```

`usePluginRoute` answers `{ data, pending, error, refetch, fetching }`, and
`pending` is a real third state beside the data: `data` being `undefined` is
both "the route answered nothing" and "the route has not answered yet".
`error` is an `Error` or `null`: a refusal the route answered arrives parsed,
with `status`, `code` and `data` to read, while a request that never got an
answer — offline, a DNS or CORS failure, a cancelled read — stays a native
`Error` with none of those. `readPluginRoute` is not cached, answers
`undefined` for a route that answered with nothing, and rejects the same way:
the parsed error on an HTTP refusal, a native error when the read never got
one. Both go through the same session handling as the admin's own reads, so an
expired session is renewed rather than surfacing as a failure.

Both address the route through the dispatcher's own path builder, so the
address agrees with where the route actually answers — a hand-spelled one is
what drifts when the mount moves. On the default mount that address is
`/plugins/<package name><path>`; a route the plugin declared with
`mount: "root"` answers at the path it declared, and the package name plays no
part in its address. The builder only builds: nothing checks that the name a
call passes is the calling plugin's. A path no plugin route and no built-in
endpoint serves is a request failure, not an empty answer — the admin's
catch-all falls through to the built-in parser and refuses it. Writes have
their own pair, `usePluginRouteMutation` and `writePluginRoute`, described with
the `csrf` options above.

## Receiving webhooks

> **Experimental.** `ctx.security.webhooks` is new and ships `@experimental`.

A route that receives webhooks is `public`, since the sender has no session, and
reads the body as the exact bytes sent (`rawBody: true`). Verify the delivery's
signature before reading anything in it:

```ts
import { definePlugin, standardWebhooks } from "@nextlyhq/plugin-sdk";

definePlugin({
  name: "@acme/nextly-plugin-orders",
  // ...
  contributes: {
    routes: [
      {
        method: "POST",
        path: "/webhooks/orders",
        public: true,
        rawBody: true,
        handler: async (req, ctx) => {
          const result = await ctx.security.webhooks.verify(req, {
            scheme: standardWebhooks,
            // Every secret currently valid: during a rotation, the new and the old.
            secrets: [process.env.ACME_ORDERS_SECRET ?? ""],
          });
          if (!result.verified) {
            ctx.logger.warn("Refused an orders webhook", { reason: result.reason });
            return new Response(null, { status: 401 });
          }
          // The same delivery can arrive twice: a sender's retry, or a
          // replay within the tolerance. Act on each delivery id once.
          if (result.deliveryId && (await seen(result.deliveryId))) {
            return new Response(null, { status: 204 });
          }
          const event = JSON.parse(result.body);
          // ...
          return new Response(null, { status: 204 });
        },
      },
    ],
  },
});
```

Use `result.body`, the bytes that were verified, rather than reading the request
again. `seen` stands for your own record of the delivery ids you have handled:
a verified delivery can still be a repeat, so handle each id once. `verify` reads a copy, so the request stays readable, but only the
verified body is known to be what the sender signed.

What core checks, whatever the scheme:

* **Age.** A delivery signed more than 5 minutes away from now, either way, is
  refused as `expired`. Set `toleranceSeconds` to change that; it must be a
  finite number.
* **Signatures.** Every signature the delivery presents is compared with every
  secret you pass, as bytes, in constant time. A delivery signed with the old
  secret or the new one verifies while you pass both.
* **Size.** A body over 1 MiB is refused as `too-large` before anything is
  signed. Set `maxBytes` to change that.
* **Nothing is verified by default.** No signature headers is `missing`, an
  unreadable header is `malformed`, no usable secret is `no-secret`, and a
  signature that matches no secret is `mismatch`. The reason is for your log;
  answer the sender with a plain 400 or 401.

### A provider's own scheme

`standardWebhooks` is the scheme Nextly signs its own [webhooks](https://nextlyhq.com/docs/webhooks.md)
with. For another provider, describe its scheme: where its signatures and
timestamp are, which bytes it signs, and how one secret signs them. Core still
does the age check and the comparison.

```ts
import { createHmac } from "node:crypto";
import type { InboundWebhookScheme } from "@nextlyhq/plugin-sdk";

/** `Provider-Signature: t=<seconds>,v1=<hex>`, signing "<t>.<body>". */
const providerScheme: InboundWebhookScheme = {
  read({ headers, bytes }) {
    const header = headers.get("provider-signature");
    if (header === null) return null; // not this scheme's delivery
    const parts = header.split(",").map(part => part.split("="));
    const t = parts.find(([key]) => key === "t")?.[1];
    if (t === undefined || !/^\d+$/.test(t)) throw new Error("no timestamp"); // malformed
    return {
      timestamp: Number(t),
      // The exact bytes sent, not text decoded and encoded again.
      signed: Buffer.concat([Buffer.from(`${t}.`), bytes]),
      signatures: parts
        .filter(([key]) => key === "v1")
        .map(([, value]) => Buffer.from(value, "hex")),
    };
  },
  sign: (secret, signed) => createHmac("sha256", secret).update(signed).digest(),
};
```

A provider that signs no time, such as one sending `sha256=<hex>` over the body
alone, returns `timestamp: "none"`. It has to say so: a scheme that leaves the
timestamp out is refused as `malformed`. Its verified result says
`freshness: "unchecked"`, against `"checked"` for every other delivery.
**Such a delivery has no replay protection here**: someone who captured one can
send it again at any time, and it still verifies. A `"checked"` delivery can be
replayed too, but only within the tolerance. Either way, handle each delivery id
once, and require `result.freshness === "checked"` wherever a replay outside
that window would do harm.

## Middleware (D27)

Routes support an ordered, typed middleware chain (onion model). Each middleware calls
`next()` to continue or returns a `Response` to short-circuit:

```ts
import type { Middleware } from "@nextlyhq/plugin-sdk";

const timing: Middleware = async (req, ctx, next) => {
  const res = await next();
  res.headers.set("x-handler", "reports");
  return res;
};

// route: { method, path, middleware: [timing], handler }
```

See also: [Permissions](https://nextlyhq.com/docs/plugins/permissions.md) · [Data access](https://nextlyhq.com/docs/plugins/services.md).
