Augur

augur-server

Server side of an Augur Next.js site: createServerSite, the server query proxy, queryAction, Redis caching, NextAuth and environment detection.

@simpleapps-com/augur-server

The server side of an Augur site on Next.js 16: one call sets up the SDK client, server actions and NextAuth; a client proxy routes React Query through server actions so the JWT never reaches the browser; and reads are cached in Redis.

pnpm add @simpleapps-com/augur-server

Peer dependencies: @simpleapps-com/augur-api, @tanstack/react-query 5, next 16, react 19, next-auth 5; optional: ioredis 5 (without it nothing is cached) and jose (session-scoped clients). Every export, with its description: API Reference.

Entry points

Import Purpose
@simpleapps-com/augur-server createSiteActions, getSiteActions, withServerCache, sdkCall, safeAction, environment, Redis, query clients
@simpleapps-com/augur-server/site createServerSite
@simpleapps-com/augur-server/hooks createServerQueryProxy (client code; importing it registers queryAction with augur-hooks)
@simpleapps-com/augur-server/query-action queryAction, the server action behind the proxy; queryActionRaw, the same call with the full response; queryActionWith and queryActionRawWith, the same calls bounded by a deadline or signal; and getSessionCredentials
@simpleapps-com/augur-server/api createAugurApiHandler, a route handler for fetch mode
@simpleapps-com/augur-server/sitemap createSitemapIndexHandler, createItemSitemapHandler, sitemapRewrite, robotsSitemaps, isSitemapPath: item sitemaps built at request time
@simpleapps-com/augur-server/auth createAuthConfig for NextAuth
@simpleapps-com/augur-server/query createQueryOptions, createSuspenseQueryOptions
@simpleapps-com/augur-server/actions Types only: SafeActionResult, ApiResult, ListResult
@simpleapps-com/augur-server/testing createMockSiteActions, createMockClient, clearSiteActions
@simpleapps-com/augur-server/next-auth NextAuth type augmentations (/// <reference types="…/next-auth" />)

createServerSite

import { AugurAPI } from "@simpleapps-com/augur-api";
import { createServerSite } from "@simpleapps-com/augur-server/site";

const api = new AugurAPI({ siteId: process.env.AUGUR_SITE_ID!, bearerToken: process.env.AUGUR_JWT! });

export const site = createServerSite(api, {
  auth: { secret: process.env.AUTH_SECRET },
  shipping: { fromAddress: { address1: "123 Main", city: "Provo", state: "UT", postalCode: "84606" } },
});
// site.client: the SDK; site.actions: SiteActions; site.auth: a NextAuth config, when `auth` is given

It also registers what queryAction needs: the site actions, the SDK client, a Redis cache wrapper using the config's cachePrefix, redisTtl (default 3600 s) and longRedisTtl (default 28800 s), a factory for session-scoped clients, the auth secret (auth.secret, else AUTH_SECRET), and the cross-site opt-in (auth.crossSite, default off).

Cross-site sessions (one site signing users in for others, augur-support's pattern: an augur_info client and the target siteId passed to signIn) need auth: { crossSite: true }. Without it, sign-in ignores the siteId and queryAction never reads the session cookie, so pages that prefetch through it can render statically and honour revalidate. A multi-tenant site MUST set it: without it every user's call runs under the site's own client.

The config (SiteActionsConfig) also takes cachePrefix (default "<siteId>:"), edgeCache, longEdgeCache, defaultCustomerId and defaultContactId (falling back to DEFAULT_CUSTOMER_ID and DEFAULT_CONTACT_ID), convertUnitOfMeasure, and per-service options for pricing, items, search, payments, shipping and vmi.

createServerQueryProxy

The way to fetch data on sites whose JWT stays on the server. It mirrors the SDK like useAugurOptions() does, and each queryFn calls queryAction, a server action:

"use client";
import { createServerQueryProxy } from "@simpleapps-com/augur-server/hooks";
import { useMutation, useQuery } from "@tanstack/react-query";

const q = createServerQueryProxy();

const { data: item } = useQuery(q.items.invMast.doc.get(invMastUid));
const { data: price } = useQuery(q.pricing.priceEngine.list({ itemId: "SKU-1", customerId }));
const addLine = useMutation(q.commerce.cartLine.add.create());

For an infinite list, spread the options into useInfiniteQuery and add getNextPageParam and initialPageParam.

Types default to DeepQueryOptions<AugurAPI>, so a new SDK method works with no code change. Keys match createOptionsProxy and augur-hooks' createAugurOptions, so server prefetches hydrate. It takes an optional query action and an optional cache config.

queryAction

queryAction(methodPath, ...args):

  • Picks a client. On a site with auth: { crossSite: true } and a valid session (an Auth.js cookie whose targetSiteId and token agree with the token's client_id), it uses a client scoped to that site and user, and caches under "<targetSiteId>:". Otherwise it uses the site's own client, and on a site without the opt-in it reads no cookies at all (getSessionCredentials returns null).
  • Caches reads. Reads (get, list, lookup, search, suggest) are cached in Redis: the long TTL when the tier's staleTime is an hour or more, the standard TTL otherwise. It never caches a tier without a Redis TTL: commerce, payments, wishlists and favorites. P21 data (a customer's records, the user profile, orders, VMI) is held one minute. Writes go straight through.
  • Strips edge caching on no-cache, user and P21 paths. It removes edgeCache from the arguments of those calls.
  • Unwraps the response. It returns the response's data, so a client query gets T, never { data, status, message }.
  • Is typed by path. The path is one of the SDK's method paths, the arguments that method's own, the result its data type, so a wrong path or arguments that an SDK upgrade changed fail tsc instead of a live request:
await queryAction("orders.oeHdr.doc.get", orderNo, { postalCode }); // typed: the order document
await queryAction("openSearch.itemSearch.attributes.list", "moulding"); // tsc error: it takes { q, ... }

On upgrading, a site may see new type errors where it calls queryAction: each is a call the SDK would refuse. Pass one literal path per call; a union of paths is typed loosely. A path built at runtime (a route forwarding a request) has no literal type: cast it, queryAction(path as MethodPath<AugurAPI>, ...args) (augur-core's MethodPath), and its arguments are unknown[]; the allowlist still checks it. queryActionRaw keeps its caller-named T.

It caches the SDK's raw response under augur-core's buildRawCacheKey, apart from the actions' shaped values, so getStock and queryAction("items.invMast.stock.get", uid) never read each other's entry. The cache key holds the site, method and arguments but not the user's token. Users of one site share cached reads outside commerce and payments, so a namespace whose responses depend on the user MUST be added to augur-core's NO_CACHE_PATHS.

queryActionRaw

queryActionRaw<T>(methodPath, ...args) is the same call (client, cache, allowlist, edgeCache strip) answered as the SDK returned it: augur-api's BaseResponse<T>, so a page can read total / totalResults and page a list. A method path carries no type, so name the data's type as T. A queryAction and a queryActionRaw of one call share one Redis entry.

"use client";
import { queryActionRaw } from "@simpleapps-com/augur-server/query-action";
import { useQuery } from "@tanstack/react-query";

const { data: page } = useQuery({
  queryKey: ["articles-page", { limit, offset }],
  queryFn: () => queryActionRaw<Article[]>("joomla.content.list", { limit, offset }),
});
// page?.data: the articles; page?.total: how many there are in all

Give it its own query key. A key from the proxy (q.joomla.content.list(...).queryKey) holds queryAction's unwrapped value, and one key MUST hold one shape.

queryActionWith

queryActionWith(options, methodPath, ...args) (and queryActionRawWith) is the same call, bounded. A server render that awaits a read SHOULD use it: unbounded, the SDK's retry budget (3 retries at 30 s each, plus backoff) becomes page latency.

import { queryActionWith } from "@simpleapps-com/augur-server/query-action";

// In a server component: within 5 s, or render without it and let the client fetch
const items = await queryActionWith({ deadline: 5000 }, "items.categories.items.list", uid, params)
  .catch(() => undefined);
  • deadline (ms) bounds the whole call, every retry and wait included. At the deadline it rejects with a TimeoutError: the request is cancelled, nothing more is retried, and nothing is cached.
  • signal cancels it too. Server code only: a signal can't be sent to a server action from the browser, but a deadline can.
  • The options are not SDK arguments and not part of the cache key, so a bounded call and an unbounded one share one Redis entry.
  • It runs on the SDK client's withRequest view, so it needs an @simpleapps-com/augur-api that has it. On an older client the call is refused rather than run unbounded.

Fetch mode

Where server actions can't read request cookies (Cloudflare Workers through OpenNext), expose queryAction as a route and point the browser at it:

// app/api/augur/route.ts
import { createAugurApiHandler } from "@simpleapps-com/augur-server/api";

export const POST = createAugurApiHandler();
import { createFetchQueryAction } from "@simpleapps-com/augur-core";
import { registerQueryAction } from "@simpleapps-com/augur-hooks";

registerQueryAction(createFetchQueryAction("/api/augur"));

For the full response in fetch mode, call augur-core's createFetchQueryActionRaw("/api/augur"): it sends raw: true, and the route answers through queryActionRaw (any other raw gets queryAction's data).

The handler refuses cross-site requests (Sec-Fetch-Site) and bodies without a methodPath string and an args array.

Site actions

site.actions (or getSiteActions() in a server action) has 26 services: pricing, items, commerce, search, orders, shipping, joomla, legacy, customers, smartyStreets, p21Pim, agrSite, avalara, payments, logistics, vmi, p21Core, p21Apis, p21Sism, agrWork, agrInfo, basecamp2, brandFolder, gregorovich, favorites and wishlists. Each is built on first use. A method a service doesn't define falls through to augur-core's createActionsProxy, which calls the SDK method of that path and caches reads with the tier's redisTtl.

"use server";
import { getSiteActions, safeAction } from "@simpleapps-com/augur-server";

export async function getPrice(itemId: string) {
  return safeAction(() => getSiteActions().pricing.getItemPrice(itemId));
}

Each action read calls the SDK method its spec names (read-specs.ts), and its cache key uses that same path. List reads that should return everything page to the end instead of stopping at the route's default 10 rows: wishlists and their lines, favorites, ship-to addresses, states, item tags, FAQs, substitutes and accessories, agr-site settings, gregorovich documents, and a menu's children. These reads page 100 rows a call, at most 50 calls, and return { data, total, capReached }; capReached is true when the cap stopped the read, so the list may be incomplete. Wishlist and favorites reads are never cached on the server. P21 data (a customer's records, the user profile, orders, VMI) is held one minute in Redis, whatever TTL the site sets. Neither is cached at the edge. To refresh a browser's copy after the user's own write, install augur-hooks' userWriteClearing on the site's QueryClient.

getSiteActions() looks in a globalThis singleton, then a module-level copy (Next.js standalone builds can reset globalThis), then builds one from AUGUR_SITE_ID and AUGUR_JWT, and throws if none of those works.

Helpers

Export Does
safeAction(fn, onError?) { ok: true, data } or { ok: false, error } instead of throwing; for server actions, not React Query reads (let those throw so React Query retries)
sdkCall(method, ...args) Calls an SDK method with its parameter and result types inferred
withServerCache(prefix, ttl, methodPath, fn, ...keyArgs) Redis read-through for a shaped value, using augur-core's buildCacheKey; a TTL of 0, or a no-cache or user methodPath, skips caching; a P21 methodPath is held one minute
cacheGet, cacheSet, isRedisConnected, getCircuitState The Redis client; never throws, and a circuit breaker stops calls while Redis is down
batchFetch Parallel fetches keyed by param; a failed one is left out
paginateOffset Wraps a list with offset paging metadata
getServerQueryClient, createServerQueryClient A per-request QueryClient, or a new one, for prefetching
verifyRecaptcha reCAPTCHA v3 check with RECAPTCHA_SECRET_KEY
unwrap, unwrapOr Re-exported from augur-utils

Redis's URL comes from REDIS_SERVERS (containers), else REDIS_URL_DEV, REDIS_URL_STAGING or REDIS_URL_PROD by environment.

Item sitemaps

The item sitemaps are built per request from the catalog (googMc.sitemaps.items.list), so the number of files follows the catalog without a deploy, however large it is. They sit in the items' own folder, /items/ unless you pass base:

  • /items/sitemap.xml: the item index, listing one file per 5,000 items.
  • /items/sitemap-1.xml, /items/sitemap-2.xml, …: each page's items.

The sitemap protocol only lets a sitemap list URLs under its own folder, so base MUST match the item links Augur returns. A link outside it is left out.

// app/items/sitemap.xml/route.ts
import { createSitemapIndexHandler } from "@simpleapps-com/augur-server/sitemap";
import { site } from "@/lib/augur-site";

export const dynamic = "force-dynamic";
export const GET = createSitemapIndexHandler(site, { siteUrl: "https://www.example.com" });
// app/items/sitemap.xml/[page]/route.ts
import { createItemSitemapHandler } from "@simpleapps-com/augur-server/sitemap";
import { site } from "@/lib/augur-site";

export const dynamic = "force-dynamic";
export const GET = createItemSitemapHandler(site, { siteUrl: "https://www.example.com" });
// next.config.ts: serve /items/sitemap-{n}.xml from the page handler
import { sitemapRewrite } from "@simpleapps-com/augur-server/sitemap";

const nextConfig = {
  async rewrites() {
    return [sitemapRewrite()];
  },
};
// app/robots.ts
import { robotsSitemaps } from "@simpleapps-com/augur-server/sitemap";

export default function robots() {
  return {
    rules: { userAgent: "*", allow: "/" },
    sitemap: robotsSitemaps("https://www.example.com"),
  };
}
  • Main pages: the site's own root /sitemap.xml (for example Next's app/sitemap.ts) lists its static pages, categories and blog. robots.txt names it and the item index; the root sitemap doesn't list the item index, because the specs don't put one index inside another.
  • Item-URL redirects: a proxy that normalizes item URLs (for example uppercasing them) MUST pass isSitemapPath(pathname) through first. The proxy runs before rewrites, so otherwise /items/sitemap-1.xml is redirected to an item page.
  • Responses:
    • a served file is cached for a day at the CDN and an hour in browsers;
    • a page number that isn't one, or an empty page past the first, is a 404;
    • when Augur fails or takes longer than deadline (10 s by default), the response is a 503 with Retry-After, never cached.
  • Format: every value is XML-escaped, and each element sits on its own line.

Environment

env is "development", "staging" or "production", with isDev, isStaging and isProduction. It comes from DEPLOYMENT_ENV (dev is staging, live is production), else NODE_ENV on the server, else the hostname in the browser.

Auth

import NextAuth from "next-auth";
import { createAuthConfig } from "@simpleapps-com/augur-server/auth";

export const { handlers, signIn, signOut, auth } = NextAuth(createAuthConfig({ augurClient: site.client }));

A Joomla credentials provider with JWT sessions; the callbacks add the user's profile and cart header to the session. Options: augurClient or callbacks (to replace the SDK calls), secret (default AUTH_SECRET), maxAge (default 4 hours), defaultCustomerId, defaultContactId and debug. createServerSite builds this for you when given auth.

  • augur-hooks: the provider that picks up the registered queryAction
  • augur-core: the proxies, tiers and cache keys