[data-reveal]{opacity:1!important;transform:none!important}
AntelopeJS DMS
DocumentationFrontend modules and request helpers

Frontend modules and request helpers

Register the frontend a module ships, sign upload fields, build public links, read the client address and the period of a request, and save native files from a write route.

A module's backend uses these functions to ship a frontend, to serve components outside a registered page, and to handle requests. Each section names the subpath it imports from. Pages, which call most of them for you, are described in Pages and modules.

Ship a frontend module

AddFrontendModule(config) registers a frontend module that your module ships. Call it from your module's construct().

typescript
import path from "node:path";
import { AddFrontendModule } from "@antelopejs/interface-dms/page";

export async function construct(): Promise<void> {
  await AddFrontendModule({
    name: "@acme/dms-billing",
    sourcePath: path.join(__dirname, "../frontend-vue"),
    renderer: { name: "vue", version: "3" },
    configKey: "dmsBilling",
    priority: 0,
    options: { prefix: "Billing" },
  });
}

AddFrontendModuleOptions

OptionTypeDescription
namestringLogical frontend module name. The registry identity also includes the renderer name and major version. Required.
sourcePathstringAbsolute path to the frontend module directory. Required.
rendererFrontendRendererMetadataFramework the module is written for: a name and a version compared by major only. Use { name: "vue", version: "3" } for the Inertia and Vue frontend. The package.json of sourcePath declares the loader releases the module runs on (Frontend layer). Required.
optionsFrontendModuleOptionsJSON-like values handed to the layer's configuration. Defaults to {}.
privateOptionsFrontendModuleOptionsA second set of values for the layer, kept apart from options and left out of GetFrontendModules(). Defaults to {}.
prioritynumberOrder among registered layers. Defaults to 0.
configKeystringConfiguration key the layer is published under.
authEstablishEndpointsstring[]Backend routes under /api/ from which the frontend server may open a session for the module, through its /auth/establish route. Each is an absolute path with no query string and no segment that climbs out. A malformed entry fails the registration.
publicEndpointsFrontendPublicEndpoint[]Backend routes the module serves to callers outside the dashboard, such as a provider's webhook. See Public endpoints.
backendProxiesFrontendBackendProxy[]Backend prefixes outside /api/** and /dms/** that the browser reaches through the frontend server, such as { path: "/media/**", auth: "none" }.

A FrontendBackendProxy has a path and an optional auth. path is /x, /x/* or /x/**, with a literal first segment outside the renderer's own paths (/api/_dms, /@, /assets, /node_modules). auth is "session", the default, which adds the session's access token on the server and requires the frontend's own Origin on a state-changing request, or "none", which never sends the session. A malformed entry fails the registration.

Within one logical name, renderer and major version, the registration with the highest priority wins, and among equal priorities the latest one wins. The manifest and archive endpoints select a renderer with the paired renderer and rendererVersion query parameters, matched on the major version. A selection that matches no registered renderer answers 404, and a request that passes only one of the two parameters answers 400. A request with neither selects renderer=vue and rendererVersion=3.

Public endpoints

The frontend server's proxy requires a same-site Origin on every state-changing request, forwards it with the signed-in user's session, and relays only a few headers. A webhook that a mail or payment provider calls through the dashboard's public URL fails both checks. Declare such a route public:

typescript
await AddFrontendModule({
  name: "@acme/dms-mailing",
  sourcePath: path.join(__dirname, "../frontend-vue"),
  renderer: { name: "vue", version: "3" },
  publicEndpoints: [
    {
      path: "/api/mailing/events/*/*",
      methods: ["POST"],
      headers: ["x-mailing-webhook-secret"],
    },
  ],
});

A request to a declared route needs no Origin, carries the declared headers, and is never sent the session, even from a signed-in browser. A cross-site form that posts to it acts as nobody, so the route authenticates its caller itself, with a shared secret or a signature.

A FrontendPublicEndpoint has three fields:

  • path is absolute under /api/. Its first segment after /api/ is literal, the module's own prefix and never *, and each later * matches exactly one segment. It has no query string, no prefix match, and no . or .. segment.
  • methods lists the methods it answers, among GET, HEAD, POST, PUT, PATCH and DELETE. Defaults to ["POST"].
  • headers names the module's own x- request headers. Headers that a proxy or the DMS gives a meaning to (x-forwarded-*, x-real-ip, x-dms-*, x-inertia*, method overrides) are refused.

A malformed entry fails the registration. The declarations reach the frontend server through the manifest it is built from, on an authenticated build only, and its DMS_PUBLIC_ENDPOINTS setting adds routes that no module declares.

Frontend module discovery

GetFrontendModules() returns a FrontendModuleMetadata for each registered frontend module: its name, sourcePath, renderer, priority, options, authEstablishEndpoints, publicEndpoints, and backendProxies with each auth filled in. It never returns privateOptions. FrontendModulesChanged is an event that fires whenever that list changes. Modules start in parallel, so a module that reads the list in its own start() registers a handler, reads the list once, and reads it again in the handler.

A module can also ship a pure FrontendModuleFunction, exported as frontendModule from the file its package.json names under dmsFrontend. It takes the module's configuration and a FrontendModuleContext ({ dev: boolean }) and returns a FrontendModuleRegistration, the same shape as AddFrontendModuleOptions, or undefined when the configuration registers no frontend. The backend passes the result to AddFrontendModule, and @antelopejs/dms-frontend calls the function itself, so a frontend builds and starts without a backend. The function reads only its arguments. Any privateOptions it returns hold their shape only, every value an empty string, and the backend and the frontend server fill in the secrets.

Stamp upload tokens

StampUploadFieldTokens(options) from @antelopejs/interface-dms/uploads takes a component's serialized options and returns them with a signed upload token in every file and image field. That covers the component's own fields and the forms it embeds, such as a relation field's inline add form or a table view's new, edit and view forms. The token binds each field to the storage and path it declares, so a client cannot presign an upload elsewhere.

The builders that carry upload fields attach it through transformOptions, and page registration stamps the authoritative declaration, so pages declared with @RegisterPage() are already covered. Call it yourself only to serialize and serve components outside that path. A token produced outside a registered page stays unbound and cannot authorize an upload.

typescript
import { StampUploadFieldTokens } from "@antelopejs/interface-dms/uploads";

const components = await StampUploadFieldTokens(layout.components);

Options without an upload field come back untouched. Otherwise the return value is a deep clone, because serialization runs again on a hot reload and each pass must start from the declaration as written.

Public URLs

GetApiBaseUrl() from @antelopejs/interface-dms/api-base-url and GetClientBaseUrl() from @antelopejs/interface-dms/client-base-url return the public origins of the DMS API and of the dashboard. They come from the DMS configuration (apiBaseUrl, clientBaseUrl), and under ajs dms dev they follow the dev server's origins. Build an absolute link on them, not on the request's headers. Behind a reverse proxy that forwards no X-Forwarded-Host, the request knows only the internal host.

typescript
import { GetApiBaseUrl } from "@antelopejs/interface-dms/api-base-url";
import { GetClientBaseUrl } from "@antelopejs/interface-dms/client-base-url";

const apiBase = await GetApiBaseUrl();
const downloadUrl = `${apiBase}/i18n/site/fr.json`;
const inviteUrl = `${await GetClientBaseUrl()}/auth/signup`;

Both return string | undefined, such as "https://api.example.com". They return undefined only when the configuration clears the value.

Client address

getClientIp(context) from @antelopejs/interface-dms/client-ip returns the address a request came from, resolved the way the DMS resolves the address it records on a session:

  • When auth.clientIpHeader is configured, from the header the hosting platform writes (Client address from the platform).
  • Otherwise behind the auth.trustedProxies reverse proxies of the configuration (Client address behind proxies). Each trusted hop vouches for the x-forwarded-for entry it appended, and nothing to the left of it counts.

An IPv4-mapped address (::ffff:10.0.0.1) comes back as plain IPv4. Key a rate limit or an anonymous visitor on it, not on x-forwarded-for read by hand, so the operator declares the proxies once for the DMS and every module.

typescript
import { Context, Controller, Post, type RequestContext } from "@antelopejs/interface-api";
import { getClientIp } from "@antelopejs/interface-dms/client-ip";

export class CollectController extends Controller("/api/collect") {
  @Context()
  declare requestContext: RequestContext;

  @Post("/")
  async collect(): Promise<{ address: string }> {
    const address = await getClientIp(this.requestContext);
    return { address };
  }
}

It returns an empty string when the request carries no address. ResolveClientIp(source) applies the same resolution to values a module already holds, such as a request it queued for later. Its ClientAddressSource has socketAddress and forwardedFor, both string | undefined, and optional headers, where the auth.clientIpHeader header is read.

Period of a request

@Period() from @antelopejs/interface-dms/period-request hands a route the period a PeriodSelector sent with a widget's request: the from, to, compareFrom, compareTo, preset and comparison query parameters a widget bound by periodScope adds to its fetchUrl. readPeriodRequest(context) reads the same from a RequestContext.

typescript
import { Controller, Get } from "@antelopejs/interface-api";
import { Period, type PeriodRequest } from "@antelopejs/interface-dms/period-request";

export class DashboardController extends Controller("/api/dashboard") {
  @Get("orders")
  orders(@Period() period: PeriodRequest): { from?: string; compared: boolean } {
    return { from: period.range?.from.toISOString(), compared: period.compare !== undefined };
  }
}

PeriodRequest has preset?: PeriodPreset, range?: PeriodWindow (absent for all), compare?: PeriodWindow (absent with no comparison, and for all), comparison: PeriodComparison (none exactly when compare is absent) and timeZone?: string, the browser's zone from the dms-time-zone cookie. A PeriodWindow is { from: Date; to: Date }, both included. The windows are the instants the selector resolved in the browser's time zone, so the route needs no preset logic of its own.

A malformed period throws HTTPResult 400 whose body { message, params } names the fault with a $dms.refusals.period translation key, such as $dms.refusals.period.not_an_instant with { name, text }: a bound that is not an ISO instant, a window missing a bound or ending before it starts, an unknown preset or comparison, all with bounds, another preset without them, or none with a comparison window. A request with no period parameters reads as all with no comparison.

SaveComponentFiles

SaveComponentFiles<T>(request: AttachmentSaveRequest, save: (promoted: Record<string, unknown>) => Promise<AttachmentSaveResult<T>>): Promise<T> comes from @antelopejs/interface-dms/attachments. Call it from a write route, after authorization, to validate where native files came from, promote staging keys, and persist once through save. The file storage guide covers the form and upload flow and storage authorization.

AttachmentSaveRequest contains:

FieldTypeContract
contextRequestContextThe authorized server request.
componentIdsstring[]Trusted component identities, never ids the client supplies.
fieldsAttachmentField[]Attachment fields the server declares.
submittedRecord<string, unknown>The submitted values.
beforeRecord<string, unknown>The values persisted before, loaded by the server.

Each AttachmentField has id (matching the form's attachmentField), key (the document field), and kind: "file" | "image". The optional storage, visibility: "private" | "public" and constraints: UploadConstraints select the provider and the upload policy. UploadConstraints comes from @antelopejs/interface-file-storage.

The callback returns an AttachmentSaveResult<T> of { document, result }. document holds the values actually saved, used for cleanup, and result goes back to the caller. Retained objects keep their declared visibility. Removed native files are deleted only after persistence succeeds, and cleanup failures are logged. A failed save leaves promoted objects in place, because another save may reference them. Cleanup is not reference-counted, so the caller must not share file keys between documents. The internal attachment validators and the table view save proxies are not entry points for consumers.