Server API Routes

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.

1Browser  →  Server Route  →  B2C Commerce API
2   ↑                              ↓
3   └────── JSON Response ─────────┘

This architecture provides:

  • 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 

TermDefinition
Server routeAny route file in src/routes/ that runs on the server.
Resource routeA server route that exports only data functions (no default component).
LoaderA function that handles GET requests and returns data.
ActionA 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.

1// src/extensions/store-locator/routes/resource.stores.ts
2import { data, type LoaderFunctionArgs } from 'react-router'
3import { extractResponseError } from '@/lib/utils'
4import { createApiClients } from '@/lib/api-clients'
5
6export async function loader({ request, context }: LoaderFunctionArgs) {
7    try {
8        const url = new URL(request.url)
9        const postalCode = url.searchParams.get('postalCode') ?? undefined
10        const maxDistance = url.searchParams.get('maxDistance')
11        const distanceUnit = url.searchParams.get('distanceUnit') ?? 'km'
12
13        const clients = createApiClients(context)
14
15        const { data: stores } = await clients.shopperStores.searchStores({
16            params: {
17                query: {
18                    postalCode,
19                    maxDistance: maxDistance ? Number(maxDistance) : undefined,
20                    distanceUnit: distanceUnit as 'mi' | 'km',
21                },
22            },
23        })
24
25        return Response.json({ success: true, stores })
26    } catch (error) {
27        const { responseMessage, status_code } = await extractResponseError(error as Error)
28        return data(
29            { success: false, error: responseMessage },
30            { status: Number(status_code) }
31        )
32    }
33}

Action Routes (POST/PUT/DELETE) 

Use an action to handle mutations and form submissions. This example shows a locale-setting endpoint.

1// src/routes/action.set-locale.ts
2import { data, type ActionFunction } from 'react-router'
3import { localeCookie } from '@/middlewares/i18next.server'
4
5export const action: ActionFunction = async ({ request }) => {
6    const formData = await request.formData()
7    const locale = formData.get('locale') as string
8
9    if (!locale) {
10        throw new Response('Locale is required', { status: 400 })
11    }
12
13    const cookieHeader = await localeCookie.serialize(locale)
14
15    return data(
16        { success: true },
17        {
18            headers: {
19                'Set-Cookie': cookieHeader,
20            },
21        }
22    )
23}

Dynamic Route Parameters 

Use dynamic segments when a family of endpoints shares a common shape.

1// src/routes/resource.auth.$operation.ts
2import type { ActionFunctionArgs } from "react-router";
3
4type AuthHandler = (request: Request, context: ActionFunctionArgs["context"]) => Promise<unknown>;
5
6const authHandlers: Record<string, AuthHandler> = {
7  "refresh-token": handleRefreshToken,
8  "login-guest": handleLoginGuest,
9  "login-registered": handleLoginRegistered,
10};
11
12export async function action({ request, params, context }: ActionFunctionArgs) {
13  const operation = params.operation as string;
14
15  const handler = authHandlers[operation];
16  if (!handler) {
17    return Response.json({
18      success: false,
19      error: `Unknown auth operation: ${operation}`,
20    });
21  }
22
23  try {
24    const result = await handler(request, context);
25    return Response.json({ success: true, data: result });
26  } catch (error) {
27    return Response.json({ success: false, error: "Operation failed" });
28  }
29}

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.

1import { useScapiFetcher } from "@/hooks/use-scapi-fetcher";
2import { useEffect } from "react";
3
4export function ProductDetails({ productId }: { productId: string }) {
5  // The hook expects: (clientName, methodName, options)
6  // Options use the SCAPI structure: { params: { path: {...}, query: {...} }, body: {...} }
7  const fetcher = useScapiFetcher("shopperProducts", "getProduct", {
8    params: {
9      path: { productId },
10    },
11  });
12
13  useEffect(() => {
14    fetcher.load();
15  }, [productId]);
16
17  if (fetcher.state === "loading") return <div>Loading...</div>;
18  if (!fetcher.success) return <div>Error: {fetcher.errors?.join(", ")}</div>;
19  if (!fetcher.data) return null;
20
21  return (
22    <div>
23      <h1>{fetcher.data.name}</h1>
24      <span>{fetcher.data.price}</span>
25    </div>
26  );
27}

For mutations, use the submit method.

1import { useScapiFetcher } from "@/hooks/use-scapi-fetcher";
2
3export function UpdateProfile({ customerId }: { customerId: string }) {
4  const fetcher = useScapiFetcher("shopperCustomers", "updateCustomer", {
5    params: {
6      path: { customerId },
7    },
8    body: {},
9  });
10
11  const handleSubmit = (formData: FormData) => {
12    fetcher.submit(formData);
13  };
14
15  return (
16    <form
17      onSubmit={(e) => {
18        e.preventDefault();
19        handleSubmit(new FormData(e.currentTarget));
20      }}
21    >
22      <input name="firstName" placeholder="First Name" />
23      <input name="lastName" placeholder="Last Name" />
24      <button type="submit" disabled={fetcher.state === "submitting"}>
25        {fetcher.state === "submitting" ? "Saving..." : "Save"}
26      </button>
27    </form>
28  );
29}

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.

Tip

Request and Response Patterns 

Server routes use standard Web APIs, such as Request, Response, and FormData, for handling requests and responses. For detailed patterns, see the React Router Actions.

Error Handling 

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";
4
5export async function action({ request }: ActionFunctionArgs) {
6  try {
7    const formData = await request.formData();
8    const result = await performOperation(formData);
9
10    return Response.json({ success: true, data: result });
11  } catch (error) {
12    // Use extractResponseError to safely extract error details
13    const { responseMessage, status_code } = await extractResponseError(error as Error);
14
15    return data({ success: false, error: responseMessage }, { status: Number(status_code) || 500 });
16  }
17}

Status Code Guidelines

StatusUse Case
400Validation errors for missing or invalid input.
401Authentication required.
403Authorization denied.
404Unknown operations or resources.
500Unexpected 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.

1import { useFetcher } from "react-router";
2
3function LocaleSwitcher() {
4  const fetcher = useFetcher();
5
6  return (
7    <fetcher.Form method="post" action="/action/set-locale">
8      <select name="locale">
9        <option value="en-US">English</option>
10        <option value="fr-FR">Français</option>
11      </select>
12      <button type="submit">Change Language</button>
13    </fetcher.Form>
14  );
15}

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.

Validate Input 

Always validate and sanitize input from requests.

1export async function action({ request }: ActionFunctionArgs) {
2  const formData = await request.formData();
3  const email = formData.get("email");
4
5  if (!email || typeof email !== "string") {
6    return Response.json({ error: "Valid email address required" }, { status: 400 });
7  }
8
9  // Proceed with validated input
10}

Keep Secrets Server-Side 

Never embed client secrets in browser code. Server routes exist specifically to keep credentials secure.

1// ✅ Correct: Secret stays on server
2export async function action({ context }: ActionFunctionArgs) {
3  const clientSecret = process.env.COMMERCE_API_SLAS_SECRET;
4  // Use secret in server-side API call
5}

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.

1return data(
2  { products },
3  {
4    headers: {
5      "Cache-Control": "public, max-age=300", // Cache for 5 minutes
6    },
7  },
8);

File Naming Conventions 

File NameRoute URLPurpose
resource.stores.ts/resource/storesStore locator BFF endpoint
resource.auth.$operation.ts/resource/auth/:operationAuthentication operations
resource.api.client.$resource.ts/resource/api/client/:resourceGeneric Commerce SDK proxy
action.set-locale.ts/action/set-localeSet locale cookie server-side
action.set-currency.ts/action/set-currencySet currency preference
action.place-order.ts/action/place-orderOrder placement
loader.wishlist-products.tsx/loader/wishlist-productsWishlist products data
oauth2.jwks.ts/oauth2/jwksJWKS proxy endpoint
_empty.logout.ts/logoutLogout endpoint without layout

Dependencies 

PackagePurpose
react-routerFramework with loader/action pattern
@salesforce/storefront-next-runtimeRuntime utilities, SCAPI types

See Also