Open MercatoDocsSearch docsAPI reference

Framework

Extend module APIs

An aggregate report, an inbound webhook and a conventional record form have different request shapes. Keep a dedicated endpoint for a specialized operation and give it the same validation, scope and access checks as the rest of the module.

While the CRUD factory covers most cases, sometimes you need bespoke endpoints – aggregations, external integrations, or webhooks. Follow these guidelines to extend module APIs safely.

File structure

src/modules/<module>/api/<path>/route.ts

Example: api/organizations/invite/route.ts handles /api/organizations/invite.

Each file exports handlers for HTTP methods (GET, POST, PUT, DELETE, etc.) following Next.js App Router conventions.

import { NextResponse } from "next/server";
import { z } from "zod";
import { createRequestContainer } from "@/lib/di/container";
import type { AuthContext } from "@open-mercato/shared/lib/auth/server";

const inputSchema = z.object({
  email: z.string().email(),
  roleId: z.string().uuid(),
});

export async function POST(req: Request, { auth }: { auth: AuthContext }) {
  const body = inputSchema.parse(await req.json());

  const container = await createRequestContainer();
  const invitations = container.resolve("organizationInvitationService");

  await invitations.inviteUser({
    ...body,
    organizationId: auth.organizationId,
  });

  return NextResponse.json({ ok: true });
}

export const metadata = {
  POST: {
    requireAuth: true,
    requireFeatures: ["directory.invite"],
  },
};

Best practices

API interceptor route identity

The catch-all API dispatcher binds the matched manifest route to the request before calling a handler. API interceptor selection consumes that identity: static segments use the route's authored spelling, and dynamic/catch-all segments keep their matched parameter values. Mixed-case and percent-encoded spellings that dispatch to the same route therefore run the same exact and wildcard interceptors. Malformed path encoding is rejected before handler execution.

Custom interceptor wrappers must use the dispatcher-bound request identity (the shared CRUD factory does this automatically), or pass an authored route constant to the interceptor runner. Do not derive a policy key independently from request.url; doing so can make dispatch and policy matching disagree. This identity does not alter the request URL, query string, or ctx.params received by the handler.

The identity survives request.clone() and new Request(request.url, request). Wrappers that reconstruct a request with an explicit RequestInit must retain the original headers or pass an authored route constant to the interceptor runner. The framework overwrites caller-supplied identity metadata at dispatch, bounds its process-local continuity state, and rejects unknown or expired metadata rather than falling back to the raw URL.

Mixing CRUD factories and bespoke endpoints gives you the flexibility to move fast while keeping the platform predictable.

Dispatcher tenant-extraction body-peek budget

Before a route handler runs, the dispatcher peeks at the request body for a tenantId field so it can enforce tenant selection (#2665) against every candidate the request carries – query string and body alike – ahead of the handler's own, larger body parsing. That peek is capped by OM_API_TENANT_EXTRACT_MAX_BYTES (default 64 KB) so an authenticated caller can't force a full JSON/multipart body to be buffered just to extract one field (#7811).

For the rare route whose handler actually reads a body-supplied tenantId to select a tenant other than the caller's own – a cross-tenant management endpoint such as auth/roles, auth/roles/acl, or auth/users/acl – an oversized body is rejected with 403 for a non-superadmin rather than silently treated as "no candidate" (#7877): the dispatcher cannot verify there is no foreign tenantId hiding past the peek limit, so it fails closed. Opt into this by setting honorsBodyTenantId: true on that method in the route's exported metadata.

Every other route – the overwhelming majority, since packages/core/AGENTS.md requires deriving tenantId from the authenticated context rather than request input – keeps the pre-existing behavior for this oversized-body case: an upload, a bulk write, or a telemetry batch whose body exceeds 64 KB is treated as "no candidate" at the dispatcher level and proceeds to the route's own (larger) body handling unaffected, same as before #7877. Only set honorsBodyTenantId after confirming the route's handler reads a body-level tenantId by some path other than withScopedPayload / parseScopedCommandInput (see below) – setting it on a route that doesn't would start rejecting that route's own legitimate oversized bodies for non-superadmins.

This dispatcher-level peek is a bounded, best-effort check – it is not the only place a body-supplied tenantId is enforced. A handler that reads a scoped payload through withScopedPayload or parseScopedCommandInput (packages/shared/src/lib/api/scoped.ts) gets tenant enforcement unconditionally, regardless of request body size: those helpers reject a non-superadmin's foreign tenantId themselves, so a route built on them needs no honorsBodyTenantId flag and no size-bound workaround at all. A route that reads a body tenantId by any other path – without going through those helpers and without calling enforceTenantSelection itself – is the one case this dispatcher-level flag exists for.

Previous: CRUD API Factory · Next: Business Rules Architecture