docs

RPC API

How do you add a customer action that changes data, such as adding a product to the basket or saving a purchase order number? You write an oRPC procedure. A procedure is a typed server function in src/server/api/: you describe its input and output with Zod schemas, list the errors it can throw, and write a handler that calls your services. You add it to apiRouter in src/server/api/index.ts, and a Vue component calls it through useRpcClient(), with the input and the result typed from your server code. oRPC carries the call, and mountAPIRouter from @scayle/storefront serves every procedure under /api.

When an action belongs in RPC

Page data and customer actions take different paths in the Storefront Application V3. A controller resolves everything a page shows while the server renders it, and the page receives it as props: as HTML on the first load and as JSON on every visit after that. A procedure covers what happens once the page is on screen: the customer clicks, types, or submits, and something on the server changes. Adding to the basket, applying a promotion code, updating the profile, and signing out are all procedures.

The rule follows from that split. If the server can know it when it renders the page, it's a prop, and Pages and Controllers covers it. If it changes data, it's a procedure. A few reads are procedures too, because they depend on something that only exists after rendering: search suggestions follow what the customer types, and the recently viewed products slider loads product IDs that the browser keeps in local storage. Loading other page data through a procedure from the browser renders the page without that data first and costs a second round trip.

How a call reaches your procedure

A procedure call is an HTTP request that passes the same middleware as a page request and then branches off to the API router:

A component calls rpcClient.basket.add as a POST to /api/basket/add. The runtime resolves country and session, the API router checks the CSRF header, then middleware, input validation, the handler and output validation run. JSON returns.

useRpcClient() returns the client that src/client/main.ts installs. It sends every call as a POST to /api/<domain>/<key>, with the active country's shopCountryId in the X-Shop-Country-Id header, the x-csrf-token header oRPC's CSRF check expects, and the session cookie. On the server, createStorefrontRuntime resolves the country from that header, loads the session, and builds the registries, as it does for a page. Request Lifecycle lists every stage. A request that resolves no country is answered with a 400 before any procedure runs. The browser code imports only the router type from src/server/api/index.ts, the one import ESLint allows from src/server, see Project Structure.

src/server/index.ts registers mountAPIRouter ahead of the SSR router, so a country segment in a page route never swallows /api. It matches the path to a procedure and rejects a call without the CSRF header with a 403, which is why a hand-written fetch to /api fails. Inside the procedure, the builder's middleware runs first, which is where authed turns a user away. oRPC then validates the input, calls your handler, and validates what the handler returns. Session writes in the handler persist when the response leaves, the same as in a controller.

During server rendering, useRpcClient() returns a different client, the one src/client/ssr.ts installs. It calls the procedure in-process with the request's own context, without an HTTP round trip and without the CSRF check. The CMS product blocks use it to render their products into the first HTML.

A successful call changes data on the server and leaves the page props as they were, because oRPC and Inertia don't talk to each other. The component reloads the props the action changed, as Show the change on the page describes.

/api speaks oRPC's RPC protocol, not REST. A call carries its input in oRPC's JSON envelope. The OpenAPI document behind /api/docs describes your procedures as REST endpoints and covers neither the envelope nor the headers above, so a native app or a partner can't call them from the document alone. A request built from it lacks the CSRF header and is rejected with a 403.

What a procedure is made of

The SDK's wishlist.remove is a complete procedure in a few lines:

Each part has one job:

  • The builder, base or authed from src/server/api/base.ts, decides who may call the procedure. You pass it when you build the procedure, not in the definition, so the same definition can be built on either.
  • route carries the HTTP method, a summary, and a description for the generated API docs. It has no path. The path comes from the procedure's place in apiRouter, so wishlist.remove answers at /api/wishlist/remove, and the browser client sends every call as a POST whatever method says.
  • input is a Zod schema that oRPC checks before the handler runs, so the handler only ever sees valid, typed input. A procedure without input, such as auth.logout, leaves it out.
  • output is checked against what the handler returns. z.custom<T>() types the result without a runtime check, for a shape such as a mapped wishlist that would be impractical to restate in Zod. z.void() says nothing comes back.
  • errors lists the codes the handler can throw, each with an HTTP status and a default message. {} means none beyond UNAUTHORIZED, which every procedure gets from base.
  • handler receives the validated input, the typed errors, and a context with four members: storefront for the config, the Storefront API client, the cache, and the active country, request for the inbound request and its session, and the request's mappers and services, the same instances a controller reads.

defineRpc checks the handler against the definition's own schemas and error map and returns the object unchanged. buildRpc(builder, definition) turns it into a procedure. The two steps keep a definition reusable: the SDK exports one for every procedure it ships, such as addToBasketDefinition, so you can rebuild one with a single part swapped.

The handler coordinates, and the services do the domain work, the same split that controllers follow. Layers and Data Flow covers where a fetch belongs.

How errors reach the browser

The browser never sees a thrown error. useRpcClient() wraps the oRPC client with createSafeClient, so every call resolves to an object: data holds the output on success, and error holds the failure otherwise.

What the browser can do with a failure depends on whether the procedure declared it. A declared error has its code in the procedure's errors map, or is UNAUTHORIZED, which base declares for every procedure. The handler throws it with errors.CODE(), and it arrives with isDefined: true, the declared status and message, and error.code narrowed by TypeScript to the codes that procedure can throw. That narrowing is the reason to declare errors: the component can tell the customer what went wrong, such as an out-of-stock variant, through a check the compiler verifies.

Everything else arrives with isDefined: false. That covers an input the schema rejects (BAD_REQUEST, unless the procedure declares that code itself), a network failure, and any other exception from the handler or a service. An unexpected exception reaches the browser as INTERNAL_SERVER_ERROR with a generic message, and the original error stays on the server, so no stack trace or upstream response leaks.

On the server, the onError interceptor that src/server/index.ts hands to mountAPIRouter logs failed calls. Errors and Logging covers the log levels.

Add your first procedure

In this tutorial, you add a field to the basket page where a business customer enters a purchase order number. A procedure stores the number in the session. A PurchaseOrderCustomDataService, which you write and register as shown in Extending the SDK, reads it from there and sends it with the basket and the checkout. You need the Storefront Application running locally with pnpm dev.

Step 1: Define the procedure

Create src/server/api/purchase-order.ts:

The input schema trims the number and rejects an empty one, so the handler only runs with a usable value. The handler merges the number into customData instead of replacing it, so keys that other code stores there survive. z.void() declares that nothing comes back: order custom data stays out of procedure results and page props, and reaches the browser only inside the signed checkout JWT.

Step 2: Add it to the router

Import the router in src/server/api/index.ts and give it a key in apiRouter:

The key becomes the namespace on the client and the first segment of the path, so the procedure answers at /api/purchaseOrder/setNumber. The client needs no change. Its type, RpcClient in src/client/utils/orpc.ts, is built from APIRouter, so every component sees the new procedure as soon as you save the file.

Step 3: Call it from a component

Add a purchase_order group with label, save, saved, and save_error keys to src/i18n/locales/en_GB.json, and then to every other locale file. Then create the component:

rpcClient.purchaseOrder.setNumber accepts exactly the input the schema describes, so TypeScript rejects a misspelled field or a number where the schema wants a string. Render <SFPurchaseOrderNumber /> on the basket page in src/client/pages/Basket.vue.

Step 4: Try it

Open the basket in the running application, enter a number, and save. The browser's network panel shows a POST to /api/purchaseOrder/setNumber answered with 200, and the success toast appears. Save an empty field, and the call answers 400: the input schema rejected it before the handler ran, and the component shows the error toast. In development, /api/docs lists the new procedure with the summary from route.

The oRPC panel of Storefront DevTools lists the same call with the input your client sent, decoded, and the response.

The number now sits in the session, so it survives a page reload. To send it with the basket and the checkout, register the PurchaseOrderCustomDataService from Extending the SDK, which reads it from there. Require a signed-in customer restricts the procedure to signed-in customers, and Test a procedure covers it with a unit test.

Common tasks

Require a signed-in customer

Build the procedure on authed instead of base. The definition stays the same:

A user's call now fails with UNAUTHORIZED before the handler runs. Handle that code in the component as shown in Handle errors in the browser.

authed checks for an unexpired access token, not for a signed-in customer. Session and Authentication explains the difference and when to build on base instead, as the SDK's auth.logout does.

A defineRpc handler is typed against the plain request context, so it doesn't see the accessToken that authed adds. You rarely need it, because the services that call the customer APIs, such as services.customer, read the token from the session themselves.

Add a typed error

When the customer needs to know why an action failed, declare the reason as a code in the definition's errors and throw it from the handler. Give each code an HTTP status from HttpStatusCode in @scayle/storefront, so a typo in a status fails to compile. A common oRPC code such as NOT_FOUND or INTERNAL_SERVER_ERROR can be declared as {} to keep oRPC's default status and message.

BasketService reports a failure as a result instead of throwing, and the SDK's basket.add maps each result to a code:

End the switch with a default that throws, so a result the service adds later fails loudly instead of falling through as a success. Pass { message } to override the message for one throw, and { cause } to keep the upstream error on the server. The browser receives the code, the status, and the message, never the cause.

Handle errors in the browser

Check isDefined first, then error, and treat the rest as success. isDefined narrows error.code to the codes the procedure declares, so the compiler checks every code you compare against. This version of the tutorial component tells a user to sign in, with a sign_in_required label next to the others:

The second branch catches every failure without a declared code, so show one generic message for all of them. With several declared codes, a switch (error.code) inside the first branch gives each its own message, as useBasket does for basket.add.

Show the change on the page

After a successful call, reload the props the action changed. The composables carry a helper for their own prop: reloadBasket from useBasket, reloadWishlist from useWishlist, and reloadCustomer from useCustomer. For any other prop, call partialReload from src/client/utils/router.ts with the prop names. usePromotionCode reloads the basket once a code applies:

A partial reload asks the server for the named props only, so the rest of the page stays as it is. useBasket reloads the basket even after a failed call, because a failed basket call can still have changed the basket on the server.

Add a procedure to an existing domain

When the action belongs to a domain that already exists, add it there, so the client finds it next to its siblings.

For a domain you own, add the definition to its file and a key to its router object, the way src/server/api/cms.ts holds both of its procedures in cmsRouter. apiRouter already holds the router, so nothing else changes.

For a domain the SDK ships, spread the factory's result in src/server/api/index.ts and add your key:

The browser then calls it as rpcClient.basket.setPurchaseOrderNumber(...). Pick a key the SDK doesn't use, because a key that matches one of its procedures replaces that procedure.

Change an SDK procedure

To run a check before the handler or to declare extra error codes, chain .use(...) or .errors(...) on the SDK procedure in src/server/api/index.ts and assign the result back under its key. The rest of the procedure stays as the SDK ships it, and the client types pick up the new codes.

To change its input, output, or handler, for example to accept an extra field on basket.add, spread its exported definition, such as addToBasketDefinition, swap the part you need, and build it with buildRpc under the same key. The buildRpc JSDoc in @scayle/storefront shows a full example. Widening an input or adding an error code keeps existing callers working, and narrowing an input breaks them.

When you rebuild a profile procedure, build it on authed, not base, or it loses its access token check.

Test a procedure

Call the procedure directly with call from @orpc/server and a mock context. No server or HTTP request is involved:

Run it with pnpm exec vitest run src/server/api/purchase-order.test.ts. A success test calls with a valid number and asserts the session.set call. createMockRequestContext takes overrides, such as a session from createMockSession or services from createMockServiceRegistry. A test of a procedure built on authed also mocks decodeJwt from jose, because authed checks the token's expiry before the handler runs, as src/server/api/base.test.ts shows.

Browse the generated API docs

In development, mountAPIRouter serves a reference of every procedure in apiRouter: a Scalar UI at /api/docs and the OpenAPI document behind it at /api/spec.json. Each entry shows the procedure's path, the method, summary, and description from route, and its error codes. specInfo in src/server/index.ts sets the document's title and version.

The Storefront Application passes enableDocs: import.meta.env.DEV, so a production build serves neither path. Pass true to serve them from a deployment, and keep in mind that both are public once enabled.

RPC reference

Procedure builders

BuilderBuilt in src/server/api/base.ts asWho can call itThe handler's context
basecreateBase()Users and signed-in customersstorefront, request, mappers, services
authedbase.use(createOrpcAuthMiddleware(base))Callers whose session holds an unexpired access tokenThe same, plus accessToken at runtime

Both declare UNAUTHORIZED with status 401 and the message Not authenticated. createBase, createOrpcAuthMiddleware, defineRpc, buildRpc, HttpStatusCode, and mountAPIRouter come from @scayle/storefront.

Error codes

CodeStatusisDefinedWhen
UNAUTHORIZED401trueauthed finds no valid access token, or a handler throws it.
A code in errorsAs declaredtrueA handler throws errors.<CODE>().
BAD_REQUEST400Only if the procedure declares itThe input fails the schema. The message is Input validation failed, and error.data.issues lists the problems.
INTERNAL_SERVER_ERROR500Only if the procedure declares itThe handler's result fails the output schema.
INTERNAL_SERVER_ERROR500falseThe handler throws something that isn't an oRPC error. The message is generic, and the original stays on the server.
CSRF_TOKEN_MISMATCH403falseThe request lacks the x-csrf-token header that the browser client adds.

Endpoints under /api

PathRegistered byWhat it serves
/api/<domain>/<key>mountAPIRouterOne procedure of apiRouter, in oRPC's RPC protocol. The browser client calls it with POST.
/api/docsmountAPIRouterThe Scalar API reference, when enableDocs is set.
/api/spec.jsonmountAPIRouterThe OpenAPI document, when enableDocs is set.
/api/upregisterHealthRouteThe health probe, { status: 'up' }, registered before every other middleware.
/api/analytics/eventsmountAnalyticsRouteThe SCAYLE Analytics beacon, a plain Hono route rather than a procedure.

mountAPIRouter(app, router, options) takes three options:

OptionDefaultWhat it does
interceptorsNoneoRPC interceptors around every call. The Storefront Application logs failures with onError.
specInfoNoneThe title, version, and optional description of the OpenAPI document.
enableDocsimport.meta.env.DEVServes /api/docs and /api/spec.json. True under pnpm dev, false in a production build.

Domains in apiRouter

The basket, wishlist, auth, search, and profile domains come from create<Domain>Router(base) factories in @scayle/storefront, and profile sits behind the auth check. cms comes from cmsRouter in src/server/api/cms.ts. The factories ship one definition per procedure, such as addToBasketDefinition for basket.add and logoutDefinition for auth.logout. The procedures of each domain are listed in the generated API docs.

Client

NameWhereWhat it does
useRpcClient()src/client/composables/useRpcClient.tsReturns the client. Every call resolves to { error, data, isDefined, isSuccess } and never throws.
RpcClientsrc/client/utils/orpc.tsThe client's type, built from APIRouter.
createBrowserOrpcPluginsrc/client/plugins/orpcBrowser.tsInstalls the HTTP client in the browser, built with createBrowserOrpcClient from @scayle/storefront/client.
createSsrOrpcPluginsrc/client/plugins/orpcServer.tsInstalls the in-process client for server rendering, built with createSsrOrpcClient from @scayle/storefront.
partialReload(only)src/client/utils/router.tsReloads the named Inertia props after a call.