Core · Developing apps · Server

HTTP routes and APIs

An application can return HTML, redirects and files directly, as well as JSON APIs for pages and other clients. The Product Catalog example demonstrates these uses; see Example source and setup for the complete application.

Choose a route type

Web routes and API routes

RequirementDeclarationExample path
HTML pages, redirects, file downloads or protocol callbacksdefineRootRoutes()/catalog
Custom queries, record creation and business operationsdefineApiRoutes()/api/products
Standard Repository operations on one collection over HTTPdefineRepositoryApiRoutes()/api/publicCategories/findMany

The root in defineRootRoutes() means the application root, which may differ from the domain root. Web routes choose their content and status codes. API routes use standard validation, JSON responses and errors, and appear in the API documentation. Neither route type determines whether an endpoint is public; configure access for its purpose.

The example's public catalog shows published products. Categories allow anonymous reads. Product management APIs and CSV downloads require authentication and the relevant permission.

Server routes and client page routes

A Web route here handles an HTTP request on the server and returns HTML or another response directly. React page routes organize client pages, layouts and navigation; see Pages, routes and navigation. Adding a server route does not add a sidebar entry.

For application lists, forms and drawers, usually declare client page routes that call APIs. Server Web routes fit standalone HTML pages, redirects from old addresses and downloads.

Declare and register routes

Route files and the registration entry

Declare routes in server/routes/, then add them to server/routes/index.ts. Creating a file alone does not expose its routes.

TypeScript
import type { Application } from '@nocobase/app-server/application';
import type { AppRouteContribution } from '@nocobase/app-server/router';
import catalogWeb from './catalog-web.js';
import products from './products.js';
import categories from './categories.js';

const routes: readonly AppRouteContribution<Application>[] = [
  catalogWeb,
  products,
  categories,
];
export default routes;

Append these declarations to the existing array, preserving other routes. The default template's server/runtime.ts already connects this entry, so runtime changes are usually unnecessary. A route factory runs during startup; its handlers run for each request.

Source: Route registration. After starting the example, open /catalog beneath the application entry to see the catalog.

Application base path and API prefix

Declare neither /api nor the deployment base path in individual handlers. When the application is mounted at /shop:

DeclarationPath in codeRequest path
defineRootRoutes()/catalog/shop/catalog
defineApiRoutes()/products/shop/api/products
Repository publicCategories, action findManyGenerated by the adapter/shop/api/publicCategories/findMany

Use the application address printed at startup. For links in generated HTML, use app.publicBasePath instead of hardcoding /shop or /main. API Client already has the API base URL; its request paths, such as /products, are relative to that address.

Write Web routes

Return an HTML page

defineRootRoutes() accepts a factory returning a Hono router. c.html() returns HTML. Templates from hono/html escape interpolated ordinary strings; do not concatenate external data such as product names into HTML.

This is the catalog handler's core pattern from server/routes/catalog-web.ts, with navigation and styling omitted:

TypeScript
import { Hono } from 'hono';
import { html } from 'hono/html';
import type { Application } from '@nocobase/app-server/application';
import { defineRootRoutes } from '@nocobase/app-server/router';
import { catalogServiceToken } from '../providers/catalog.js';
import { publicProductPolicy } from '../providers/catalog-service.js';

export default defineRootRoutes<Application>((app) => {
  const router = new Hono();
  const service = app.container.resolve(catalogServiceToken);

  router.get('/catalog', async (c) => {
    const { data } = await service.list(publicProductPolicy, {
      q: '', page: 1, pageSize: 50,
    });
    return c.html(html`<ul>${data.map((product) =>
      html`<li>${product.name}</li>`,
    )}</ul>`);
  });
  return router;
});

publicProductPolicy belongs to the example. It allows only specified fields of products with published set to true and denies writes. The server defines the public scope independently of filters a browser supplies.

Open <application entry>/catalog. The initial data should show Canvas Backpack and Desk Lamp, while the unpublished Travel Mug stays hidden. The page displays up to 50 products.

The server-rendered catalog shows two published products and links to the application, API documentation and CSV download
The server-rendered catalog shows two published products and links to the application, API documentation and CSV download

Source: Web routes, Public read policy and query service.

Redirect to another address

Use c.redirect() in the same Web router:

TypeScript
router.get('/old-catalog', (c) => c.redirect('/catalog', 302));

Requesting /shop/old-catalog returns 302 with Location: /shop/catalog, which the browser follows. The runtime used by this example adds the application base path to application-local redirect locations starting with /; it leaves absolute external URLs unchanged. Never use unchecked user input as a redirect target.

Run curl -i "$APP_URL/old-catalog" to inspect the status and Location. APP_URL includes the application base path and has no trailing slash. See the Web route implementation.

Return files and downloads

A download can also be a Web route. The following handler runs behind authentication and authorization middleware. productPolicy() supplies the current request's permitted data scope:

TypeScript
router.get('/catalog/export.csv', async (c) => {
  const policy = await productPolicy(c, 'view');
  const records = await service.repository(policy).findMany({
    limit: 500,
    sort: (s) => s.field('name').asc(),
  });
  // The example handles quotes, newlines and spreadsheet formula prefixes.
  const csv = toCsv(records);
  c.header('Content-Type', 'text/csv; charset=utf-8');
  c.header('Content-Disposition', 'attachment; filename="products.csv"');
  c.header('Cache-Control', 'private, no-store');
  return c.body(csv);
});

toCsv is the example's CSV conversion function, not a framework API. Content-Type describes the content; Content-Disposition: attachment requests a file download.

Sign in to the same application with product view permission, then click Download CSV on the catalog. The downloaded products.csv contains up to 500 products the account may view, including drafts where permitted. An administrator's export scope differs from the public page's published-only policy. An anonymous download returns 401; an authenticated caller without view permission receives 403.

This example generates a small file in memory. Larger exports need batched reads or streaming rather than removing the limit and loading every record at once.

Write custom APIs

The handlers below belong inside the defineApiRoutes() factory in server/routes/products.ts. It resolves authentication, authorization and the product service and registers error handling. service is the product service; productPolicy(c, action) returns the current operation's database policy. Both are example code. See Product APIs for their complete integration.

The factory uses defineApiRoutes(). This is its integration skeleton; the source above includes authentication, handlers and imports for the example helpers:

TypeScript
import { Hono } from 'hono';
import type { Application } from '@nocobase/app-server/application';
import { defineApiRoutes } from '@nocobase/app-server/router';
import { catalogServiceToken } from '../providers/catalog.js';
import {
  catalogErrorHandler, type CatalogEnv,
} from './catalog-access.js';

export default defineApiRoutes<Application>((app) => {
  const router = new Hono<CatalogEnv>();
  const service = app.container.resolve(catalogServiceToken);
  router.onError(catalogErrorHandler);
  // Register path-scoped authentication and the handlers below here.
  return new Hono().route('/', router);
});

Read query parameters and return a list

Validate query parameters with apiValidator('query', schema) and read the converted values through c.req.valid('query'):

TypeScript
const Query = z.strictObject({
  q: z.string().max(100).default(''),
  page: z.coerce.number().int().min(1).max(10000).default(1),
  pageSize: z.coerce.number().int().min(1).max(50).default(10),
});

router.get('/products',
  describeRoute({
    tags: ['Products'], summary: 'List products', operationId: 'listProducts',
    responses: { 200: listResponse(Product), ...apiErrorResponses },
  }),
  apiValidator('query', Query),
  async (c) => c.json(await service.list(
    await productPolicy(c, 'view'), c.req.valid('query'),
  )),
);

After signing in, execute GET /products?q=Desk&page=1&pageSize=10 in the API documentation. Expect Desk Lamp, with data and meta.page, meta.pageSize, and meta.total. Apply the same policy and filter to rows and the total; otherwise the count can reveal records the caller cannot access. pageSize=51 returns 400.

Source: List handler, Paginated query.

Read path parameters and return a record

Hono declares a path parameter as :id; OpenAPI displays it as {id}:

TypeScript
router.get('/products/:id',
  describeRoute({
    tags: ['Products'], summary: 'Get a product', operationId: 'getProduct',
    responses: { 200: dataResponse(Product), ...apiErrorResponses },
  }),
  apiValidator('param', z.object({ id: z.uuid() })),
  async (c) => c.json({ data: await service.get(
    await productPolicy(c, 'view'), c.req.valid('param').id,
  ) }),
);

Take a product ID from the list and request GET /products/{id}. Expect { data: product }. This example generates UUIDs, hence z.uuid(); other applications may use different identifiers. An invalid UUID returns 400. A valid ID that is missing or outside the caller's read scope returns the same 404.

Source: Detail handler.

Validate a request body and create a record

Creation accepts a name and a price in cents. The server controls publication:

TypeScript
const Values = z.strictObject({
  name: z.string().trim().min(1).max(100),
  priceCents: z.number().int().min(0).max(100000000),
});

The route passes this schema to apiValidator('json', Values) and reads c.req.valid('json'). Execute POST /products in the API documentation with:

JSON
{ "name": "Travel Notebook", "priceCents": 1200 }

Also provide an Idempotency-Key header in the form <13-digit millisecond timestamp>.<UUID v4>. Generate a new operation key from the application directory:

Bash
node -e 'console.log(`${Date.now()}.${require("node:crypto").randomUUID()}`)'

Success returns 201 with id, name, priceCents and published: false in data. An extra published field, empty name or negative price returns 400 without creating a record. strictObject() rejects undeclared fields; a describeRoute() response declaration does not itself filter the actual response.

The example explicitly uses executeIdempotentMutation() to commit creation and its receipt in one transaction. Retry an operation whose response was lost with the original key and input. A successful replay includes Idempotency-Replayed: true and creates no second product. Use a new key for an intentional new record. Adding the header alone does not give an ordinary custom POST this behavior.

Source: Creation handler and receipt integration. See Validation and response handling for input and error conventions.

Call a business service

Keep business rules in server/providers/, register the service through a Provider and resolve it once in the route factory:

TypeScript
const service = app.container.resolve(catalogServiceToken);

The core service call in POST /products/{id}/publish is:

TypeScript
const policy = await productPolicy(c, 'publish');
const id = c.req.valid('param').id;
// Inside executeIdempotentMutation's execute(transaction) callback:
return service.publish(policy, id, transaction);

The route owns HTTP input, identity, authorization and responses. The service checks that the product exists and is unpublished, then updates it through the supplied policy and transaction connection. It does not read a Hono Context or choose an HTTP status.

Publish the product you just created using a new key and an empty body {}. Expect 200 with published: true; refresh the public catalog to see it. Retrying the same key returns its original result. Publishing it again with a new key returns 409 PRODUCT_ALREADY_PUBLISHED. A conditional update preserves the expected state so concurrent callers cannot both treat the same draft as unpublished.

Source: Provider and token, Product service, Publish route. See ServiceProvider for service lifecycle and Transactions and consistency for transaction boundaries.

Use Repository data APIs

Configure collections and exposed operations

defineRepositoryApiRoutes() fits standard operations on one collection. It creates neither tables nor management pages. Prepare catalogCategories through a migration, then declare:

TypeScript
import { defineRepositoryApiRoutes } from '@nocobase/app-server/router';

export default defineRepositoryApiRoutes({
  repositories: [{
    name: 'publicCategories',
    collection: 'catalogCategories',
    actions: { findMany: { maxLimit: 50 }, findOne: {}, count: {} },
    policy: {
      read: { scope: true, fields: ['id', 'title'] },
      create: false, update: false, delete: false,
    },
  }],
});

name is the HTTP resource name; collection names the database collection. Only operations listed in actions are registered, so this declaration exposes no createOne route. Reads also use POST: POST /api/publicCategories/findMany.

Source: Category APIs, Migration.

Restrict records and fields

actions controls which operations exist. policy controls the records, fields and writes those operations allow. Configure both.

The policy above permits anonymous reads of every category but returns only id and title. The stored internalNote must not appear in responses, and client filters cannot broaden the server's scope. findMany.maxLimit: 50 bounds the result size; limit: 51 returns 400.

For identity- or role-dependent access, integrate authenticated identity resolution and dynamic policies. See Repository data APIs for the complete options and authorization plugin integration.

Call with API Client and HTTP

Obtain the client with useApiClient() in a React page, then pass it into an ordinary function:

TypeScript
import type { ApiClient } from '@nocobase/app-client';

type Category = { id: string; title: string };
export async function loadCategories(api: ApiClient) {
  return api.repository<Category>('publicCategories').findMany({ limit: 20 });
}

The result is the category array: the remote Repository unwraps { data }. A raw HTTP response retains the wrapper:

Bash
curl "$APP_URL/api/publicCategories/findMany" \
  -H 'Content-Type: application/json' \
  -d '{"limit":20}'
JSON
{ "data": [
  { "id": "office", "title": "Office" },
  { "id": "travel", "title": "Travel" }
] }

Without an explicit sort, do not rely on array order. The same client's count() returns a number; findOne() returns a record or undefined. See loadCategories for the client wrapper. The example's endpoint tests also call the registered routes with the real API Client. See Data requests and state for client request state.

Protect routes and handle errors

Add authentication and business authorization

Mounting under /api authenticates nothing. Each module should protect the paths it owns, without relying on another module's registration order or accidentally protecting public routes through global wildcard middleware.

TypeScript
const auth = app.container.resolve(authenticationToken);
const authz = app.container.resolve(authorizationToken);
for (const path of ['/products', '/products/*']) {
  router.use(path, auth.required({ scopedKeys: false }), authz.middleware());
}

Authentication identifies the caller. Authorization checks view, create or publish; the resulting database policy constrains records and fields. Downloads use authentication and the view policy too. This example's management operations use signed-in sessions and do not accept scoped API keys.

Installation creates Catalog viewer and Catalog editor roles without assigning them to ordinary users. Administrators assign roles to specific users through Users and edit operations and data scopes in Permission management. Page access does not authorize server operations.

Source: Business permissions, Request authorization, Initial roles.

Handle invalid input and business errors

Represent HTTP errors with ApiError and pass them to apiErrorHandler(), instead of constructing different error JSON in each handler. The example translates service errors into standard API errors:

TypeScript
new ApiError({
  status: 'NOT_FOUND',
  reason: 'PRODUCT_NOT_FOUND',
  domain: 'catalog',
  message: 'Product not found.',
});
SituationResponse
Anonymous product API or download request401
Signed in without the required operation403
Invalid input400, with field information for validation errors
Product missing or outside the permitted scope404 PRODUCT_NOT_FOUND
Publishing an already published product with a new operation key409 PRODUCT_ALREADY_PUBLISHED

Callers branch on status and reason, not message text. See the error handler. Web routes need not use the API format: this example reuses standard JSON errors for failed downloads, while an HTML page may provide its own error page.

Avoid path conflicts

Give each method and path a single clear handler. The framework reports duplicate API routes at startup; do not rely on registration order to override another endpoint. Keep Web routes clear of /api, static asset paths and client page paths. Avoid catch-all handlers that consume other entries.

The example uses /catalog for HTML and /api/products for business APIs, leaving / to the client application. API documentation and endpoint tests can check the registered result.

Generate and use API documentation

Describe inputs, responses and errors

Custom APIs use describeRoute() for a stable operationId, tag, purpose and responses. Schemas passed to apiValidator() supply input descriptions. dataResponse() and listResponse() describe record and list responses; they neither query the database nor replace runtime validation.

Repository endpoints generate descriptions from their collections and enabled actions. Web routes are absent from the API document; verify them directly in the browser or with HTTP requests as shown above.

Source: API declarations. When response fields change, update both the actual result and its schema.

Send requests from the interactive documentation

Sign in, then open <application entry>/api/swagger/docs#/Products to reach the product group directly. The JSON document is at <application entry>/api/swagger. Both require a session or credential allowed to access them.

Expand an operation under Products, click Try it out, enter its parameters and body, then click Execute. Creation and publication also need the Idempotency-Key described earlier. Copy the new product ID from the creation response for detail and publication requests.

The Products group in the interactive API documentation includes list, create, detail and publish operations
The Products group in the interactive API documentation includes list, create, detail and publish operations

Verify routes and APIs

Check responses and saved data

With the example's initial data:

  1. Open /catalog anonymously and confirm only published products appear. Open /old-catalog and confirm the redirect stays beneath the same application base path.
  2. Call category findMany anonymously. Confirm category titles are returned without internalNote.
  3. Sign in with management permissions and create a product through the API documentation. Expect 201; its detail is readable, but it is absent from the public catalog.
  4. Publish it. Expect 200 and its appearance after refreshing the catalog. Replaying the original operation does not execute it again; a new publication operation returns 409.
  5. Download CSV and check its filename, content and the caller's permitted records.

Verify access limits and failure cases

Check ordinary users too. With no role, product APIs and downloads are denied. View permission allows reads and downloads, but not creation or publication. A restricted product scope must affect lists, totals, details and downloads alike.

Also verify that invalid input creates no record, out-of-scope details disclose no product and permission revocation denies the next request. Run the example's automated checks:

Bash
pnpm exec vitest run tests/server/catalog.test.ts tests/database/catalog.test.ts tests/server/authorization-assignment-safety.test.ts

These tests start the real application with isolated databases and real sign-in. They cover those boundaries, migration rollback and reapplication, receipt replay and API documentation. Browser checks and screenshot instructions are in the example README.

Example source and setup

The complete Product Catalog source includes all three route types, the product service, migrations, English sample records, permissions and tests.

The example uses default template 1.0.0-beta.85, Node.js 24 or later and pnpm 11.11.0. Its lockfile fixes the example's dependencies. See the README for configuration and a map from each documented usage to its implementation.

Bash
git clone https://github.com/nocobase/docs-examples-v3.git
cd docs-examples-v3
git checkout 0639e6a2a6cba857bf967757083e9f8d7aa6b9fe
cd apps/product-catalog
npm pkg set packageManager=pnpm@11.11.0
pnpm install --frozen-lockfile
pnpm nocobase config init --dialect sqlite
pnpm nocobase config check
APP_SAMPLE_DATA=true pnpm dev

SQLite is the example's setup choice, not an HTTP routing requirement. Before the first startup, configure the administrator under users.initialAdmin in local config.yml. Sign in using the full application address printed at startup. APP_SAMPLE_DATA=true installs sample products and categories on first installation; later starts do not overwrite edited data. If the first installation omitted samples, use pnpm nocobase db sample in development to add them.

Append /catalog to the application address for the public page, or /api/swagger/docs for API operations. Saved products survive page reloads and server restarts.

NocoBase docs assistant

Ask anything about NocoBase…

Each question is answered independently, without earlier questions or answers. Include all relevant context.