API Architecture
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:
| Owner | Responsibilities | Reference |
|---|---|---|
Built into @movk/nuxt | Multi-endpoint $api creation & caching, isolating server-only headers from client publicHeaders | Endpoints · $api |
Built into @movk/nuxt | Automatic token injection from session, 401 session cleanup & login redirect, movk:api:unauthorized hook | Auth Integration · Hooks |
Built into @movk/nuxt | Business status checks (businessCheck), unwrapping (unwrap), normalized ApiError, method-filtered toasts | Overview · $api |
Built into @movk/nuxt | SSR/CSR caching & dedupe keys (useApiFetch family), upload/download progress, SSE streaming | useApiFetch · Upload & Download · Streaming |
| Your Application | Choosing direct / same-origin proxy / minimal BFF per endpoint, domain contracts, and thin server boundaries | This guide |
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"]
| Pattern | Request Path | When to Choose It |
|---|---|---|
| Direct Backend | App → Backend | Public API or CORS-enabled backend where the browser carries credentials directly — zero server code |
| Same-Origin Proxy | App → /proxy/** → Backend | Browser'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 BFF | App → server/api/ → Upstream | Requires 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 |
- When an upstream returns
snake_caseor bare arrays, disablebusinessCheckandunwrapon that endpoint, put a Zod.transform()inshared/contracts/, and pass it touseApiFetch'stransformoption 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:
- Parse contracts once: keep Zod schemas and field mappings in
shared/contracts/. Direct/proxy endpoints parse once in the composable ortransform; BFFs output the final view model without re-parsing on both sides. - Call directly per domain on the client: organize
app/composables/api/by domain and call$api,useApiFetch, oruseClientApiFetchdirectly — never add a customrequest.tswrapper. - One upstream factory and one entry on the server: keep a single upstream client factory (timeout, logging,
502/504mapping) and a single call helper per upstream family (context switching + envelope unwrapping) inserver/utils/. - 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. - At most two server layers per upstream:
route → single upstream entry → upstream. Never stack specialized pass-through helpers on top of generic helpers. - 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.tsfiles.
Three Integration Patterns Example
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 }
}
}
}
}
}
})
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):
- Enable
movk.api.auth.enabled: true(readssession.tokenby default, injects the header, and handles 401 cleanup +/loginredirect; for custom headers such assessionId, setheaderName: 'sessionId', tokenType: 'Custom'). - In your login handler, call
await setUserSession(event, { user, token }). - On the login page after success, run
await useUserSession().fetch()followed byclearNuxtData()before navigating so stale data from a previous account never flashes. - For silent token refresh, hook
movk:api:unauthorized, setresult.handled = trueon success, and callrefreshNuxtData().
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:
- Register
nuxt-auth-utilsexplicitly inmodulesand keepmovk.api.auth.enabled: false(auth.unauthorizedstill cleans up sessions and redirects on 401). - Call
const { user } = await requireUserSession(event)in protected BFF routes before calling upstreams with private keys fromuseRuntimeConfig(event). - Forward cookies to same-origin
/apirequests during SSR inapp/plugins/ssr-cookie.server.ts(never forward cookies to external domains):
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-Pattern | Problem | Recommended Fix |
|---|---|---|
| Writing a BFF just to rename fields | Adds extra network hops and dozens of pass-through routes | Disable unwrap on the endpoint and transform once in shared/contracts/ via Zod |
| Parsing twice on server and client | Server maps DTOs and client runs safeParse again | Pick one parsing boundary: parse in client composables for direct/proxy, or return view models directly from BFF |
| One shell route per CRUD endpoint | Dozens of [id].get/put/delete.ts files repeating validate + forward | Consolidate into read/write operation tables (query/[op].get.ts + action/[op].post.ts) |
| Multiple client factories per upstream | Timeout, logging, and error mapping diverge across files | Keep a single createUpstream and one entry helper in server/utils/gateway.ts |
| Mixing incompatible envelopes | BFF 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 wrappers | route → helperA → helperB → service → client indirection | Inline single-caller helpers; keep at most two server layers per upstream |
Non-ASCII text in statusMessage | Node/Undici rejects non-ASCII HTTP status lines with 500 | Always pass localized error text in createError({ statusCode, message }) |
New Endpoint Checklist
Verify these seven items before adding a new backend integration:
- 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. - Match endpoint config to payload shape: disable
response.businessCheck,response.unwrap, andauth.enabledfor unauthenticated raw-payload endpoints. - Keep a single parsing point: store Zod schemas in
shared/contracts/and validate/map once. - Control toasts and concurrency: keep
GETquiet viatoast.success.methods, and useuseAsyncData+Promise.allinstead of sequentialawait useApiFetchwaterfalls. - Handle
enabledgating transitions:useAsyncData/useClientApiFetchenabledonly gates and aborts requests — it does not auto-trigger when switchingfalse → true, so watchenabledand callexecute()whenstatus === 'idle'. - Guard error boundaries: map upstream schema mismatches and connection failures to
502/504on the server (usingmessagefor localized text), never leaking stack traces or internal config. - Reuse existing operation tables: register new similar admin reads or mutations in
ADMIN_READS/ADMIN_ACTIONSinstead of duplicating route and service boilerplate.