Server API Routes, also known as Resource Routes, are the standard way to fetch and mutate data in Storefront Next. They implement the Backend-For-Frontend (BFF) pattern—your client-side components communicate with these server endpoints, which securely handle B2C Commerce API calls, authentication, and sensitive business logic.
How It Works
All data fetching routes through server endpoints. Server routes handle:
API authentication: SLAS flows, client secrets, and token management.
B2C Commerce API proxying: All SCAPI calls route through server endpoints.
Callbacks and redirects: Auth redirects, webhooks, JWKS proxying.
Cookie and header management: Session handling, locale preferences.
JSON responses: Data for useFetcher() or client-side fetch() calls.
This approach keeps credentials secure, reduces client bundle size, and centralizes data access patterns.
The Backend-For-Frontend Pattern
Server routes implement the Backend-for-Frontend (BFF) pattern. Your storefront app acts as an intermediary between the client and backend services.
API aggregation: Combine multiple Commerce API calls into single endpoints.
Security: Keep API credentials and sensitive logic on the server.
Performance: Reduce client-side JavaScript and network requests.
Flexibility: Transform API responses to match your UI needs.
Server Route Architecture
Storefront Next uses React Router 7 in framework mode. Routes are defined by files in src/routes/ by using the flat routes convention.
A route module becomes a resource route (API endpoint) when it exports only data functions such as loader and action, without a default React component.
Key Concepts
Term
Definition
Server route
Any route file in src/routes/ that runs on the server.
Resource route
A server route that exports only data functions (no default component).
Loader
A function that handles GET requests and returns data.
Action
A function that handles mutations (POST, PUT, DELETE).
Naming Conventions
Storefront Next uses these naming conventions.
resource.* files map to /resource/... endpoints.
action.* files map to /action/... endpoints.
loader.* files map to /loader/... endpoints.
_empty.* files bypass parent layouts. Use this prefix when a route needs to render without the standard page wrapper, for example, the logout action that redirects immediately.
Server-Side Data Layer
All data fetching in Storefront Next happens on the server. Resource routes use loader and action functions that run server-side for both initial page loads and client-side navigation.
This server-side approach provides:
Security: Sensitive API keys and business logic stay on the server.
Performance: Reduced client bundle size.
Consistency: Single source of truth for data-fetching logic.
SEO: All data is available during server-side rendering.
Always use server-side loader and action functions. While React Router supports clientLoader and clientAction, Storefront Next enforces a server-only data retrieval. Client-side loaders expose your app to security risks and violates the architecture. If you have a rare edge case that seems to require client-side data fetching, consult with the team before implementing.
Important
Route Types
Server routes support three main patterns: loaders for GET requests, actions for mutations, and dynamic parameters for flexible endpoints.
Loader Routes (GET)
Use a loader to respond to GET requests. This example shows a store search endpoint.
This dynamic segment maps to /resource/auth/:operation. For example, /resource/auth/login-guest.
Calling B2C Commerce APIs with useScapiFetcher
For standard B2C Commerce operations, use the useScapiFetcher hook. This hook pairs with a generic server route so that you can call any SCAPI method from your components while keeping the actual API communication on the server.
You don’t interact with the underlying server route directly—the hook handles everything for you.
While useScapiFetcher looks like a direct API call, it serializes your request, sends it to the server route, executes the SDK method on the server, and returns the result. The hook provides these convenience properties: data (the response payload), errors (any error messages), success (a boolean), and state (loading, submitting, or idle).
Note
Don’t await the load() or submit() methods expecting data to be populated when the promise resolves. These methods trigger the fetch but return immediately. Use the state property or useEffect to react to data changes instead.
Handle errors gracefully and return appropriate status codes. Don’t expose sensitive information in error messages.
1import type{ActionFunctionArgs}from "react-router";2import{data}from "react-router";3import{extractResponseError}from "@/lib/utils";45export async function action({request}: ActionFunctionArgs){6 try{7 const formData = await request.formData();8 const result = await performOperation(formData);910 return Response.json({success: true, data: result});11}catch(error){12 // Use extractResponseError to safely extract error details13 const{responseMessage, status_code} = await extractResponseError(error as Error);1415 return data({success: false, error: responseMessage}, {status: Number(status_code) || 500});16}17}
Status Code Guidelines
Status
Use Case
400
Validation errors for missing or invalid input.
401
Authentication required.
403
Authorization denied.
404
Unknown operations or resources.
500
Unexpected server failures.
Call Server Routes from UI Code
Use React Router’s useFetcher() hook to call server routes without triggering a full page navigation. For complete documentation, see React Router’s Data Loading.
Don’t await the fetcher.load() or fetcher.submit() methods expecting fetcher.data to be populated when the promise resolves. These methods trigger the request but return immediately. Use fetcher.state or a useEffect watching fetcher.data to react when data arrives.
Tip
Security Best Practices
Server routes handle sensitive operations. Follow these practices.
Never embed client secrets in browser code. Server routes exist specifically to keep credentials secure.
1// ✅ Correct: Secret stays on server2export async function action({context}: ActionFunctionArgs){3 const clientSecret = process.env.COMMERCE_API_SLAS_SECRET;4 // Use secret in server-side API call5}
Avoid Open Proxies
Use the generic Commerce SDK proxy (resource.api.client.$resource.ts) carefully. If you implement similar patterns, enforce an allowlist of methods and validate parameters. Don’t expose a “call-anything” proxy without guardrails.
Set Cache Headers Intentionally
Public endpoints must set appropriate Cache-Control headers.