The WooCommerce REST API for a headless storefront
In a headless shop, WordPress and WooCommerce keep the products, orders and payments, and a separate frontend (Next.js, Nuxt, Astro) renders the pages. WooCommerce has two APIs for this, and the most common mistake is using the wrong one: the authenticated REST API wc/v3 is for servers, the public Store API wc/store/v1 is for the visitor’s cart and checkout.
Problem: A shop moves to a Next.js frontend. The first prototype calls /wp-json/wc/v3/ from the browser with the consumer key and secret in the JavaScript bundle, which gives every visitor full read and write access to the shop.
Solution: Keep the keys on the server: the frontend’s Node.js layer calls wc/v3 with a read-only key for the catalog, while the cart and the checkout in the browser use the Store API, which works with the visitor’s session and needs no keys.
Keys and a small client
Create the key in WooCommerce → Settings → Advanced → REST API. For a catalog, permission Read is enough; a key with Read/Write is needed only for server jobs that change data. Over HTTPS, the key and secret go into a Basic Auth header.
// lib/woocommerce.js — runs only on the server (route handler, getServerSideProps, build step)
const WC_URL = process.env.WC_URL; // https://shop.example.com
const AUTH = 'Basic ' + Buffer.from( `${ process.env.WC_KEY }:${ process.env.WC_SECRET }` ).toString( 'base64' );
async function wc( path, params = {} ) {
const url = new URL( `/wp-json/wc/v3${ path }`, WC_URL );
Object.entries( params ).forEach( ( [ key, value ] ) => {
if ( value !== undefined ) url.searchParams.set( key, value );
} );
const res = await fetch( url, { headers: { Authorization: AUTH } } );
if ( ! res.ok ) {
const body = await res.json().catch( () => ( {} ) );
throw new Error( `WooCommerce ${ res.status }: ${ body.message ?? res.statusText }` );
}
return {
data: await res.json(),
totalPages: Number( res.headers.get( 'X-WP-TotalPages' ) ?? 1 ),
};
}
export function getProducts( { page = 1, perPage = 12, category, search } = {} ) {
return wc( '/products', { status: 'publish', page, per_page: perPage, category, search } );
}
export async function getProduct( id ) {
const [ product, variations ] = await Promise.all( [
wc( `/products/${ id }` ),
wc( `/products/${ id }/variations`, { per_page: 100 } ),
] );
return { ...product.data, variations: variations.data };
}
The number of pages comes in the X-WP-TotalPages header, not in the JSON body; per_page is limited to 100. Catalog data changes rarely, so the frontend should cache these answers (incremental static regeneration in Next.js, or a short server cache) instead of asking WooCommerce on every page view.
Cart and checkout with the Store API
The Store API is what the WooCommerce Cart and Checkout blocks use themselves. It is public, identifies the cart by a token and protects write requests with a nonce, both sent back by the API in response headers.
// in the browser
const STORE = 'https://shop.example.com/wp-json/wc/store/v1';
let cartToken = sessionStorage.getItem( 'haCartToken' );
let nonce = '';
async function store( path, options = {} ) {
const res = await fetch( STORE + path, {
...options,
headers: {
'Content-Type': 'application/json',
...( cartToken && { 'Cart-Token': cartToken } ),
...( nonce && { Nonce: nonce } ),
},
} );
cartToken = res.headers.get( 'Cart-Token' ) ?? cartToken;
nonce = res.headers.get( 'Nonce' ) ?? nonce;
if ( cartToken ) sessionStorage.setItem( 'haCartToken', cartToken );
if ( ! res.ok ) throw new Error( ( await res.json() ).message );
return res.json();
}
export const getCart = () => store( '/cart' );
export const addToCart = ( id, quantity = 1 ) =>
store( '/cart/add-item', { method: 'POST', body: JSON.stringify( { id, quantity } ) } );
For a variation, id is the variation ID. The response of every cart call is the whole cart with totals, taxes and shipping rates calculated by WooCommerce, so the frontend never computes prices itself. The checkout is a POST /checkout with addresses and the payment method; it works with payment gateways that support the Checkout block.
Order status for the customer
An order lookup by number alone would let anyone read other people’s orders. The thank-you link in WooCommerce contains the order key for this reason, and the server checks both:
export async function getOrderStatus( orderId, orderKey ) {
const { data: order } = await wc( `/orders/${ Number( orderId ) }` );
if ( order.order_key !== orderKey ) {
throw new Error( 'Not found' );
}
return { status: order.status, total: order.total, currency: order.currency };
}
This runs on the server with a key that can read orders; only the three fields go to the browser.
NOTE: When the frontend and WordPress are on different domains, the Store API needs CORS headers for the frontend origin and the cart token must be stored by the frontend, as above, because the WooCommerce session cookie is not sent cross-site. The WordPress side of a headless setup in general: WordPress REST API as a headless CMS backend.