headless-bff-architecture
Apply when designing or modifying a BFF (Backend-for-Frontend) layer, middleware, or API proxy for a headless VTEX storefront. Covers BFF middleware architecture, public vs private API classification, VtexIdclientAutCookie management, API key protection, and secure request proxying. Use for any headless commerce project that must never expose VTEX_APP_KEY or call private VTEX APIs from the browser.
What this skill does
# BFF Layer Design & Security
## When this skill applies
Use this skill when building or modifying any headless VTEX storefront that communicates with VTEX APIs — whether a custom storefront, mobile app, or kiosk.
- Setting up a BFF (Backend-for-Frontend) layer for a new headless project
- Deciding which VTEX APIs need server-side proxying vs direct frontend calls
- Implementing credential management (`VTEX_APP_KEY`, `VTEX_APP_TOKEN`, `VtexIdclientAutCookie`)
- Reviewing a headless architecture for security compliance
Do not use this skill for:
- Checkout-specific proxy logic and OrderForm management (use [`headless-checkout-proxy`](../headless-checkout-proxy/SKILL.md))
- Search API integration details (use [`headless-intelligent-search`](../headless-intelligent-search/SKILL.md))
- Caching and TTL strategy (use [`headless-caching-strategy`](../headless-caching-strategy/SKILL.md))
## Decision rules
- A BFF layer is **mandatory** for every headless VTEX project. There is no scenario where a headless storefront can safely operate without one.
- Route all VTEX API calls through the BFF **except** Intelligent Search, which is the only API safe to call directly from the frontend.
- Use `VtexIdclientAutCookie` (stored server-side) for shopper-scoped API calls. Use `X-VTEX-API-AppKey`/`X-VTEX-API-AppToken` for machine-to-machine calls.
- Treat client-side exposure of `VTEX_APP_KEY`, `VTEX_APP_TOKEN`, `VtexIdclientAutCookie`, checkout cookies, or shopper/session tokens as a security violation — not as a recommendation or tradeoff. Use explicit wording such as “must not”, “never expose”, and “server-side only”, and avoid softer language such as “avoid”, “prefer”, or “ideally”.
- Classify APIs by their path: `/pub/` endpoints are public but most still need BFF proxying for session management; `/pvt/` endpoints are private and **must** go through BFF.
- Even public Checkout endpoints (`/api/checkout/pub/`) must be proxied through BFF for security — they handle sensitive personal data.
- Create separate API keys with minimal permissions for different BFF modules rather than sharing one key with broad access.
## Hard constraints
### Constraint: A BFF layer is mandatory for headless VTEX — no exceptions
Every headless VTEX storefront MUST have a server-side BFF layer. Client-side code MUST NOT make direct HTTP requests to private VTEX API endpoints. All private API calls must be routed through the BFF.
**Why this matters**
Private VTEX APIs require `X-VTEX-API-AppKey` and `X-VTEX-API-AppToken` headers. If the frontend calls these APIs directly, the credentials must be embedded in client-side code or transmitted to the browser, exposing them to any user who opens browser DevTools. Stolen API keys can be used to access order data, modify pricing, or perform destructive administrative actions.
**Detection**
If you see `fetch` or `axios` calls to `vtexcommercestable.com.br/api/checkout`, `/api/oms`, `/api/profile`, or any `/pvt/` endpoint in client-side code (files under `src/`, `public/`, `app/`, or any browser-executed bundle) → STOP immediately. These calls must be moved to the BFF.
**Correct**
```typescript
// Frontend code — calls BFF, not VTEX directly
async function getOrderDetails(orderId: string): Promise<Order> {
const response = await fetch(`/api/bff/orders/${orderId}`, {
credentials: "include", // sends session cookie to BFF
});
if (!response.ok) {
throw new Error(`Failed to fetch order: ${response.status}`);
}
return response.json();
}
```
**Wrong**
```typescript
// Frontend code — calls VTEX OMS API directly (SECURITY VULNERABILITY)
async function getOrderDetails(orderId: string): Promise<Order> {
const response = await fetch(
`https://mystore.vtexcommercestable.com.br/api/oms/pvt/orders/${orderId}`,
{
headers: {
"X-VTEX-API-AppKey": "vtexappkey-mystore-ABCDEF", // EXPOSED!
"X-VTEX-API-AppToken": "eyJhbGciOi...", // EXPOSED!
},
}
);
return response.json();
}
```
---
### Constraint: VtexIdclientAutCookie MUST be managed server-side
The `VtexIdclientAutCookie` token MUST be stored in a secure server-side session (e.g., encrypted cookie, Redis session store) and MUST NOT be stored in `localStorage`, `sessionStorage`, or any client-accessible JavaScript variable.
**Why this matters**
The `VtexIdclientAutCookie` is a bearer token that authenticates all actions on behalf of a shopper — placing orders, viewing profile data, accessing payment information. If stored client-side, it can be stolen via XSS attacks, browser extensions, or shared/public computers. An attacker with this token can impersonate the shopper.
**Detection**
If you see `VtexIdclientAutCookie` referenced in `localStorage.setItem`, `sessionStorage.setItem`, or assigned to a JavaScript variable in client-side code → STOP immediately. The token must be managed exclusively server-side.
**Correct**
```typescript
// BFF route — stores VtexIdclientAutCookie in server-side session
import { Router, Request, Response } from "express";
import session from "express-session";
const router = Router();
// After VTEX login callback, extract and store token server-side
router.get("/auth/callback", async (req: Request, res: Response) => {
const vtexAuthToken = req.cookies["VtexIdclientAutCookie"];
if (!vtexAuthToken) {
return res.status(401).json({ error: "Authentication failed" });
}
// Store in server-side session — never sent to frontend
req.session.vtexAuthToken = vtexAuthToken;
// Clear the cookie from the browser response
res.clearCookie("VtexIdclientAutCookie");
// Redirect to frontend with a secure session cookie
res.redirect("/account");
});
// BFF proxy uses session token for VTEX API calls
router.get("/api/bff/profile", async (req: Request, res: Response) => {
const vtexToken = req.session.vtexAuthToken;
if (!vtexToken) {
return res.status(401).json({ error: "Not authenticated" });
}
const response = await fetch(
`https://${process.env.VTEX_ACCOUNT}.vtexcommercestable.com.br/api/checkout/pub/profiles`,
{
headers: {
Cookie: `VtexIdclientAutCookie=${vtexToken}`,
},
}
);
const profile = await response.json();
res.json(profile);
});
```
**Wrong**
```typescript
// Frontend code — stores auth token in localStorage (SECURITY VULNERABILITY)
function handleLoginCallback() {
const params = new URLSearchParams(window.location.search);
const vtexToken = params.get("authToken");
// WRONG: token is now accessible to any JS on the page, including XSS payloads
localStorage.setItem("VtexIdclientAutCookie", vtexToken!);
}
// Later, reads from localStorage and sends in header
async function getProfile() {
const token = localStorage.getItem("VtexIdclientAutCookie"); // EXPOSED!
return fetch("https://mystore.vtexcommercestable.com.br/api/checkout/pub/profiles", {
headers: { Cookie: `VtexIdclientAutCookie=${token}` },
});
}
```
---
### Constraint: API keys MUST NOT appear in client-side code
`VTEX_APP_KEY` and `VTEX_APP_TOKEN` values MUST only exist in server-side environment variables and MUST NOT be present in any file that is bundled, served, or accessible to the browser.
**Why this matters**
API keys grant programmatic access to the VTEX platform with the permissions of their associated role. Exposing them in frontend bundles, public directories, or client-side environment variables (e.g., `NEXT_PUBLIC_*`, `VITE_*`) allows anyone to extract them and make unauthorized API calls.
**Detection**
If you see `VTEX_APP_KEY`, `VTEX_APP_TOKEN`, `X-VTEX-API-AppKey`, or `X-VTEX-API-AppToken` in files under `src/`, `public/`, `app/` directories, or in environment variables prefixed with `NEXT_PUBLIC_`, `VITE_`, or `REACT_APP_` → STOP immediately. Move these to server-side-only environment variables.
**Correct**
```typescript
// BFF server code — reads keys from server-side env vars only
// File: server/vtex-client.ts (never buRelated in Web Dev
generating-lwc-components
IncludedLightning Web Components with PICKLES methodology and 165-point scoring. Use this skill when the user creates or edits LWC components, builds wire service patterns, or writes Jest tests for LWC. TRIGGER when: user creates/edits LWC components, touches lwc/**/*.js, .html, .css, .js-meta.xml files, or asks about wire service, SLDS, or Jest LWC tests. DO NOT TRIGGER when: Apex classes (use generating-apex), Aura components, or Visualforce.
tanstack-query
IncludedManage server state in React with TanStack Query v5. Set up queries with useQuery, mutations with useMutation, configure QueryClient caching strategies, implement optimistic updates, and handle infinite scroll with useInfiniteQuery. Use when: setting up data fetching in React projects, migrating from v4 to v5, or fixing object syntax required errors, query callbacks removed issues, cacheTime renamed to gcTime, isPending vs isLoading confusion, keepPreviousData removed problems.
document-processor-api
IncludedProcess documents with Nutrient DWS. Use when the user wants to generate PDFs from HTML or URLs, convert Office/images/PDFs, assemble or split packets, OCR scans, extract text/tables/key-value pairs, redact PII, watermark, sign, fill forms, optimize PDFs, or produce compliance outputs like PDF/A or PDF/UA. Triggers include convert to PDF, merge these PDFs, OCR this scan, extract tables, redact PII, sign this PDF, make this PDF/A, or linearize for web delivery.
nutrient-document-processing
IncludedProcess documents with Nutrient DWS. Use when the user wants to generate PDFs from HTML or URLs, convert Office/images/PDFs, assemble or split packets, OCR scans, extract text/tables/key-value pairs, redact PII, watermark, sign, fill forms, optimize PDFs, or produce compliance outputs like PDF/A or PDF/UA. Triggers include convert to PDF, merge these PDFs, OCR this scan, extract tables, redact PII, sign this PDF, make this PDF/A, or linearize for web delivery.
tanstack-query
IncludedManage server state in React with TanStack Query v5. Covers useMutationState, simplified optimistic updates, throwOnError, network mode (offline/PWA), and infiniteQueryOptions. Use when setting up data fetching, fixing v4→v5 migration errors (object syntax, gcTime, isPending, keepPreviousData), or debugging SSR/hydration issues with streaming server components.
accelint-nextjs-best-practices
IncludedNext.js performance optimization and best practices. Use when writing Next.js code (App Router or Pages Router); implementing Server Components, Server Actions, or API routes; optimizing RSC serialization, data fetching, or server-side rendering; reviewing Next.js code for performance issues; fixing authentication in Server Actions; or implementing Suspense boundaries, parallel data fetching, or request deduplication.