Multiple Site Themes in Next.js with Middleware
How I serve four complete site designs from one Next.js app with a cookie, a middleware rewrite and static routes. Real code, SEO canonicals and pitfalls.
My portfolio has four completely different designs, and every visitor picks one. Kathmandu is red brick and temple roofs. Tempo Dash is a small driving game. Ledger looks like an accountant's ruled book. Terminal is keyboard-driven with CRT effects. They share content and nothing else: different layouts, fonts, components and interactions.
The whole switch runs on one cookie, one middleware.ts and a handful of static routes. No theme provider, no flash of the wrong design, and every page is still pre-rendered at build time.
Most guides on Next.js themes are about colours. Libraries like next-themes swap CSS variables for light, dark or a few named palettes, which is perfect when the layout stays the same. Guides on middleware rewrites, on the other hand, are almost always about A/B testing, where the server assigns the variant and the visitor never knows. This article covers the case in between: the visitor chooses between whole designs, and the choice has to survive page loads, share links, deep pages like the blog, and Google. You can try it right now with the Edition button in the bottom corner of this page.
When you need routes instead of CSS variables
If your themes only change colours, fonts and spacing, stop here and use CSS custom properties. One component tree with a data-theme attribute is simpler than anything below.
I went with separate routes because each edition is its own component tree:
- The Kathmandu home page is a house you scroll down, floor by floor, with scroll-driven animations.
- Tempo Dash is a canvas game where each bus stop unlocks a part of the portfolio.
- Ledger has a drawing layer so you can scribble on the page.
- Terminal has a command palette and a boot sequence.
Putting all four behind conditionals in one page would ship every edition's JavaScript to every visitor. Separate routes mean each visitor downloads only the design they chose, and each route can be fully static.
The setup at a glance
The idea fits in four lines:
- Each design is a normal route:
/kathmandu,/tempo,/ledger,/terminal. - The visitor's choice lives in a cookie called
pf_style. - Middleware reads the cookie on
/and rewrites to the chosen route, so the address bar still says/. - Every edition route tells search engines that
/is the real page.
One list of editions
Everything starts from a single list, so the switcher menu, the middleware and the first-visit chooser can never disagree:
// lib/styles.ts
export const STYLE_COOKIE = "pf_style";
export const STYLE_COOKIE_MAX_AGE = 60 * 60 * 24 * 365; // one year
export const STYLES = [
{ id: "kathmandu", name: "Kathmandu" },
{ id: "tempo", name: "Tempo Dash" },
{ id: "ledger", name: "Ledger" },
{ id: "terminal", name: "Terminal" },
] as const;
export type StyleId = (typeof STYLES)[number]["id"];
export const DEFAULT_STYLE: StyleId = "kathmandu";
export function isStyle(v: unknown): v is StyleId {
return STYLES.some((s) => s.id === v);
}
export function styleHref(id: StyleId, path = "/"): string {
return `${path}?style=${id}`;
}
isStyle matters more than it looks. The cookie and the query string both come from the browser, so the middleware never trusts them until they pass this check.
The default edition lives at "/"
The root page does not decide anything. It simply re-exports the default edition:
// app/(site)/page.tsx
export { default } from "./kathmandu/page";
That means a visitor with no cookie, and every search engine crawler, gets a complete, static Kathmandu page at / without middleware doing any work.
The middleware
Here is the core of middleware.ts, trimmed to the home page:
// middleware.ts
import { NextResponse, type NextRequest } from "next/server";
import { DEFAULT_STYLE, STYLE_COOKIE, STYLE_COOKIE_MAX_AGE, isStyle } from "@/lib/styles";
const COOKIE_OPTS = { path: "/", maxAge: STYLE_COOKIE_MAX_AGE, sameSite: "lax" } as const;
export function middleware(req: NextRequest) {
const requested = req.nextUrl.searchParams.get("style");
const pref = req.cookies.get(STYLE_COOKIE)?.value;
// "/?style=tempo": remember the choice, then send the visitor back to "/"
if (requested !== null) {
const url = req.nextUrl.clone();
url.searchParams.delete("style");
if (!isStyle(requested)) return NextResponse.redirect(url);
const res = NextResponse.redirect(url);
res.cookies.set(STYLE_COOKIE, requested, COOKIE_OPTS);
return res;
}
// "/" with a saved choice: show that edition, keep the URL as "/"
if (isStyle(pref) && pref !== DEFAULT_STYLE) {
return NextResponse.rewrite(new URL(`/${pref}`, req.url));
}
return NextResponse.next();
}
export const config = { matcher: ["/"] };
Three decisions in there are worth explaining.
Switching is a plain link. The edition menu is a <details> element full of ordinary links to /?style=tempo and friends. Clicking one sets the cookie and redirects back to /, where the rewrite takes over. The switcher needs no client-side JavaScript, and it works even before React has loaded.
Rewrite for viewing, redirect for choosing. A rewrite serves /tempo while the browser still shows /, which keeps one clean URL for the home page. Choosing goes through a redirect so the ?style= parameter disappears from the address bar and does not get bookmarked or shared by accident.
The matcher is narrow. Middleware runs only on the paths listed in matcher. Everything else (images, scripts, other pages) never touches it, so the cost stays close to zero.
Share links that don't change your setting
A share link should show a specific edition without overwriting the reader's own choice. So there is a second parameter: /?edition=ledger rewrites to Ledger for that one request, keeps the URL intact so it can be copied again, and leaves the cookie alone.
const shared = req.nextUrl.searchParams.get("edition");
if (shared !== null && isStyle(shared)) {
if (shared === DEFAULT_STYLE) return NextResponse.next();
const url = req.nextUrl.clone();
url.pathname = `/${shared}`;
return NextResponse.rewrite(url);
}
?style= means "remember this". ?edition= means "show me this once". If both did the same thing, every shared link would quietly change the reader's saved design.
One edition that is never remembered
Terminal is the odd one out. It is a developer toy, and I did not want someone who peeked at it once to land in a terminal every time they came back. Choosing Terminal redirects to /terminal without saving it as the home page preference, so / and the browser's Back button always return to the last regular edition.
Keeping search engines happy
Four URLs with the same content is a textbook duplicate content problem. The fix is a canonical tag on every edition route that points at /. I set it once in the layout that all the editions share, so each edition route inherits it:
// app/(site)/layout.tsx
export const metadata = {
alternates: { canonical: "/" },
// title, description, Open Graph...
};
Then I left the edition routes out of sitemap.xml on purpose. Google indexes one home page, and that page is what a crawler without cookies sees anyway: the full default edition, server-rendered.
The first-visit chooser (the overlay that asks new visitors to pick a design) follows the same rule. It is a client component that only opens when there is no cookie, and it never opens for crawlers, link previews or audit tools, because an interstitial covering the content is exactly what search engines dislike.
Making deeper pages follow the theme
The home page was the easy part. Then I built the blog and realised every post opened in the Terminal design, whatever edition you were browsing.
The fix extends the same pattern one level down:
/blogs/[slug]renders the default edition and is the canonical URL./tempo/blogs/[slug],/ledger/blogs/[slug]and/terminal/blogs/[slug]are copies in each design, all generated at build time withgenerateStaticParams.- Middleware now also matches
/blogsand/blogs/:slug, and rewrites to the visitor's edition.
export const config = { matcher: ["/", "/blogs", "/blogs/:slug"] };
Inside the site, each edition links straight to its own copy, so you stay in the design you are reading even if you arrived through a share link. Every copy declares /blogs/<slug> as canonical, so search engines still see one article. The edition switcher on a post links to /blogs/<slug>?style=ledger, which saves the choice and lands you back on the same post in the new design.
I keep all of this in one helper file so the four editions cannot drift apart: post URLs, canonical metadata and the structured data for each article come from shared functions.
Pitfalls I hit
A decoration pushed the whole page sideways
On phones, two editions could scroll horizontally, and the fixed Edition button slid partly off screen. The culprit was decoration: a pigeon animation that finished just past the right edge of the screen, and a rotated rubber stamp that overhung its card. On mobile Chrome, anything poking past the edge widens the layout viewport, so the whole page and every fixed element moved with it.
The fix was overflow-x: clip on each edition's wrapper. I used clip instead of hidden because hidden creates a scroll container, which breaks position: sticky for anything inside it. I tracked this one down on a real phone over USB with Chrome's remote DevTools, by listing every element whose right edge sat past the viewport. When an animation ends off screen, it stays there after it fades out.
A hashed image URL broke social previews on the copies
Each post has a generated social image. With the opengraph-image.tsx file convention, Next.js served it at a URL with a hash on the end, and only the canonical route linked to it automatically. The edition copies pointed at a plain URL that returned a 404. I moved the image to a route handler at /blogs/[slug]/og.png, which gives every copy one stable address.
Remember that rewrites hide the real route
When something renders wrong, check which route actually served it. The address bar says /blogs/my-post whatever the rewrite did. I tag each edition's wrapper with a data-edition attribute, and testing with curl -H "Cookie: pf_style=tempo" plus a grep for that attribute confirms which design came back for each cookie value.
Next.js 16 renames middleware
If you are on Next.js 16 or later, the file convention is proxy.ts instead of middleware.ts, and the Next.js upgrade guide covers the change. The logic in this article carries over unchanged; this site runs Next.js 15, so the examples use middleware.ts.
Frequently asked questions
Can I use next-themes for completely different layouts?
You can, but it is not what it is built for. next-themes sets a class or attribute so CSS can change, and every theme still ships the same component tree. For different layouts and interactions, separate routes plus a middleware rewrite keep each design's code out of the others' bundles.
Does a middleware rewrite hurt SEO?
Not if each variant declares a canonical URL. Crawlers do not send your theme cookie, so they get the default page at the canonical address. Add alternates.canonical to every variant route and leave the variants out of your sitemap.
Why use a cookie instead of localStorage?
The server never sees localStorage. With a cookie, middleware can pick the right design before any HTML is sent, so there is no flash of the default theme while JavaScript loads.
Do the pages stay static with this setup?
Yes. The middleware only chooses which pre-rendered route to serve. Every edition and every blog copy on this site is built at build time; nothing reads cookies inside a page component, which is what would force dynamic rendering.
How do I let people share a link to one specific theme?
Use a separate query parameter that rewrites for a single request and never writes the cookie. On this site /?edition=ledger shows Ledger once and leaves the visitor's own choice untouched.
Wrapping up
The pattern is small: a list of themes, a cookie, a rewrite, and a canonical tag on every variant. What made it work in practice was the part around it: separating "remember" from "show once", keeping the default edition at the canonical URL for crawlers, and carrying the choice into deeper pages like the blog.
If you build something similar, start with the home page only and add the matcher paths one section at a time. And if you want to see the result, the edition switcher is in the corner of this page. More of what I've written is on the Writing page, and if debugging stories are your thing, Lessons from Debugging a Stubborn Bug walks through the process I used to find the sideways scroll.