You can personalise a headless Next.js or Astro site without buying a personalisation platform. A short request-time handler reads one signal, such as country, campaign or a cookie, rewrites the request to a pre-built page variant, and lets the CDN serve that variant from cache. Keep the variant set small and keep one canonical URL. Serve the default version to search engines and to visitors you do not recognise. Whether you should do it at all depends on your traffic and on whether your segments actually need different content.

TL;DR

  • Personalise at the edge by rewriting to pre-rendered variants, not by swapping content in the browser after the page loads.
  • Scope the middleware to a handful of routes with a matcher. Every request it touches gets an extra hop and an extra cost.
  • Store variants in the CMS as overrides of a few fields (headline, proof, call to action), not as duplicate pages.
  • Use one canonical URL per page and no user-agent sniffing. The default variant should be one you'd be happy for Google to index.
  • Skip personalisation if you can't measure a difference or your visitors don't have different needs. Buy a tool if marketers need to run many segments without engineers.

What personalisation means in this guide

The tools market sells website personalization as everything from product recommendations to AI-written pages. This guide is narrower. It covers marketing pages on a headless site, where you change a few elements above the fold based on what you know at request time. Logged-in apps and recommendation engines are out of scope.

Four signals are realistic without buying data:

  • Location. On Vercel, requests arrive with geolocation headers such as x-vercel-ip-country and x-vercel-ip-city (Vercel docs). When Vercel launched Edge Middleware, it said geolocation came pre-populated for all customers rather than needing a separate paid service (Vercel). Good uses include currency, a local phone number, the nearest office or the regulations that apply.
  • Referral source. UTM parameters and the referrer header tell you which campaign or site sent the visitor. Persist the first touch in a cookie so the second page view still knows.
  • Industry. This is the hardest one. Either the visitor tells you (they came from an industry campaign or browsed an industry page), or you buy reverse-IP enrichment. Enrichment is one of the places where a paid tool earns its fee.
  • Returning visitor. A first-party cookie, set when someone completes a key action or comes back in a later session. A returning visitor doesn't need your elevator pitch again. A case study or a route back to pricing usually serves them better.

Three ways to build it

There are three broad approaches. The right one depends on who edits the variants and how many variants you need, and also on how much first paint matters.

SaaS personalisation tool Edge middleware with CMS variants Client-side swaps
Where the decision happens Usually a script in the browser, sometimes an edge integration Request-time code before the cache JavaScript after the page loads
What the first paint shows Often the default, then the variant The variant The default, then the variant
Caching Depends on the integration Each variant cached as its own static page Page cached; swap runs per visitor
Effect on Core Web Vitals Risk of flicker and layout shift from script-based tools Minimal if the matcher is tight Flicker and layout shift if above the fold
SEO risk Low if the default is sensible Low with one canonical and no crawler detection Low; crawlers usually get the default
Who edits variants Marketers in the tool's interface Editors in Sanity or Payload; engineers add new segments Engineers, or editors if fields are in the CMS
Cost shape Recurring subscription Build cost, then small hosting cost per request Cheapest to build
Best when Many segments, enrichment and stats needed, no engineering capacity A few well-defined segments on key pages Small touches below the fold

A SaaS personalisation tool

A good tool gives marketers an audience builder, a visual editor and reports, plus sometimes company enrichment, all without a deploy. That can justify the fee if your marketing team runs lots of experiments and engineering time is scarce. There's a trade-off. You pay a recurring fee and, for many tools, add another script on every page.

Treat the statistics vendors publish with care. One personalisation vendor's blog says B2B brands personalising their web experiences see an average conversion increase of 80%, and that personalised web experiences can lead to a 19% increase in sales (Instapage). The same source says 85% of businesses claim to personalise while only 60% of consumers feel they get personalised experiences. These figures come from a company that sells personalisation. They aren't independent research. Even hosting providers hedge. Vercel's own architecture piece cites customer results, then says they are not a guarantee of seeing the same numbers elsewhere (Vercel).

Edge middleware with CMS variants

The rest of this guide uses this approach. Vercel describes Routing Middleware as running globally before the cache, which makes it a practical way to personalise statically generated content (Vercel docs). Before it returns a response, it can run custom logic, rewrite, redirect and add headers. It's available on all plans.

Vercel states the trade-off too. Personalisation decisions finish before paint, but every request pays for a network hop, including requests with nothing to personalise (Vercel). That's why scoping matters.

Client-side swaps

The cheapest version is a component that reads a cookie in the browser and swaps a headline. It works. But visitors see the default first. Vercel argues for server-side bucketing because it avoids heavy client-side libraries and the layout shift caused by checking experiment membership in the browser (Vercel). In the same post, an engineer at SumUp says edge experiments let them show the control or experiment version immediately instead of using third-party scripts, removing the likelihood of flickering and layout shifts. Client-side swaps still suit a "welcome back" line in the footer or a tweak further down the page.

Building it in Next.js

Next.js 16 renamed middleware to Proxy

If you're on Next.js 16 or later, the file lives at proxy.ts at the project root. Earlier versions use middleware.ts (Vercel docs). The Next.js docs say the middleware convention is deprecated and renamed to proxy, and that Proxy defaults to the Node.js runtime. The runtime config option isn't available in Proxy files, and setting it throws an error (Next.js docs). If you're mid-upgrade, our notes on moving a large site to Next.js 16 Cache Components cover the caching side.

The pattern: decide, rewrite, serve from cache

The shape is simple:

  1. Proxy reads the signals and picks a segment from a fixed allowlist.
  2. It rewrites /pricing to an internal path such as /v/uk/pricing. The visitor's URL doesn't change.
  3. Each variant path is pre-rendered at build time (or revalidated), so the CDN caches it like any static page.
  4. Every variant declares the public URL as its canonical.

Rewriting to a distinct path is the part that keeps this cacheable. If you pass the segment in a header and read it during a dynamic render, every request would still hit your server. Next.js lists headers, cookies, rewrites, redirects and the URL as the ways to pass information from Proxy to the app (Next.js docs). For static personalisation, use the rewrite.

// proxy.ts (project root, Next.js 16+)
import { NextResponse, type NextRequest } from 'next/server';

const SEGMENTS = new Set(['default', 'uk', 'healthcare', 'returning']);

function pickSegment(req: NextRequest) {
  const campaign = req.nextUrl.searchParams.get('utm_campaign') ?? '';
  if (campaign.startsWith('health')) return { segment: 'healthcare', persist: true };

const saved = req.cookies.get('seg')?.value;
  if (saved && SEGMENTS.has(saved)) return { segment: saved, persist: false };

const country = req.headers.get('x-vercel-ip-country');
  if (country === 'GB') return { segment: 'uk', persist: false };

  return { segment: 'default', persist: false };
}

export function proxy(req: NextRequest) {
  const { pathname } = req.nextUrl;

// Send direct hits on internal variant paths back to the public URL
  if (pathname.startsWith('/v/')) {
    const publicPath = '/' + pathname.split('/').slice(3).join('/');
    return NextResponse.redirect(new URL(publicPath, req.url));
  }

const { segment, persist } = pickSegment(req);
  const url = req.nextUrl.clone();
  url.pathname = `/v/${segment}${pathname === '/' ? '' : pathname}`;

const res = NextResponse.rewrite(url);
  if (persist) res.cookies.set('seg', segment, { path: '/', sameSite: 'lax' });
  return res;
}

export const config = {
  matcher: ['/', '/pricing', '/services/:path*', '/v/:path*'],
};

The variant page is an ordinary static route:

// app/v/[segment]/pricing/page.tsx
export function generateStaticParams() {
  return ['default', 'uk', 'healthcare', 'returning'].map((segment) => ({ segment }));
}

export const metadata = {
  alternates: { canonical: 'https://example.com/pricing' },
};

export default async function Pricing({ params }: { params: Promise<{ segment: string }> }) {
  const { segment } = await params;
  const page = await getPage('pricing', segment); // CMS fetch with default fallback
  return <PricingView page={page} />;
}

A few details that matter more than they look:

  • The matcher must be a constant. Matcher values are statically analysed at build time, and dynamic values such as variables are ignored (Next.js docs). Without a matcher, Proxy runs on every request, including _next/static, _next/image and everything in public/.
  • Allowlist segments. Never build a path from a raw cookie or query value. Map it to a known segment or fall back to default.
  • Don't put noindex in the variant template. The rewritten response is served on the public URL, so a noindex there would de-index your real page. Redirecting direct hits on /v/... (as above) is safer.
  • Check your cache key. Campaign parameters on the URL can fragment caching on some setups. Test how your host treats query strings on rewritten routes before launch.

When you don't need code at all

If the decision is only a plain lookup, such as whether a cookie exists or a header has a value, skip Proxy. Vercel's docs recommend static configuration when routing doesn't need custom code, because static rules run on the CDN without invoking your code, so they're faster and use fewer resources (Vercel docs). vercel.json supports has and missing conditions on headers, cookies, query parameters and host:

{
  "rewrites": [
    {
      "source": "/",
      "has": [{ "type": "cookie", "key": "seg", "value": "returning" }],
      "destination": "/v/returning"
    }
  ]
}

The same docs say to use middleware when the decision needs logic that static rules can't express, such as verifying a session token, calling an API or assigning visitors to an A/B test.

Building it in Astro

The pattern carries over. Pre-render each variant route with getStaticPaths, give every variant the same canonical, and keep the decision in front of the cache. Decide early. On Vercel, Routing Middleware runs ahead of the deployment, so an Astro site can rewrite to variant paths the same way. Netlify uses Edge Functions for the same job. If you're still choosing a framework, our Astro vs Next.js comparison covers the wider trade-offs. For most content-led marketing sites, either works well. We build on both, and the detail sits on our Next.js development and Astro development pages.

Modelling variants in Sanity or Payload

The CMS model matters. It decides whether editors keep using personalisation after launch, or whether the work becomes too awkward to maintain. The common mistake is copying whole pages per segment. That drifts quickly. After a few months, the variants fall out of step with the default, and nobody remembers which one is current.

A better model is a base page with optional overrides on specific blocks:

  • A segment list in one place. Keep a small segment document type (key, label, description of who it's for). Generate the Proxy allowlist and generateStaticParams from it at build time.
  • Overrides, not copies. On the hero, proof and call-to-action blocks, add an optional variants array. Each item has a segment reference plus the few fields that change.
  • Fallback by default. If a segment has no override, the default field renders. Editors only write what's different.

In Sanity, GROQ makes the fallback a one-liner:

*[_type == "page" && slug.current == $slug][0]{
  "headline": coalesce(hero.variants[segment->key == $segment][0].headline, hero.headline),
  "cta": coalesce(hero.variants[segment->key == $segment][0].cta, hero.cta)
}

In Payload, the same idea works as an array field inside the relevant blocks, with a relationship to a Segments collection. The shape stays local. Either way, set up preview so editors can pick a segment and see the variant before publishing.

Be strict about field types from day one. A practitioner write-up on migrating Sanity content describes author fields stored as a string in some posts, a reference in others and an array of references elsewhere, which took several normalisation passes (Ona). That drift is expensive. Variant fields can drift the same way if the schema is loose. Our Sanity Studio production notes go further on schema discipline.

Keeping it SEO-safe

Google defines cloaking plainly. It means showing different content to users and to search engines, with the intent to manipulate search rankings and mislead users (Google Search Central). The example is this: a page about travel destinations is served to search engines, while users get a page about discount drugs. Break the spam policies, and a site may rank lower or not appear in results at all.

Swapping a headline for UK visitors is nowhere near that. Still, the rules below keep you clearly on the right side:

  • Never branch on user agent or crawler IP ranges. Google's description of hacked sites notes that malicious redirects sometimes depend on the referrer, user agent or device. Don't build anything that looks like that pattern.
  • Same subject, same substance. Variants change emphasis, proof and calls to action. The page stays about the same thing for everyone.
  • The default is for anyone without a signal. Googlebot doesn't carry your cookies or campaign parameters, so for referrer, industry and returning-visitor segments it sees the default. For location, it gets whichever variant its IP maps to. That's one more reason to keep geo variants to small details.
  • One canonical per page. Every variant points to the public URL.
  • Rewrite, don't redirect by location. Bouncing visitors to different URLs by country is confusing for people and crawlers alike.
  • Give real regional differences real pages. Google lists pages targeted at specific regions or cities that funnel users to one page as a doorway abuse example. If a city or language genuinely needs different content, build an indexable page with something useful on it, plus hreflang where relevant. Our international SEO work covers this.

That last point is often the better answer. On the SleepDr migration, we built five languages and 20 city pages. For bdManagedIT, we added service pages, industry pages, location pages and compliance pages. None of that is personalisation. They are separate, indexable pages that searchers can land on directly, without passing through one audience page first. If you only have one page per audience, start there.

Google's paywall guidance makes the same point. It isn't cloaking if Google can see the full content just like any person with access, and you follow its Flexible Sampling guidance. Put simply, Google should see what a real visitor in the same position would see.

Performance and cost

Personalisation that slows the page down cancels itself out. A few rules:

  • Tight matchers. Only the routes you personalise, plus /v/:path* for the redirect.
  • No data fetching in Proxy. Vercel's guidance is that edge compute belongs on proximity-sensitive work like routing, auth and personalisation, while data-heavy queries belong in a region near your database (Vercel). Pick the segment from headers and cookies, and let the pre-rendered page carry the CMS content.
  • Small cookies. A short segment key is enough. Don't store profiles in cookies.
  • Prefer static rules where has and missing conditions do the job.

Vercel cites a claim, attributed to Deloitte, that every 100ms shaved off load time is tied to an 8% conversion lift (Vercel). Treat that figure carefully. It's a hosting company quoting a consultancy, so don't rely on that figure. The direction is sound, though: a personalised page that renders late may do worse than a generic one that renders fast. Our Core Web Vitals guide covers the measurement side, and our Core Web Vitals optimisation work is how we fix it.

What to measure

Personalisation that isn't measured becomes a backlog of variants nobody wants to delete. Decide before launch how you'll judge success:

  • Conversion per segment against a holdout. Keep part of each segment on the default page and compare like with like. Before-and-after comparisons get muddied by seasonality and campaign changes.
  • Assignment counts. How many visitors actually land in each segment. If a segment is tiny, it can't show a result. Fold it back into the default.
  • Flag evaluations. If you run variants through Vercel Flags, you can run A/B tests on conversion and performance, track flag evaluations in Runtime Logs and analyse the impact in Web Analytics (Vercel docs).
  • Core Web Vitals per variant. A heavier hero image on one variant shows up here first.
  • Cache hit rate and middleware invocations on personalised routes, plus the line on your hosting bill.
  • Search health. In Search Console, check that the canonical is indexed and that URL inspection shows the default content.
  • Editorial load. How often variants go stale. If editors stop maintaining them, the segments are too many or too fine.

If conversion is the real problem, start with our conversion rate optimisation page. Personalisation creates more versions of a page that already works. It rarely fixes one that doesn't.

When a SaaS tool is the better buy

Building it yourself isn't always right. Pay for a tool when:

  • Marketers need to create and retire segments weekly without a deploy.
  • You need company-level enrichment (industry, size, named accounts) that you can't get from your own data.
  • You want a built-in statistics engine and reporting, and nobody on your team owns analytics.
  • You run many sites or brands and want one interface across them.
  • Engineering time is the bottleneck, and the subscription costs less than the backlog.

If you choose that route, prefer an integration that makes the decision at the edge or on the server. Then check what a visitor sees on first paint. Our build-versus-buy framework applies here too.

When personalisation isn't worth it

Often the honest answer is not yet:

  • Low traffic. If each segment can't produce enough conversions to compare against a holdout in a reasonable time, you'll never know whether it worked.
  • No segments with different needs. If a UK visitor and a US visitor want the same thing from the page, a country switch adds complexity and nothing else.
  • The default page is weak. Fix the generic message, proof and call to action first.
  • One page per audience would do. Dedicated industry, service or city pages rank, can be shared and need no runtime logic. For many B2B websites, that's the bigger win.
  • Nobody will maintain it. Variants need an owner. Without one, they go stale.

How we'd approach it

This is an implementation guide, not a case study. We build on Next.js and Astro with Sanity or Payload, deployed on Vercel or Netlify, and this edge-rewrite pattern fits that stack. We'd start with a scoped audit. It would cover which pages matter and which segments are real, plus whether you have the traffic to measure them. Pricing is a fixed fee, agreed after that audit and paid in milestones. When we hand over, you own the repository, hosting, CMS and data. If you want to talk it through, get in touch.

FAQ

Is website personalisation the same as cloaking?

No. Google defines cloaking as showing users and search engines different content with the intent to manipulate rankings and mislead users. A changed headline, proof point or call to action for a segment isn't cloaking, provided the page keeps the same topic and substance. Don't detect crawlers. Keep one canonical and serve a sensible default.

The risk comes from routing by user agent or crawler IP ranges, or from variants that change what the page is actually about. Keep variants to emphasis changes. That keeps you clear of the policy.

Do I need a SaaS tool to personalise a Next.js site?

Not for a few well-defined segments. Next.js Proxy (or Vercel Routing Middleware) can read geolocation headers and cookies, then rewrite to pre-rendered variant pages and let the CDN cache each one. The variant content sits in Sanity or Payload. A paid tool earns its fee when marketers need many segments, enrichment and reporting without engineers.

Building costs engineering time up front, plus a small hosting cost per request. A tool is a recurring subscription. Often it adds another script to the page too.

Will edge personalisation slow my site down?

Middleware adds a network hop to every request it runs on, so scope it with a matcher to the routes you personalise. Keep data fetching out of the middleware. Serve pre-rendered variants from cache. With that setup, visitors get the right variant on first paint, with no flicker or layout shift.

Next.js Proxy runs on every request without a matcher. That includes static files and image optimisation. If the decision is a plain cookie or header check, Vercel's static rewrite rules avoid invoking code at all.

What does Googlebot see on a personalised page?

Googlebot sees the default variant for segments based on cookies, campaign parameters or returning visits, because it doesn't carry those signals. For location-based variants, it sees whichever version its IP address maps to. That's why geo variants should change small details only. Real regional differences deserve their own pages.

Check this with URL inspection in Search Console. The rendered HTML should show the default content, with the canonical pointing at the public URL.

How much traffic do I need before personalisation is worth it?

There's no universal threshold. Each segment needs enough conversions to compare against a holdout group on the default page within a sensible period. A segment too small to show a difference goes back into the default. Then improve the generic page, or build dedicated pages instead.

Start small. Pick one or two segments on your highest-traffic pages and measure them, then add more only when the first ones show their worth.

Can I do this on Astro or on Netlify?

Yes. The pattern is framework-neutral. Pre-render the variant routes and give them all the same canonical. Decide which one to serve before the cache. On Vercel, Routing Middleware sits in front of an Astro deployment the same way it does for Next.js. Edge Functions do the same job on Netlify.

Use getStaticPaths in Astro to build each variant. The CMS modelling advice doesn't change. It's a base page with per-block overrides and a single segment list.

Should location pages be personalised or built as separate pages?

If a city or region needs genuinely different content, build a separate, indexable page with something useful on it. Personalisation suits small details such as phone numbers and currency, or the nearest office. Avoid thin regional pages that funnel to one page. Google cites that as a doorway abuse example.

Separate pages can rank for local searches. A personalised variant behind one URL never will. Use hreflang where languages differ.