How to Build a Headless WooCommerce Store with Next.js and the Store API
There is no @woocommerce/store-api npm package. Use the Store API with plain fetch from Next.js: cart and checkout endpoints, Cart-Token and Nonce headers, CORS, authentication choices. Checked against the docs 15 November 2026.

We checked the answer to the question most readers arrive with: the npm package @woocommerce/store-api does not exist. The npm registry returns “not found” for that name, and WooCommerce does not publish a JavaScript client for the Store API at all. You call it with plain fetch, and that is what this guide does. For a Next.js storefront, use the Store API (the wc/store/v1 namespace) for products, cart and checkout, and keep the REST API v3 with API keys for server-side admin work only.
Everything below was checked against the WooCommerce Store API documentation, the WooCommerce source code on GitHub (trunk, WooCommerce 11.3.0 was the latest release on 15 November 2026) and the current Next.js documentation (Next.js 16.4.6 was the latest release). We did not run these snippets against a live store for this refresh, so treat them as checked against the docs, not as tested output, and test them on a staging store before you rely on them.
Is there an “@woocommerce/store-api” npm package?
No. We looked it up in the npm registry on 15 November 2026: @woocommerce/store-api returns “Not found”, and so does @woocommerce/blocks-checkout, another name people search for. The Store API is a set of REST routes inside the WooCommerce plugin, and its own documentation shows plain curl calls, not an SDK.
Here is what does exist, so you can tell the real packages from the guesses:
@woocommerce/woocommerce-rest-apiis the official JavaScript client, but only for the REST API v3 (wc/v3). It signs requests with a consumer key and secret, so it belongs on a server, never in browser code. The registry lists version 1.0.2.@woocommerce/apiis published from the WooCommerce monorepo (version 0.2.0 in the registry) and describes itself as an interface for talking to a WooCommerce installation. It is not a Store API client, and we would not build a storefront on a 0.x package.- Community wrappers exist. One we found by searching,
woocommerce-store-api, has a single 1.0.0 release from May 2023 by an individual author, and we did not review its code. Check the maintenance date and the source of any wrapper before you add it as a dependency. - The WordPress.org plugin CoCart is a separate headless cart API with its own endpoints, not a wrapper around the Store API. Its listing shows version 4.9.7, updated 30 September 2026. We have not tested it for this guide.
What to use instead: a small typed fetch helper of your own (about 40 lines, shown below), run on the Next.js server. It is less code than most wrappers, and you control the headers, which is where nearly all headless problems come from.
What is headless WooCommerce, and when does it make sense?
Headless WooCommerce means WooCommerce keeps running the catalog, orders, stock, tax, shipping and payments, while a separate front end (here, Next.js) draws every page. The browser never loads a WordPress theme. Your pages talk to WooCommerce over HTTP.
It makes sense when the storefront needs behaviour a theme cannot give you: a React design system shared with a mobile app, very fast static product pages served from a CDN, or one front end over several back ends. It is the wrong choice for a small catalog that depends on plugins that print things on the front end (reviews widgets, product add-ons, page builders), because those plugins render through the theme and do not show up in a Store API response unless they extend it.
Our team’s view, from custom WooCommerce builds: count the front-end plugins first. If more than two or three change what a shopper sees, the cost of rebuilding each one in React usually outweighs the speed gain. If you are weighing it against a normal theme, our guide to scaling WooCommerce past 100,000 products and the WooCommerce performance checklist cover what you can fix without going headless.
Store API or REST API for a Next.js storefront?
Use the Store API for anything a shopper does, and the REST API v3 for anything a store manager does. They are different APIs with different security models, and mixing them up is the most common design mistake we see.
Store API | REST API v3 | |
|---|---|---|
Namespace |
|
|
Authentication | None. It is public and reflects the current customer | Consumer key and secret (Basic Auth over HTTPS) or OAuth 1.0a over HTTP |
Whose data you see | Only the current customer’s cart, checkout and order | Any customer, order or product the key’s user may access |
Writes | Cart and checkout for the current customer, with a Nonce or Cart-Token header | Full create, update and delete on store data |
Cart and checkout | Yes, this is its main job | No cart or checkout resource |
Safe in the browser | Yes, by design | No, the key must stay on the server |
Rate limiting | Optional, off by default | Not covered in the docs we checked |
The Store API documentation states it is “unauthenticated” and “does not provide access to sensitive store data or other customer information”, and that it cannot look up other customers or orders by ID. The REST API documentation describes keys that follow the permissions of the WordPress user they were created for. That is the whole reason the split exists: the Store API is safe to expose because it can only touch what the current shopper owns.
Practical split for a Next.js app: product pages, search, cart, coupons, shipping rates and checkout go through the Store API. Order history for a logged-in customer, inventory sync jobs and webhooks go through REST API v3 from a server action or a route handler, with the key stored in a server-only environment variable. If you are extending the REST API for an app, our guide on custom WooCommerce REST API endpoints for mobile apps covers that side, and the Store API developer guide goes deeper on the schema and ExtendSchema.
Which Store API endpoints does a storefront need?
The documented routes below cover a complete storefront. Every path sits under /wp-json/wc/store/v1; if you leave the version out, v1 is served, and v1 is the only version today.
Task | Method and path | Needs Nonce or Cart-Token |
|---|---|---|
List products | GET | No |
One product by ID or slug | GET | No |
Filter counts for a shop page | GET | No |
Read the cart | GET | No (this call returns the headers you need) |
Add a product | POST | Yes |
Change quantity | POST | Yes |
Remove a line | POST | Yes |
Apply or remove a coupon | POST | Yes |
Set the customer address | POST | Yes |
Choose a shipping rate | POST | Yes |
Read checkout data | GET | Yes |
Save fields before payment | PUT | Yes |
Place the order | POST | Yes |
Several cart calls in one | POST | Yes, on each cart sub-request |
Three details from the docs that save debugging time. First, list endpoints are paginated: page starts at 1, per_page defaults to 10 with a maximum of 100, and the totals come back in the X-WP-Total and X-WP-TotalPages headers. Second, prices are returned as strings in the smallest currency unit with a currency_minor_unit field, so "1105" with a minor unit of 2 is 11.05. Third, the products route accepts filters such as category, on_sale, min_price, max_price, stock_status and orderby (date, price, popularity, rating, title and others), which is enough for most shop pages without touching the REST API.
How do the Cart-Token and Nonce headers work?
A write request to a cart route, or any request to checkout, must carry either a Nonce header or a Cart-Token header. With a valid Cart-Token you do not need the Nonce. In a headless setup, use the Cart-Token: the nonce is tied to a WordPress session cookie that your Next.js front end does not have.
How you get them, per the Store API docs and the plugin source:
- Make a GET request to
/cart. Responses from cart routes carry aCart-Tokenheader, plusNonce,Nonce-Timestamp,User-IDandCart-Hash. Error responses caused by a cart session loading failure do not include Cart-Token or Cart-Hash. - Send the token back on every later request as a
Cart-Tokenrequest header. The response then shows the cart that belongs to that token. - The token is a signed token issued by
store-api. By default it expires after 48 hours, taken from thewc_session_expirationfilter in the source. After that, a fresh GET to the cart gives you a new one, and the old cart is gone. - If you use the Nonce instead, it is created with
wp_create_nonce( 'wc_store_api' ), sent in a header named exactlyNonce, and replaced by the fresh value returned in each response.
A request with neither header is rejected with a missing-nonce error (401). A bad nonce returns an invalid-nonce error (403). The exact error codes, from the route source on GitHub:
woocommerce_rest_missing_nonce 401
woocommerce_rest_invalid_nonce 403For local development only, WooCommerce documents a filter that turns the nonce check off. Never ship it:
add_filter( 'woocommerce_store_api_disable_nonce_check', '__return_true' ); // development onlyChecked against the docs on 15 November 2026.
How do I handle CORS between Next.js and WooCommerce?
The cleanest answer is to avoid browser CORS entirely: call WooCommerce from the Next.js server, and let the browser talk only to your own Next.js domain. The plugin source explains why that is the safer default.
Here is what the plugin source (Authentication.php, trunk, checked 15 November 2026) does, because it differs from the normal WordPress REST API:
- WooCommerce removes the default WordPress CORS handler for the Store API and sends its own, because some routes return personal data.
- The allowed request headers are the WordPress defaults plus
Cart-TokenandNonce. Any other custom header fails the preflight request. - Only
Cart-Tokenis exposed to browser JavaScript, notNonce. The code comment says only one of them is needed. - A response includes
Access-Control-Allow-Originfor your origin only if the request is a preflight, or carries a valid Cart-Token, or the origin passes WordPressallowed_http_origins. A valid Cart-Token is accepted from any origin.
So a browser app on another domain can work if it sends a Cart-Token, and you can add your storefront domain to the allowed list with the standard WordPress filter. This sets only the origin allow-list, and it belongs in a small must-use plugin on the WooCommerce site:
add_filter( 'allowed_http_origins', function ( array $origins ): array {
$origins[] = 'https://shop.example.com'; // your Next.js domain
return $origins;
} );The upstream project tracks multi-origin CORS support, cart-token session parity and checkout links as open work in its issue “Make Store API suitable to build headless stores” (opened December 2024, still open on 15 November 2026). That is a fair summary of the state of things: it works, but you are on the less-travelled path.
How should I set up the Next.js project?
Use the App Router, keep every Store API call on the server, and store the Cart-Token in an HTTP-only cookie that your own domain sets. The browser then never sees WooCommerce’s headers, CORS is a non-issue, and the token cannot be read by a script injected into a page.
Two Next.js facts that shape the code, from the current docs. cookies() is async (await cookies()), and you can only set a cookie from a Server Function or a Route Handler, never while a Server Component renders. And fetch responses are not cached unless you opt in, so a cart request is fresh by default, but we still pass cache: 'no-store' to make the intent obvious and to stay safe if the route is ever prerendered.
Environment variables first. Both stay on the server (no NEXT_PUBLIC_ prefix):
WC_STORE_URL=https://your-store.example.com
WC_REST_KEY=ck_xxx # only if you also call REST API v3
WC_REST_SECRET=cs_xxxA small helper that always sends the current Cart-Token, and fetches one if the visitor has none yet:
// lib/store-api.ts
import { cookies } from 'next/headers'
const BASE = `${process.env.WC_STORE_URL}/wp-json/wc/store/v1`
export const TOKEN_COOKIE = 'cart_token'
export async function storeFetch(path: string, init: RequestInit = {}) {
const jar = await cookies()
let token = jar.get(TOKEN_COOKIE)?.value
// The first cart write needs a token, and GET /cart is how you get one.
if (!token) {
const first = await fetch(`${BASE}/cart`, { cache: 'no-store' })
token = first.headers.get('Cart-Token') ?? undefined
}
const res = await fetch(`${BASE}${path}`, {
...init,
cache: 'no-store',
headers: {
'Content-Type': 'application/json',
...(token ? { 'Cart-Token': token } : {}),
...init.headers,
},
})
// Cart routes return a fresh Cart-Token header; hand it back to the caller.
return { res, token: res.headers.get('Cart-Token') ?? token }
}A Route Handler that adds a product and saves the token. This is the one place that is allowed to set the cookie:
// app/api/cart/add/route.ts
import { cookies } from 'next/headers'
import { NextResponse } from 'next/server'
import { storeFetch, TOKEN_COOKIE } from '@/lib/store-api'
export async function POST(request: Request) {
const { id, quantity = 1 } = await request.json()
const { res, token } = await storeFetch('/cart/add-item', {
method: 'POST',
body: JSON.stringify({ id, quantity }),
})
const cart = await res.json()
if (token) {
const jar = await cookies()
jar.set(TOKEN_COOKIE, token, {
httpOnly: true,
secure: true,
sameSite: 'lax',
path: '/',
maxAge: 60 * 60 * 24 * 2, // matches the 48-hour default token life
})
}
return NextResponse.json(cart, { status: res.status })
}Checked against the docs on 15 November 2026. One honest limit: storeFetch can read the cookie anywhere on the server, but only the Route Handler (or a Server Function) may write it.
Should I list products with the Store API or the REST API?
Use the Store API for the storefront’s product lists and product pages. It is public, needs no key, accepts shop-style filters and returns prices in a format ready for display. Use REST API v3 only when you need data the Store API does not expose, such as private meta or cost prices, and call it from the server.
A product listing as a Server Component, cached for five minutes and tagged so you can clear it on demand:
// app/shop/page.tsx
const BASE = `${process.env.WC_STORE_URL}/wp-json/wc/store/v1`
type Product = {
id: number
name: string
slug: string
prices: { price: string; currency_minor_unit: number; currency_prefix: string }
images: { src: string; alt: string }[]
}
export default async function Shop({
searchParams,
}: {
searchParams: Promise<{ page?: string }>
}) {
const { page = '1' } = await searchParams
const res = await fetch(
`${BASE}/products?per_page=12&page=${page}&orderby=popularity&order=desc`,
{ next: { revalidate: 300, tags: ['products'] } }
)
const products: Product[] = await res.json()
const totalPages = Number(res.headers.get('X-WP-TotalPages') ?? 1)
return (
<main>
<ul>
{products.map((p) => {
const price = Number(p.prices.price) / 10 ** p.prices.currency_minor_unit
return (
<li key={p.id}>
<a href={`/shop/${p.slug}`}>{p.name}</a>{' '}
{p.prices.currency_prefix}{price.toFixed(p.prices.currency_minor_unit)}
</li>
)
})}
</ul>
<p>Page {page} of {totalPages}</p>
</main>
)
}Notes on that code. searchParams is a promise in current Next.js, which is why it is awaited. The next.revalidate and next.tags options are documented on the fetch reference page. And the page count comes from X-WP-TotalPages, so you never download the whole catalog to count it. A single product page can use /products/:slug directly, which saves a lookup by ID.
Do not cache anything that depends on the shopper. A cached product list is shared by everyone, which is fine. A cached cart response would hand one visitor another visitor’s cart. Keep cart, checkout and anything with a Cart-Token on no-store.
How do I clear cached products when the catalog changes?
Call revalidateTag from a Route Handler that WooCommerce hits through a webhook when a product changes. In current Next.js the function takes two arguments, and the one-argument form is deprecated.
// app/api/revalidate/route.ts
import { revalidateTag } from 'next/cache'
export async function POST(request: Request) {
if (request.headers.get('x-revalidate-secret') !== process.env.REVALIDATE_SECRET) {
return Response.json({ ok: false }, { status: 401 })
}
// "max" serves stale content while fresh data loads in the background.
revalidateTag('products', 'max')
return Response.json({ ok: true })
}The Next.js docs say revalidateTag can be called from Server Functions and Route Handlers, not from Client Components or Proxy, and that "max" is the recommended profile. They also say a webhook-style call can pass { expire: 0 } if you need the data expired at once. Point a WooCommerce webhook, or a short must-use plugin on the product update hook, at this route with the shared secret in a header.
How does checkout work with the Store API?
Checkout is three calls: read it, save the fields, place the order. All three need the Cart-Token. The Store API turns the current cart into an order, collects the addresses and hands payment to the chosen gateway.
GET /checkoutreturns checkout data, including a draft order created from the cart (statuscheckout-draft). The payment fields are empty at this stage.PUT /checkoutsaves values before payment, such aspayment_method,order_notesand anyadditional_fields. The docs note the__experimental_calc_totalsquery parameter, which says whether cart totals should be recalculated after the update.POST /checkoutplaces the order. It requiresbilling_address,shipping_addressandpayment_method;payment_data,customer_note,customer_passwordandexpected_totalare optional.
expected_total deserves a line of its own. It is a string in the smallest currency unit, matching the cart’s total price. If you send it and the server’s total no longer matches, the order is rejected with a 409 and the refreshed cart comes back, so you can show the shopper the new total before they pay. Send it from your confirm step whenever you can.
// app/api/checkout/route.ts
import { NextResponse } from 'next/server'
import { storeFetch } from '@/lib/store-api'
export async function POST(request: Request) {
const body = await request.json() // billing_address, shipping_address, payment_method, expected_total...
const { res } = await storeFetch('/checkout', {
method: 'POST',
body: JSON.stringify(body),
})
const order = await res.json()
return NextResponse.json(order, { status: res.status })
}The response contains a payment_result object with payment_status, payment_details and redirect_url. For a gateway that sends the shopper to another site, you redirect the browser to redirect_url. For a card form, the gateway’s own JavaScript has to collect the card and pass the result in payment_data.
This is where headless stores most often stall, and we want to be direct about it: a payment gateway only works in a headless checkout if it supports the Store API (the same API the Checkout block uses). A gateway built only for the classic shortcode checkout may have no way to run. Check each gateway’s documentation for Checkout block or Store API support before you commit to headless. Our Checkout block migration guide shows how to tell which of your plugins already work with that API.
Checkout is also where abuse lands. The Store API’s rate limiting is off by default; the docs show an options filter for it (default 25 POST requests per 10 seconds when enabled), and a Features setting that limits POST /checkout to 3 requests per 60 seconds. Only POST requests are limited. Turn it on for a public headless store.
How do I handle login and authentication?
You have three real options, and the Store API itself only handles one of them. Pick by who the user is and what they need to see.
Situation | Option | Where it runs |
|---|---|---|
Guest shopper, cart and checkout | Cart-Token, no login | Next.js server, token in an HTTP-only cookie |
Admin or back-office jobs (stock sync, orders export) | REST API v3 key and secret | Server only, key in a server environment variable |
Customer account area (past orders, saved addresses) | Your own login flow plus server-side calls with a key, scoped to that customer’s ID | Server only, after you check the session |
Why not make the Store API do login? Its docs say it is unauthenticated and returns only the current customer’s data. It has no login endpoint. If you add a token plugin such as the JWT Authentication for WP REST API plugin, remember that guest and logged-in carts then behave differently, as the next section shows.
For the customer area, we recommend a boring pattern. Log the shopper in through your own auth layer (WordPress login via a server route, or a separate identity provider), keep the session in an HTTP-only cookie, and when the page needs order history, call REST API v3 from the server with the store key and filter by that customer’s ID. The key never reaches the browser, and the customer can only see what your server code chooses to return. Test that filter with two accounts; an unscoped call returns every order.
One rule that is not negotiable: never put a REST API consumer key or secret in a NEXT_PUBLIC_ variable or any client-side code. The REST API documentation describes keys that carry the permissions of a WordPress user. Anyone who reads the key from your JavaScript bundle can use it.
Common mistakes people report
These are recurring problems from the WooCommerce GitHub issues and developer write-ups, paraphrased, checked 15 November 2026.
- Calling a cart write before getting a token. A POST to
/cart/add-itemwith no Cart-Token and no Nonce returns a missing-nonce 401 error. The fix is a GET to/cartfirst and a reuse of the returnedCart-Tokenheader. See the Cart Tokens documentation. - Sending a header name the server does not allow. A developer building a Vue app on a separate domain reported a CORS preflight failure because the request carried an
X-WC-Store-API-Nonceheader; the issue was closed in 2022. In the current source the allowed custom headers areCart-TokenandNonce. See issue 29116 and Authentication.php. - Cannot read the Cart-Token in browser code. Only Cart-Token is exposed through CORS, and developers report it missing in client-side code when the origin is not allowed. One Next.js write-up from September 2024 fixed it by proxying the Store API through a server route, which is the approach in this guide. See the write-up.
- Guest and logged-in carts do not merge. A developer using Next.js, a JWT plugin and the Cart-Token and Nonce headers reported that the saved cart of a logged-in user is replaced rather than merged, and that merging only worked once the user was also logged in on the WordPress side. A WooCommerce maintainer replied that with cart tokens the logic has to live at the session handler level. The issue is still open. See issue 55653. Plan for guest-only carts, or test the merge flow before you promise it.
- Caching a response that belongs to one shopper. Next.js does not cache
fetchby default, butcache: 'force-cache'will cache any request, including ones with cookie or authorization headers, according to the docs. Never use it on cart, checkout or customer calls. - Using the old revalidation call.
revalidateTag('products')with one argument still appears in many tutorials. The current docs mark it deprecated; userevalidateTag('products', 'max'). - Forgetting the image host. A product image from your WooCommerce domain fails in
next/imageuntil the host is listed inimages.remotePatterns; the docs say an unmatched host responds with 400 Bad Request.
How do I show product images from WooCommerce in Next.js?
Tell Next.js which host serves the images. Without it, next/image refuses to optimise images from your store domain.
// next.config.js
module.exports = {
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 'your-store.example.com',
pathname: '/wp-content/uploads/**',
},
],
},
}Then render each image with explicit width and height (or fill with a sized parent) so the page does not shift while it loads. The Store API returns image URLs and alt text in each product’s images array. The pattern format is taken from the next/image documentation, checked 15 November 2026.
What does a headless storefront cost you that a theme does not?
Be honest with yourself about the trade before you start. These are the costs our team sees most often on headless WooCommerce projects, from our own experience rather than a published benchmark:
- Every front-end plugin needs a replacement. Wishlists, reviews, subscriptions UI, bundles and variation swatches all render through the theme today.
- You own SEO. Titles, canonical URLs, product schema, sitemaps and redirects move into Next.js and must match what the store had, or you lose rankings.
- Two deployments to keep alive. A WooCommerce update can change Store API behaviour, so pin a staging copy and run your cart-to-checkout test after every update. Our migration guide and the checkout-after-update habit it describes apply here too.
- Payment and tax plugins must support the Store API, as covered above.
When those costs are fine, the gains are real: static product pages from a CDN, a front end you can change without touching WordPress, and one API for web and mobile.
Headless WooCommerce with Next.js: frequently asked questions
Is there an official WooCommerce JavaScript SDK for the Store API?
No. The official JavaScript package is the REST API v3 client, @woocommerce/woocommerce-rest-api, and it needs a consumer key. For the Store API, use fetch.
Do I need a nonce if I use a Cart-Token?
No. The Store API documentation says that when you send a Cart-Token, a Nonce is not required.
How long does a Cart-Token last?
The source sets the expiry from the wc_session_expiration filter, which defaults to two days (48 hours). Store the token in a cookie with a matching lifetime and start a new cart when it expires.
Can I use the Store API from the browser instead of a server?
Yes, if the browser’s origin is allowed and you send a Cart-Token, because a valid Cart-Token is accepted from any origin. We still prefer server calls: the token stays in an HTTP-only cookie and you avoid CORS settings on the store.
Is the Store API rate limited?
Only if you turn it on. It is optional and off by default, and only POST requests count. A separate setting limits checkout to 3 requests per 60 seconds.
Should I use WPGraphQL instead?
It can be, if your team already works in GraphQL. We did not check WPGraphQL or its WooCommerce extension against current docs for this refresh, so we cannot say how complete its cart and checkout support is today. Compare it with the Store API in a staging project before you decide.
Where do I start if I want help building this?
Our team builds custom WooCommerce storefronts and checkout flows. If you want a second opinion on whether headless fits your store, send us your plugin list and traffic numbers and we will tell you honestly if a theme-based build would serve you better.
Sources we checked
All checked on 15 November 2026. Pages change; re-check them for your own WooCommerce and Next.js versions.
- WooCommerce developer docs: Store API (namespace, resources, pagination, status codes).
- Store API: Nonce tokens and Cart tokens.
- Store API: Checkout endpoint and Rate limiting.
- WooCommerce REST API v3 documentation (keys and authentication).
- WooCommerce source: Store API Authentication.php (CORS headers, allowed and exposed headers).
- Issue 53325: Make Store API suitable to build headless stores.
- Next.js: fetch, revalidateTag, cookies and Image.
- npm registry entry for @woocommerce/woocommerce-rest-api.
Plugins we build and run
We maintain these ourselves, which is why we can support them on your site.
- BuddyNextThe self-hosted community engine for WordPress
- BuddyXFree community theme, Pro when you outgrow it
- ReignPremium community theme. Add pieces, build anything
- JetonomyCommunity forum and Q&A for WordPress
- EventonomyEvents and RSVPs for WordPress communities
- LearnomyCourses and learning communities on WordPress
- ListoraDirectories and listings your members can browse
- SnipShareCode sharing built for developer communities
- WB Ad ManagerAd placements that turn traffic into revenue
- WP Career BoardA job board your community actually uses
- WP Sell ServicesSell services with offers, orders, and payouts
- MediaVersePhotos, video, and media albums for members
- WB GamificationPoints, badges, and rewards that keep members active
- Product RoadmapPublic roadmaps with voting your users trust



