Article

Decouple a CMS layer without losing performance or routing

Move editorial content behind your own content API, keep routes, SEO and a rollback path, and compare performance with k6 in a fair way.

Published Updated 10 min read

This guide shows how to separate editorial content from application and commerce data in a headless Next.js stack. You move one route at a time, and you keep URLs, SEO and a rollback path intact. It also shows how to compare performance with a k6 load test in a fair way, because the first comparison is often a comparison of caches, not of code. It is written for tech leads and architects who want to take a composition layer or headless CMS out of the critical path of a storefront. The examples use the Next.js Pages Router. Next.js 16.4.6 and k6 2.4.0 are the current versions on 1 December 2026.

Draw the boundary before you move anything

A composition layer often starts as a place for editors. Over time it also holds data that the application needs to work. Before you move code, sort every data type into editorial or structural.

Data Typical owner Source after decoupling
Page copy, legal pages, FAQ Content team CMS, through your content API
Products, prices, stock Commerce platform Product or catalog API
Cart, checkout, account Application teams Commerce and identity APIs
Navigation and footer Content and product Content API, cached at the edge
URLs, redirects, breadcrumbs Shared One routing source, chosen on purpose
SEO metadata and UI labels Content and SEO Decide this explicitly

Then list the jobs that the composition layer does without anyone noticing. Uniform is a good example. Its project map is a hierarchical tree that you use for URL management, for navigation and menus, and to generate sitemap.xml. Its Route API resolves static paths, dynamic paths and redirects in one endpoint, and a redirect match overrides a project map match. Data types cache external data by default with a 30-second TTL. When you remove such a layer, every one of these jobs needs a new owner.

Do not forget preview. In the Pages Router, Draft Mode lets an API route call res.setDraftMode({ enable: true }). This sets the __prerender_bypass cookie, and pages then render at request time. Your new content API needs a way to return draft content for that request.

Put a versioned content API in front of the CMS

Do not let every page call the CMS SDK. Put a versioned API that you own between the front end and the CMS. Each endpoint returns a view model in the shape that the page needs, not the raw CMS response. Protect the API with a key and cache the responses at the edge.

This gives you one place to absorb change. When a back end changes, ask one question first: is the new version only a different endpoint, or also a different response shape? A new endpoint is a change in the mapping layer only. A new response shape can also need a new version of the view model.

Start with mocked responses in the shape of the view model. Then the front-end work and the API work can run in parallel.

// lib/content-api.ts
export type LegalPage = {
  slug: string;
  title: string;
  body: string;
  seo: { title: string; description: string; canonicalPath: string };
};

export async function getLegalPage(
  slug: string,
  locale: string,
  draft = false,
): Promise<LegalPage | null> {
  const url = new URL(`/v1/legal-pages/${slug}`, process.env.CONTENT_API_URL);
  url.searchParams.set('locale', locale);
  if (draft) url.searchParams.set('draft', 'true');

  const res = await fetch(url, {
    headers: { authorization: `Bearer ${process.env.CONTENT_API_KEY}` },
  });
  if (res.status === 404) return null;
  if (!res.ok) throw new Error(`Content API returned ${res.status} for ${slug}`);
  return res.json();
}

Keep routing in one place

Routing is usually the expensive part of a decoupling, not the data. A URL that is live is a contract with users and search engines. The Uniform routing guide says the same: once a URL is published, it acts as a contract.

Make an inventory before you move a route:

  • Every path that the composition layer resolves, per locale.
  • Every redirect, and where it is managed.
  • Every place that builds breadcrumbs, menus or the sitemap from the same tree.

Then move one route at a time. In Next.js, the router checks non-dynamic pages before dynamic routes. So a new explicit page, such as pages/terms-and-conditions.tsx, wins over a catch-all route such as pages/[[...slug]].tsx. The catch-all keeps serving every page that you did not move yet. If a page has a different slug per locale, cover every slug, or keep that locale on the catch-all until you move it.

Keep redirects in their current source until you move all of them. A redirect in the old layer can still point to a path that you just moved, so test both.

Put the data source behind a feature flag, so you can switch back without a code change:

// pages/terms-and-conditions.tsx
import type { GetStaticProps } from 'next';
import { getLegalPage, type LegalPage } from '../lib/content-api';
import { getLegacyLegalPage } from '../lib/legacy-cms';
import { isFlagEnabled } from '../lib/flags';

type Props = { page: LegalPage };

export const getStaticProps: GetStaticProps<Props> = async ({
  locale = 'en',
  draftMode = false,
}) => {
  const fromContentApi = await isFlagEnabled('legal-pages-from-content-api');
  const page = fromContentApi
    ? await getLegalPage('terms-and-conditions', locale, draftMode)
    : await getLegacyLegalPage('terms-and-conditions', locale);

  if (!page) return { notFound: true, revalidate: 60 };
  return { props: { page }, revalidate: 300 };
};

With revalidate, Next.js serves the cached page and regenerates it in the background after the interval. If the regeneration fails, Next.js keeps serving the last page that it generated successfully. ISR runs on the Node.js runtime only, and it does not work with a static export.

Keep SEO the same, then improve it

Search engines see a migration even when users do not. For every route that you move, the new version must return the same:

  • Status code and final URL, including redirects.
  • <title> and meta description.
  • Canonical URL and hreflang alternates.
  • Robots meta tag.
  • Entry in the sitemap.

Decide who owns SEO metadata and UI labels after the decoupling. If nobody owns them, they stay in the old layer and block its removal.

A small script compares two environments before every switch. It compares paths, not hosts, because the hosts always differ. It is not a crawler, so adjust the patterns to your markup.

// seo-parity.mjs
// Usage: node seo-parity.mjs https://<old-host> https://<new-host> /terms-and-conditions
const [, , baseA, baseB, ...paths] = process.argv;

const pick = (html, re) => html.match(re)?.[1] ?? null;
const pathOf = (url) => (url ? new URL(url, 'https://example.com').pathname : null);

async function snapshot(base, path) {
  const res = await fetch(new URL(path, base), { redirect: 'manual' });
  const html = res.status === 200 ? await res.text() : '';
  return {
    status: res.status,
    location: pathOf(res.headers.get('location')),
    title: pick(html, /<title[^>]*>([^<]*)<\/title>/i),
    description: pick(html, /<meta[^>]+name="description"[^>]+content="([^"]*)"/i),
    canonical: pathOf(pick(html, /<link[^>]+rel="canonical"[^>]+href="([^"]*)"/i)),
    robots: pick(html, /<meta[^>]+name="robots"[^>]+content="([^"]*)"/i),
    hreflang: [...html.matchAll(/hreflang="([^"]+)"/gi)].map((m) => m[1]).sort().join(','),
  };
}

let differences = 0;
for (const path of paths) {
  const [a, b] = await Promise.all([snapshot(baseA, path), snapshot(baseB, path)]);
  for (const key of Object.keys(a)) {
    if (a[key] !== b[key]) {
      differences++;
      console.log(`${path} ${key}: "${a[key]}" vs "${b[key]}"`);
    }
  }
}
process.exit(differences ? 1 : 0);

Plan each phase with entry, exit and rollback

Write each phase down before you start it. A phase is done when its exit criteria are met, not when the code is merged.

Phase Entry Work Exit Rollback
Prove Content API endpoint with mocked data Move one static page Parity script passes, k6 results compared fairly Flag off
Move pages Proof accepted Move pages per type, behind the flag Editors publish through the new path Flag off, revalidate paths
Move shared data Owners for navigation, SEO metadata and labels Move shared data to the content API No page reads shared data from the old layer Old endpoint stays available
Move routing Full route and redirect inventory Move routes and redirects to one source Sitemap and redirects match the inventory Catch-all stays in place
End state All of the above Remove the layer, keep it as catch-all only, or keep it for authoring behind the content API Decision recorded Depends on the choice

A rollback is two steps. First, switch the flag off. Then call res.revalidate('/terms-and-conditions') from an API route, so the page regenerates now and not after the interval. Proxy does not run for on-demand ISR, so revalidate the exact path that the page uses.

If you self-host more than one instance, check where the ISR cache lives. The Next.js App Router ISR guide notes that the default file system cache is per instance, so an on-demand revalidation only reaches the instance that receives the call. A shared cache handler fixes this.

Compare performance fairly with k6

Two environments rarely differ in one thing only. They can differ in rendering mode, cache state, instance size, data volume and network distance. If you compare them, you measure all of those at once. Keep everything equal except the one thing that you want to learn about:

  • The same page, with the same content size.
  • The same rendering and cache mode on both sides.
  • The same load profile and the same test duration.
  • The same location of the load generator.
  • The same instance size and number of instances.

Caching can dominate the result. A cached ISR response skips rendering and data fetching. A dynamic page with getServerSideProps runs at request time and calls its data sources on every request. The Next.js docs advise getStaticProps when a page does not need request-time data. So if one side is cached and the other is not, the difference is mostly the cache.

Pick the k6 metrics before the test:

Question k6 metric Note
Time to first byte http_req_waiting Time spent waiting for the first byte
Response time http_req_duration at p(95) Sending, waiting and receiving, without DNS and connect
Throughput http_reqs per second A counter, the summary shows the rate
Errors http_req_failed A rate of failed requests
Load not sent dropped_iterations Iterations that did not start because no VU was free

Pick the load model on purpose. The constant-vus executor is a closed model: a VU sends its next request only after the previous one ends. So a faster system also gets more requests, and throughput follows response time. k6 calls this coordinated omission. The constant-arrival-rate executor is an open model: it starts iterations at a fixed rate, whatever the response time. Use it to compare latency at the same load. Do not add sleep at the end of the iteration, because the executor already controls the pace.

// compare.js
import http from 'k6/http';
import { check } from 'k6';

const BASE_URL = __ENV.BASE_URL;
const PAGE_PATH = __ENV.PAGE_PATH || '/terms-and-conditions';

export const options = {
  scenarios: {
    same_load: {
      executor: 'constant-arrival-rate',
      rate: 100,
      timeUnit: '1s',
      duration: '2m',
      preAllocatedVUs: 20,
      maxVUs: 100,
    },
  },
  tags: { setup: __ENV.SETUP || 'unknown' },
  thresholds: {
    http_req_failed: ['rate<0.01'],
    http_req_duration: ['p(95)<200'],
  },
};

function header(res, name) {
  const key = Object.keys(res.headers).find((k) => k.toLowerCase() === name);
  return key ? res.headers[key] : '';
}

export default function () {
  const res = http.get(`${BASE_URL}${PAGE_PATH}`);
  check(res, {
    'status is 200': (r) => r.status === 200,
    'served from Next.js cache': (r) => /HIT|STALE/.test(header(r, 'x-nextjs-cache')),
  });
}

The second check shows how many responses came from the Next.js cache. On a Pages Router page with getStaticProps, the x-nextjs-cache header is MISS at most once, on the first visit, and then STALE or HIT. So request the page once on every instance before the measured run. When you test through a CDN, also check the CDN cache header, because the CDN can answer before Next.js runs.

Run the same script against both setups:

k6 run --summary-mode=full -e BASE_URL=https://<old-host> -e SETUP=before compare.js
k6 run --summary-mode=full -e BASE_URL=https://<new-host> -e SETUP=after compare.js

In k6 2.x the default summary mode is compact, which does not show http_req_waiting. The full mode does. The -e flag sets variables for __ENV, not k6 options. Use names such as BASE_URL, not PATH, because --include-system-env-vars can also fill __ENV. If a threshold fails, k6 exits with a non-zero code, so you can run the comparison in CI.

Test the origin to compare code. Test through the CDN to see what users get. Both are useful, but do not mix them in one comparison.

In practice

We support an international cosmetics retailer with its headless Next.js storefront, described in the case study. In September 2026, we took over the work to decouple content from the composition layer, and it is still in progress.

Navigation was the precedent. Navigation data already came from a versioned endpoint of the client’s own content API, protected with an API key and cached at the edge. That is the pattern that we want for other content. Routing is still open, because routes and breadcrumbs depend on the composition layer and a separate URL service. As this post describes, that is the expensive part, not the data.

A proof of concept for static pages moved a terms and conditions page. We ran k6 with 10 virtual users for 2 minutes against two setups. The pull-request preview environment served the page with ISR. The test environment rendered it dynamically.

Metric Preview environment (ISR) Test environment (dynamic)
TTFB 7 ms 41 ms
p95 15 ms 51 ms
Throughput 363/s 169/s
Errors 0% 0%

The cause of the difference is caching, not the code. The test also used one small static page and a fixed number of virtual users, which is a closed model, so the higher throughput follows from the lower response time. We do not read these numbers as a gain from the decoupling itself. The next step is to measure k6 results and render parity per candidate page, and to note for each page where the boundary between structural and editorial data lies. Each phase gets a migration path with entry, work, exit and rollback, as described above.

Checklist

  • List every job of the composition layer: routes, redirects, navigation, sitemap, preview and caching.
  • Put a versioned content API with view models in front of the CMS.
  • Move one route at a time, with an explicit page that wins over the catch-all.
  • Keep URLs, status codes and redirects the same for every route.
  • Run an SEO parity check on title, description, canonical, hreflang and robots.
  • Name an owner for SEO metadata and UI labels.
  • Write entry, exit and rollback criteria for each phase.
  • Compare k6 runs with the same page, cache mode, load model and location.
  • Report TTFB, p95, throughput, errors and dropped iterations together.

For help with a decoupling plan or a fair load test, see custom project.

Sources

Let's connect

Talk about your project

Tell us about your team and your problem. In 30 minutes we find out whether one of our offers fits, and if none does, we tell you.

Book a 30-minute call