API Architecture

Clarify @movk/nuxt's responsibility boundary, organize direct backend calls, same-origin proxies, and minimal BFFs with lean layers, and wire up both authentication patterns.
View source

When setting up a Nuxt project with @movk/nuxt, over-complication almost always comes from two habits: wrapping $api / useApiFetch in another custom interceptor layer, and writing dozens of pass-through BFF files or wrapper functions just to rename fields or expose REST routes.

This guide establishes a practical boundary, selection order, strict layering rules, and minimal examples so your API layer stays flat and maintainable.

Responsibility Boundary

Separate what @movk/nuxt already handles from what your application decides:

OwnerResponsibilitiesReference
Built into @movk/nuxtMulti-endpoint $api creation & caching, isolating server-only headers from client publicHeadersEndpoints · $api
Built into @movk/nuxtAutomatic token injection from session, 401 session cleanup & login redirect, movk:api:unauthorized hookAuth Integration · Hooks
Built into @movk/nuxtBusiness status checks (businessCheck), unwrapping (unwrap), normalized ApiError, method-filtered toastsOverview · $api
Built into @movk/nuxtSSR/CSR caching & dedupe keys (useApiFetch family), upload/download progress, SSE streaminguseApiFetch · Upload & Download · Streaming
Your ApplicationChoosing direct / same-origin proxy / minimal BFF per endpoint, domain contracts, and thin server boundariesThis guide
The API domain relies on the Nuxt runtime and server-private runtimeConfig isolation — it is only available in Nuxt mode. Plain Vue + Vite mode includes UI components, AutoForm, DataTable, and general-purpose composables.

Selection Decision Tree

Evaluate every backend integration in the order Direct → Same-Origin Proxy → Minimal BFF. One project can mix all three via multiple endpoints:

flowchart TD
    A["Add a new backend endpoint group"] --> B{"Supports CORS and browser can send credentials directly?"}
    B -- "Yes" --> C["Direct Backend: configure endpoint baseURL only"]
    B -- "No" --> D{"Browser session already authorized; only need CORS, same-origin cookies, or runtime host?"}
    D -- "Yes" --> E["Same-Origin Proxy: /proxy/:target/* -> upstream"]
    D -- "No (privileged session switch / tenant lock / secrets / multi-step login / fan-out / binary cache)" --> F["Minimal BFF: server/api/ -> single gateway entry"]
PatternRequest PathWhen to Choose It
Direct BackendApp → BackendPublic API or CORS-enabled backend where the browser carries credentials directly — zero server code
Same-Origin ProxyApp → /proxy/** → BackendBrowser's own session already authorizes the upstream path (e.g. /proxy/gateway/:menuId/:buttonId); you only hide internal hosts, avoid CORS, share cookies, or switch upstream URLs at runtime
Minimal BFFApp → server/api/ → UpstreamRequires server-only secrets, privileged session switching with server-enforced tenant params, multi-step login cookie setup, multi-upstream aggregation, sharded concurrency limits, or binary packing & caching
Do not build a BFF just to rename fields or proxy direct gateway paths:
  • When an upstream returns snake_case or bare arrays, disable businessCheck and unwrap on that endpoint, put a Zod .transform() in shared/contracts/, and pass it to useApiFetch's transform option once on the client.
  • If the browser's own session already has permission to call a gateway path and the backend isolates tenants by session, call the same-origin proxy directly from app/composables/api/ without a BFF.

Layering Rules (Hard Constraints)

Keep every request path easy to trace by following six constraints:

  1. Parse contracts once: keep Zod schemas and field mappings in shared/contracts/. Direct/proxy endpoints parse once in the composable or transform; BFFs output the final view model without re-parsing on both sides.
  2. Call directly per domain on the client: organize app/composables/api/ by domain and call $api, useApiFetch, or useClientApiFetch directly — never add a custom request.ts wrapper.
  3. One upstream factory and one entry on the server: keep a single upstream client factory (timeout, logging, 502/504 mapping) and a single call helper per upstream family (context switching + envelope unwrapping) in server/utils/.
  4. Keep routes as thin gatekeepers: server/api/ handlers only validate params/body, call one service/helper function, and return the unified response envelope — no loops, retries, or aggregations inside route files.
  5. At most two server layers per upstream: route → single upstream entry → upstream. Never stack specialized pass-through helpers on top of generic helpers.
  6. Eliminate single-caller wrappers and shell routes: inline any helper with only one caller; consolidate repetitive BFF CRUD/query endpoints into dual read/write operation tables (query/[op].get.ts + action/[op].post.ts) instead of maintaining dozens of [id].get/put/delete.ts files.

Three Integration Patterns Example

nuxt.config.ts
const baseURL = process.env.NUXT_APP_BASE_URL || '/'

export default defineNuxtConfig({
  modules: ['@movk/nuxt'],
  app: { baseURL },
  // Injected at container runtime via NUXT_GATEWAY_URL / NUXT_SENSOR_URL / NUXT_ORDERS_TOKEN
  runtimeConfig: {
    gatewayUrl: '',
    sensorUrl: '',
    ordersToken: ''
  },
  movk: {
    api: {
      // Show automatic success toasts only for mutating methods; keep GET queries silent
      toast: {
        success: { methods: ['POST', 'PUT', 'PATCH', 'DELETE'] }
      },
      endpoints: {
        // 1. Minimal BFF: enables { code, message, data } validation and unwrapping by default
        default: { baseURL: `${baseURL}api` },
        // 2. Same-origin proxy: mostly raw responses; opt in per request when needed
        gateway: {
          baseURL: `${baseURL}proxy/gateway`,
          response: { businessCheck: false, unwrap: false, messageKey: 'msg' }
        },
        // 3. Unauthenticated service returning bare arrays: disable auth to prevent token leaks & false logouts
        sensor: {
          baseURL: `${baseURL}proxy/sensor`,
          response: { businessCheck: false, unwrap: false },
          auth: {
            enabled: false,
            unauthorized: { clearSession: false, redirect: false }
          }
        }
      }
    }
  }
})
Why createError({ statusCode, message }) instead of putting localized text in statusMessage? HTTP status lines only allow ASCII characters — passing non-ASCII text in statusMessage causes Node / Undici to throw Invalid character in statusMessage as a 500 error. Put user-facing messages in message, which @movk/nuxt extracts automatically.

Two Authentication Architectures

Both patterns rely on nuxt-auth-utils for encrypted session cookies. Always configure at least a 32-character NUXT_APP_SECRET in production.

Pattern A: Built-in Backend Auth (Backend Issues Token / SessionId)

When an auth service or gateway issues tokens and expects them in a header (Authorization: Bearer <token> or a custom header like sessionId):

  1. Enable movk.api.auth.enabled: true (reads session.token by default, injects the header, and handles 401 cleanup + /login redirect; for custom headers such as sessionId, set headerName: 'sessionId', tokenType: 'Custom').
  2. In your login handler, call await setUserSession(event, { user, token }).
  3. On the login page after success, run await useUserSession().fetch() followed by clearNuxtData() before navigating so stale data from a previous account never flashes.
  4. For silent token refresh, hook movk:api:unauthorized, set result.handled = true on success, and call refreshNuxtData().
If security rules forbid exposing the raw token to browser JS, store it in setUserSession(event, { user, secure: { token } }), set movk.api.auth.enabled: false, and inject secure.token inside proxy/[target]/[...path].ts using getUserSession(event).

Pattern B: No Built-in Backend Auth (Nuxt Manages Sessions, or Upstream Uses a Service Key)

When upstreams only accept a static server API key or Nuxt handles user login directly:

  1. Register nuxt-auth-utils explicitly in modules and keep movk.api.auth.enabled: false (auth.unauthorized still cleans up sessions and redirects on 401).
  2. Call const { user } = await requireUserSession(event) in protected BFF routes before calling upstreams with private keys from useRuntimeConfig(event).
  3. Forward cookies to same-origin /api requests during SSR in app/plugins/ssr-cookie.server.ts (never forward cookies to external domains):
app/plugins/ssr-cookie.server.ts
export default defineNuxtPlugin((nuxtApp) => {
  const { cookie } = useRequestHeaders(['cookie'])
  if (!cookie) return

  nuxtApp.hook('movk:api:request', ({ request, options }) => {
    const base = options.baseURL || ''
    const url = typeof request === 'string' ? request : ''
    const isSameOrigin = (base.startsWith('/') && !base.startsWith('//'))
      || (!base && url.startsWith('/') && !url.startsWith('//'))
    if (!isSameOrigin) return

    const headers = new Headers(options.headers as HeadersInit | undefined)
    if (!headers.has('cookie')) {
      headers.set('cookie', cookie)
      options.headers = headers
    }
  })
})

Anti-Pattern Checklist

Any of the following signs means your API layer is becoming over-engineered and should be simplified immediately:

Anti-PatternProblemRecommended Fix
Writing a BFF just to rename fieldsAdds extra network hops and dozens of pass-through routesDisable unwrap on the endpoint and transform once in shared/contracts/ via Zod
Parsing twice on server and clientServer maps DTOs and client runs safeParse againPick one parsing boundary: parse in client composables for direct/proxy, or return view models directly from BFF
One shell route per CRUD endpointDozens of [id].get/put/delete.ts files repeating validate + forwardConsolidate into read/write operation tables (query/[op].get.ts + action/[op].post.ts)
Multiple client factories per upstreamTimeout, logging, and error mapping diverge across filesKeep a single createUpstream and one entry helper in server/utils/gateway.ts
Mixing incompatible envelopesBFF mixes raw upstream envelopes with custom { code, data }Always return Movk's default envelope from custom BFFs; keep raw payloads on proxy/direct endpoints
Single-caller intermediate wrappersroute → helperA → helperB → service → client indirectionInline single-caller helpers; keep at most two server layers per upstream
Non-ASCII text in statusMessageNode/Undici rejects non-ASCII HTTP status lines with 500Always pass localized error text in createError({ statusCode, message })

New Endpoint Checklist

Verify these seven items before adding a new backend integration:

  1. Choose the simplest topology: prefer direct over proxy, and proxy over BFF; only use server/api/ for secrets, privileged session switching/tenant locking, multi-step login, aggregations, sharded limits, or binary caching.
  2. Match endpoint config to payload shape: disable response.businessCheck, response.unwrap, and auth.enabled for unauthenticated raw-payload endpoints.
  3. Keep a single parsing point: store Zod schemas in shared/contracts/ and validate/map once.
  4. Control toasts and concurrency: keep GET quiet via toast.success.methods, and use useAsyncData + Promise.all instead of sequential await useApiFetch waterfalls.
  5. Handle enabled gating transitions: useAsyncData / useClientApiFetch enabled only gates and aborts requests — it does not auto-trigger when switching false → true, so watch enabled and call execute() when status === 'idle'.
  6. Guard error boundaries: map upstream schema mismatches and connection failures to 502 / 504 on the server (using message for localized text), never leaking stack traces or internal config.
  7. Reuse existing operation tables: register new similar admin reads or mutations in ADMIN_READS / ADMIN_ACTIONS instead of duplicating route and service boilerplate.
Copyright © 2025 - 2026 YiXuan - MIT License