Merchants & developers

Next.js App Router (server-side)

Assign Apex variants before React renders, with server styles, slots, flags, consent, and CDN caching.

Use @drip-apex/sdk/next when your App Router storefront renders experiment content on the server. Apex makes the assignment before React renders, so the HTML, React Server Component payload, and hydration agree. Tests rendered this way need no browser JavaScript.

The entry is server-only. Import it in Server Components, route handlers, or your proxy. Client Components must use the React bindings instead. Use Next.js 16 for proxy.ts; App Router versions with after() can use middleware.ts and an exported middleware function.

Configure your shop

Install @drip-apex/sdk in your existing Next.js app. Create one server initialization module and import it from the proxy and each server entry that uses Apex:

ts
// lib/apex.ts
import { configureApex } from '@drip-apex/sdk/next';
 
configureApex({
  shopId: 'your-shop-id',
  sourceKey: process.env.APEX_SOURCE_KEY,
  revalidateSeconds: 60,
  consent: ctx => ctx.cookies.get('analytics_consent')?.value === 'yes',
});

Keep the apx_src_ tracking source key in your server environment. Never prefix it with NEXT_PUBLIC_ or pass it to a Client Component. Config defaults to https://app.drip-apex.com/api/exp?shopId=...; events default to https://events.drip-apex.com/v1/events. Set configUrl and eventsUrl only when using your own corresponding endpoints. Compile the entry with Next (use transpilePackages: ['@drip-apex/sdk'] if your app externalizes packages).

configUrl must be an absolute HTTP(S) URL; configureApex reports invalid configuration at startup. If an invalid URL still reaches a request, config loading fails open and original content renders. eventsUrl accepts an origin, a proxy base such as https://proxy.example.com/apex, or its full https://proxy.example.com/apex/v1/events endpoint. Both events and /v1/assign retain the /apex prefix.

ts
// proxy.ts
import './lib/apex';
import { apexProxy } from '@drip-apex/sdk/next';
import type { NextRequest } from 'next/server';
 
export function proxy(request: NextRequest) {
  return apexProxy(request);
}
 
export const config = { matcher: ['/products/:path*', '/collections/:path*'] };

On consent-mode shops, server-side analytics requires a consent callback that returns the boolean true based on your consent provider’s current decision. Apex ignores its own drip_consent cookie for this decision. An absent callback leaves consent unknown. Any other return value or a thrown error blocks server delivery. Replace the example’s analytics_consent read with your provider’s current server-readable decision. Define the callback in configureApex as shown so it runs on routes outside the proxy matcher, including routes that call trackServerEvent, and when the proxy and renderer run in separate processes or runtimes. A callback passed only to apexProxy can share its grant with the renderer when both run in the same process.

Until required consent is granted, server rendering uses original content and caller-provided flag defaults. The same fallback applies to memory and sessionStorage even after consent, and when the published config cannot be loaded. In these cases the server creates no visitor or assignment cookies and sends no assignment requests or events. The browser SDK can make decisions where installed, according to its own consent and storage rules.

With localStorage, cookie, or the default storage mode, once the policy permits delivery, the proxy reuses a valid drip_uid or creates a 32-character lowercase hex ID. It forwards the ID and sets it on the response for new visitors, so even the first page is assigned. The cookie lasts one year, uses Path=/, SameSite=Lax, and is Secure on HTTPS.

Keep your config endpoint, static files, and image endpoints outside the proxy matcher. The proxy forwards the page URL as x-apex-url.

Render assignments, styles, and slots

tsx
import '@/lib/apex';
import { getApexAssignments, ApexStyles, ApexSlot } from '@drip-apex/sdk/next';
 
export default async function ProductPage() {
  const apex = await getApexAssignments();
  const offer = apex.variant('experiment-id');
  const enabled = await apex.flag('offer_enabled', false);
 
  return <main>
    <ApexStyles assignments={apex} />
    <h1>{offer && !offer.isControl ? 'Your variant title' : 'Your original title'}</h1>
    {enabled && <p>Your flag-controlled content</p>}
    <ApexSlot id="pdp-below-atc" assignments={apex} />
  </main>;
}

getApexAssignments() shares state within the Next request, including route handlers and server actions. Repeated reads with the same customer ID share the result and schedule exposures once. variant(id) returns variationId, index, isControl, and qa, or null when unassigned. Keep the original branch when it returns null.

ApexStyles renders one React-owned style tag with each assigned non-control variation's CSS and style mutations, in assignment order. ApexSlot renders a div with data-apex-slot and applies HTML or text mutations targeting exactly [data-apex-slot="pdp-below-atc"]. HTML is server-rendered only when it is plain markup; a fragment with scripts, event handlers or other blocked content is left out. Set HTML, set text, insert before/after, prepend, and append are applied in order to the slot's content. A control or unassigned slot is empty. Put original page content outside the slot or render it in your own assignment branch.

Apex does not rewrite HTML after React renders. Selectors targeting other elements, arbitrary attributes, remove actions, custom JavaScript, clicks, scrolls, and other browser interactions stay with the browser SDK. Do not let a browser mutation and a server component both own the same content.

Customer identity and flags

Pass the same customer ID that your Flutter, iOS, or Android app passes to identify:

ts
const apex = await getApexAssignments({ userId: customer.id });

The customer ID applies to API-delivered feature-flag tests shared with your app. Page experiments, including CSS and slots, always bucket by the visitor cookie drip_uid, just as the browser SDK does; signing in does not change those assignments. You can provide resolveUserId: async ctx => ... in configureApex to read your authenticated customer from the request. Derive it from your server session, never an untrusted query parameter.

await apex.flag('flag_key', defaultValue) reads a public flag locally using drip_uid. API-delivered flags are absent from the public config, so the first missing flag triggers one authenticated POST /v1/assign with your customer ID as user_id (or drip_uid when absent); other flag reads in that request share it. An unavailable flag returns your default after at most 800 ms. A flag value of another type than your default (for example null for a string default) also returns the default; pass null as the default to read raw JSON values. Use the same customer ID across channels for feature-flag tests shared with your app. Pass that same customer ID as userId to trackServerEvent at checkout, or configure resolveUserId, so purchases keep API-flag attribution.

Append ?drip_force=EXPERIMENT:VARIATION to preview a variation. Comma-separated pairs preview multiple experiments; EXPERIMENT:~ renders the original. The proxy keeps the force in drip_qa_force for 30 minutes and forwards it before rendering.

When a forced experiment is absent from live config, Apex fetches the QA config with drip_qa=1 and drip_force, without shared caching. A drip_qa_session query parameter or cookie also marks the request as QA. Draft previews therefore work before launch without placing the draft in the shared live cache. Exposures, purchases, and goals automatically carry qa_mode: true for a QA force or session.

Events

Apex schedules one experiment_viewed per assignment per request through Next's after(), batched in one authenticated request. Each event includes its event ID, visitor, experiment, variation, index, assignment epoch, page URL, and web platform.

Send purchases and custom goals from a server route with the same configuration:

ts
await trackServerEvent({
  eventType: 'purchase',
  visitorId,
  eventId: `purchase:${order.id}`,
  properties: { order_id: order.id, revenue: order.total, currency: order.currency },
});

Purchases send one shop-level row without experiment fields, then one row per remembered assignment with experiment_id and variation_id. All rows share the same event ID, timestamp, visitor and purchase properties. You do not need to read every flag again on the checkout request. If you read API flags with getApexAssignments({ userId }), pass the same customer ID as trackServerEvent({ ..., userId }) or configure resolveUserId; keep visitorId set to the visitor’s drip_uid.

The assignment history is the browser SDK's first-party drip_assignments_v1 cookie: experiment IDs map to [variationId, assignmentEpoch, assignedAtMilliseconds]. The proxy merges its page decisions into this cookie and forwards the updated cookie to the current request as well as the response. getApexAssignments also updates the request's history and writes the cookie in a route handler or Server Action. Server Components cannot set response cookies, so the proxy must cover tested pages; API-only flag reads made exclusively in a Server Component remain available for attribution within that request, but need a cookie-writable route or action to persist for a later checkout. Keep the proxy matcher on checkout routes too.

On purchase, Apex uses the recorded assignments plus assignments already evaluated in this request. Public assignments must still have a live, eligible experiment, the same assignment epoch and an existing variation. Page URL changes and traffic-allocation changes do not discard a recorded sticky assignment. Audience, schedule, holdout and exclusion checks still apply. Recorded API-only flags absent from public config are revalidated through /v1/assign; this does not emit new exposures or add flags the visitor never read. Unknown, stopped, reset or deleted assignments are left out. A purchase without assignment history still sends its shop-level row. If config or API revalidation is unavailable, only already validated request assignments and the shop-level row are sent. QA uses the request's QA assignments and does not read or overwrite live assignment history.

The browser keeps up to 80 assignment records in localStorage and the newest 20 in this cookie. The server can read only the cookie and its current request, so localStorage-only assignments are unavailable. The proxy writes host-only cookies; it does not synchronize a separate browser cookieDomain configuration or assignment history across subdomains. The browser also knows whether DOM mutation delivery is pending or contaminated; the server does not have that browser delivery state. Its page assignments describe server-rendered decisions. Browser trackRevenue emits revenue goals for attributable runtime assignments (or one unassigned goal if there are none); server purchases use the native app SDK's base-plus-assignment purchase rows. Native app SDKs use their current in-memory assignment list. Neither localStorage nor native app state is readable from a server request.

Custom goals are single rows. The browser's trackGoal resolves the goal through its configured goal wiring and attributable assignments; the server helper does not run that browser wiring. Supply the specific experiment and variation explicitly when the goal belongs to a test, for example:

ts
await trackServerEvent({
  eventType: 'goal', visitorId,
  experimentId: 'EXPERIMENT_ID', variationId: 'VARIATION_ID',
  properties: { goalId: 'signup' },
});

Import trackServerEvent from @drip-apex/sdk/next. Use a stable eventId for orders and retryable goals so retries cannot count twice. Otherwise Apex generates an ID for the call. See the event schema for purchase and goal fields. No events are sent without a source key or consent. Known bots receive the same rendered assignments as people, but send no exposures, purchases, or goals.

trackServerEvent returns Promise<boolean> and never throws for delivery failures. It resolves true only when every batch of at most 200 rows was accepted with no quarantined or rejected rows. A missing source key, network or HTTP errors, timeouts, or a failure in any batch resolves false and warns once without row contents. Check the boolean to retry with the same eventId. Events skipped because the shop policy blocks server delivery or the visitor is a known bot also resolve false. Programmer errors still throw: an invalid visitorId, a missing or empty purchase order_id, non-finite or negative revenue, or an invalid three-letter currency code.

CDN caching: Akamai and CloudFront

Start a proof of concept by bypassing shared caching on tested routes. This also applies to React Server Component and navigation requests. Leave untested routes on their existing caching rules.

For variation caching, run the proxy before the cache lookup. On a tested URL with a server assignment it sets apex_v to sorted experimentId=variationIndex pairs joined with a dot. With no assignments it clears that cookie. Use the newly forwarded cookie, including on a first visit; an incoming cookie alone can describe the previous route or a stopped test.

  • Akamai: in Property Manager, add a Cache ID Modification behavior on tested routes that includes the apex_v cookie value in the cache key. Untested routes keep their normal cache policy. Route the assignment step before cache lookup, or bypass shared caching whenever that ordering is unavailable.
  • CloudFront: create a cache policy that includes the apex_v cookie and apply it to tested behaviors. Resolve assignment before the cached response is selected; otherwise use the bypass rule.

Never add Vary: Cookie. Preserve Next's existing RSC and router-header cache distinctions. Do not share responses containing visitor-specific Set-Cookie headers, and bypass shared caching for QA, consent-dependent, logged-in, or otherwise personalized pages. Use variation caching only when the response is safe to share and the proxy and renderer share a server process. They share the request’s config snapshot within that process. Bypass shared caching when the proxy and renderer run in separate processes or runtimes.

Freshness and troubleshooting

Turning consent on takes effect per server instance at the next config refresh, with a cache window of revalidateSeconds (default 60 seconds, capped at 300 seconds). The first request after expiry waits for a bounded refresh before using identity or sending events. When a read fails or times out, Apex renders original content, uses caller-provided flag defaults, and skips further config reads for five seconds.

If the first page is unassigned, confirm the proxy matcher covers it and that drip_uid appears on the forwarded request, not just the response. If a draft preview is missing, check its force IDs and QA config response. If a flag returns the default, check the source key and /v1/assign response. If changes revert on hydration, render them through your assignment branch or an exact Apex slot and remove competing browser mutations.

A runnable fixture app is in packages/sdk/examples/next-app-router/ in the SDK repository.