Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions examples/nextjs-app-router/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,5 @@ node_modules
.env.test.local
.env.production.local
.vercel
tsconfig.tsbuildinfo
next-env.d.ts
126 changes: 108 additions & 18 deletions examples/nextjs-app-router/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,33 +41,123 @@ Run `npm run build` for production build and `npm start` to start server in prod

## Uniform toolbar

In development, the floating product toolbar mounts from
`lib/uniform/CustomUniformClientContext.tsx` (same Context instance as
`UniformComposition`).
In development, the root layout (`app/layout.tsx`) renders the floating product
toolbar from `lib/uniform/AppUniformToolbar.tsx`. The toolbar gets the Context
from `useUniformContext()`, so it uses the same Context instance as the pages.

`package.json` overrides `@uniformdev/context` so the toolbar uses the same
version as the app. The toolbar's peer range (`^20.72`) does not include
prerelease versions of the SDK.

## Enable Uniform Insights

Uniform Insights is a Context plugin, so you must add it when the Context is made.

1. Set `NEXT_PUBLIC_UNIFORM_INSIGHTS_API_KEY` and `NEXT_PUBLIC_UNIFORM_INSIGHTS_API_URL`
in `.env`. See `.env.example`.
1. Make `lib/uniform/InsightsClientContext.tsx`. It is the default client context
component of the SDK, with the Insights plugin added:

```tsx
"use client";

import { ContextPlugin, enableContextDevTools } from "@uniformdev/context";
import { enableUniformInsights } from "@uniformdev/insights";
import {
ClientContextComponent,
createClientUniformContext,
useInitUniformContext,
} from "@uniformdev/next-app-router-client";
import { useRouter } from "next/navigation";

export const InsightsClientContext: ClientContextComponent = ({
manifest,
disableDevTools,
defaultConsent,
experimentalQuirkSerialization,
cookieMaxBytes,
pruneUnknownTests,
pruneUnknownDimensions,
pruneZeroScores,
}) => {
const router = useRouter();

useInitUniformContext(() => {
const plugins: ContextPlugin[] = [
enableUniformInsights({
endpoint: {
type: "api",
projectId: process.env.NEXT_PUBLIC_UNIFORM_PROJECT_ID!,
apiKey: process.env.NEXT_PUBLIC_UNIFORM_INSIGHTS_API_KEY!,
host: process.env.NEXT_PUBLIC_UNIFORM_INSIGHTS_API_URL!,
},
}),
];

if (!disableDevTools) {
plugins.push(
enableContextDevTools({
onAfterMessageReceived: () => {
router.refresh();
},
}),
);
}

return createClientUniformContext({
manifest,
plugins,
defaultConsent,
experimental_quirksEnabled: experimentalQuirkSerialization,
cookieMaxBytes,
pruneUnknownTests,
pruneUnknownDimensions,
pruneZeroScores,
});
});

return null;
};
```

Until the packages are on npm, this starter depends on a local clone via `file:`:
1. Give the component to `UniformComposition` in `app/uniform/[code]/page.tsx`
and to `UniformPlayground` in `app/playground/[code]/page.tsx`:

```
../../../toolbar/packages/toolbar
../../../toolbar/packages/toolbar-element
../../../toolbar/packages/toolbar-react
```
```tsx
clientContextComponent={InsightsClientContext}
```

Insights attributes page hits and goals to the page composition. `UniformComposition`
and `UniformPlayground` set it by default (`pageComposition`).

## Edge personalization (NESI)

`.npmrc` sets `install-links=true` so those `file:` deps are copied instead of
symlinked — required for Next.js Turbopack (symlinks outside the project resolve as
missing modules).
`middleware.ts` uses `vercelUniformEdgeMiddleware` from `@uniformdev/next-app-router/vercel`.

Toolbar peers expect `@uniformdev/context` `^20.72`. This starter is still on `20.70` —
install with `npm install --legacy-peer-deps` until you bump the Uniform packages.
After publish, switch the toolbar deps to the published versions (for example `^20.73.0`)
and you can drop `install-links`.
- Every visitor of a route shares one cached page (`/uniform/[code]`). Personalizations and tests
are in that page between NESI tags.
- For an HTML document request, the middleware fetches the cached page and keeps only the
visitor's variants as it streams through. The first paint shows the right variant, with no flicker.
- The middleware loads the published Context manifest at runtime and keeps it in the Vercel runtime
cache. `app/api/preview/route.ts` passes `expireVercelRuntimeCacheTags` to the POST handler, so a
publish expires the cached manifest and page records. Point a Uniform webhook at `/api/preview`
for this.
- Pages that the middleware learns have no placements are rewritten without processing.
`generateStaticParams` prebuilds both edge mode values (`edgeMode: [true, false]`) for this.
- The `missing` header rule in the matcher stops the middleware from running again on its own
fetch of the cached page (`x-uniform-edge-origin`).
- Visibility rules run in the browser. NESI does not support them.
- Outside Vercel (`next start` locally), the runtime cache falls back to memory.

## Important: Uniform Preview support

In order to support Uniform preview for Next.js 16 on Vercel, you need to leave `middleware.ts` named as such, don't rename it to `proxy.ts` and keep this export in it:
In order to support Uniform preview for Next.js 16 on Vercel, you need to leave `middleware.ts` named as such, don't rename it to `proxy.ts` ([vercel/next.js#82344](https://github.com/vercel/next.js/issues/82344)) and keep the edge runtime in its config:

```
export const runtime = 'experimental-edge';
export const config = {
matcher: [/* ... */],
runtime: 'experimental-edge',
};
```

## How to enable cache components support
Expand Down
4 changes: 3 additions & 1 deletion examples/nextjs-app-router/app/api/preview/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ import {
createPreviewPOSTRouteHandler,
createPreviewOPTIONSRouteHandler,
} from "@uniformdev/next-app-router/handler";
import { expireVercelRuntimeCacheTags } from "@uniformdev/next-app-router/vercel";

export const GET = createPreviewGETRouteHandler();
export const POST = createPreviewPOSTRouteHandler();
// Publishing expires what the edge middleware keeps in the Vercel runtime cache (manifest, page records).
export const POST = createPreviewPOSTRouteHandler({ onRevalidateTags: expireVercelRuntimeCacheTags });
export const OPTIONS = createPreviewOPTIONSRouteHandler();
3 changes: 3 additions & 0 deletions examples/nextjs-app-router/app/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";

import { AppUniformToolbar } from "@/lib/uniform/AppUniformToolbar";

import "./globals.css";

const geistSans = Geist({
Expand Down Expand Up @@ -29,6 +31,7 @@ export default function RootLayout({
className={`${geistSans.variable} ${geistMono.variable} font-sans antialiased bg-neutral-50 text-neutral-950`}
>
{children}
<AppUniformToolbar />
</body>
</html>
);
Expand Down
4 changes: 2 additions & 2 deletions examples/nextjs-app-router/app/uniform/[code]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,13 @@ import {
// TODO: Uncomment this to use resolveComponent with cache components support
// import { resolveRouteFromCode } from "@uniformdev/next-app-router/cache";
import { resolveComponent } from "@/components/resolveComponent";
import { CustomUniformClientContext } from "@/lib/uniform/CustomUniformClientContext";

export const generateStaticParams = async () => {
return createUniformStaticParams({
// Important: for localized sites, you need to add the locales to the paths
paths: ["/en"],
// Prebuild both edge mode values: the middleware skips pages it learns have no placements.
edgeMode: [true, false],
});
};

Expand All @@ -25,7 +26,6 @@ export default async function UniformPage(props: UniformPageParameters) {
code={code}
resolveRoute={resolveRouteFromCode}
resolveComponent={resolveComponent}
clientContextComponent={CustomUniformClientContext}
/>
);
}
19 changes: 19 additions & 0 deletions examples/nextjs-app-router/lib/uniform/AppUniformToolbar.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
"use client";

import { useUniformContext } from "@uniformdev/next-app-router-client";
import { UniformToolbar } from "@uniformdev/toolbar-react";

export function AppUniformToolbar() {
const { context } = useUniformContext();

return (
<UniformToolbar
// Local file: installs resolve @uniformdev/context from the toolbar monorepo
// and the starter separately. Drop the cast after installing from npm with a
// matching @uniformdev/context (^20.72).
context={context as never}
simulator
enabled={process.env.NODE_ENV === "development"}
/>
);
}

This file was deleted.

15 changes: 11 additions & 4 deletions examples/nextjs-app-router/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { uniformMiddleware } from "@uniformdev/next-app-router/middleware";
import { vercelUniformEdgeMiddleware } from "@uniformdev/next-app-router/vercel";

// Important: the list of locales can be retrieved from Uniform API for multi-lingual solutions
const locales = ["en"]; // example locales, adjust as needed

export default uniformMiddleware({
// Edge mode: every visitor of a route shares one cached page, and the middleware keeps
// the visitor's personalization and test variants as the page streams through.
export default vercelUniformEdgeMiddleware({
// since the default locale in the starter is 'en', in order for the app to respond on locale-less path, we add this rewrite
rewriteRequestPath: async ({ url }) => ({
path: formatPath(url.pathname, locales[0]),
Expand All @@ -27,10 +29,15 @@ const isLocaleInPath = (path: string): boolean => {
: false;
};

// IMPORTANT: This is required for the middleware to work correctly for preview in Next.js 16
// IMPORTANT: keep this file as middleware.ts on the edge runtime. Do not rename it to proxy.ts:
// there the SDK cannot read draft mode, so Uniform preview breaks on Vercel (vercel/next.js#82344).
export const config = {
matcher: [
"/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
{
source: "/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
// The middleware's own fetch of the cached page carries this header. Skip it.
missing: [{ type: "header", key: "x-uniform-edge-origin" }],
},
],
runtime: "experimental-edge",
};
6 changes: 0 additions & 6 deletions examples/nextjs-app-router/next-env.d.ts

This file was deleted.

Loading