Next.js App Router SDK Reference

Developer preview

This feature is in developer preview. Use with caution as it may change unexpectedly. For more information, contact us.

Developer Preview

This reference documents version 20.81.1-alpha.25.sha-f076f9b857. The entry points @uniformdev/next-app-router/edge and @uniformdev/next-app-router/vercel are new in the developer preview.

PackagePeer dependencies
@uniformdev/next-app-routernext 16.0.7 or later, react and react-dom 18.2 or 19, @vercel/functions 3 or later (optional)
@uniformdev/next-app-router-clientnext 16.0.7 or later, react and react-dom 18.2 or 19
@uniformdev/next-app-router-sharednext 16.0.7 or later, react and react-dom 18.2 or 19

All three packages require Node.js 20.9 or later.

Server-only exports. The entry point imports server-only.

ExportDescription
UniformCompositionResolves the route from a [code] and renders the composition in UniformContext.
UniformResolvedCompositionRenders the components of a resolver result. Renders nothing for a redirect or a not-found result.
UniformContextStarts the browser Context, and adds the visual editing script and the edge state script. Render it one time on each page.
UniformPlaygroundRenders a pattern from a code or a result. Draft mode only.
resolveRouteFromCodeResolves the route in a code with the Route API.
resolveRouteFromPathResolves a path with the Route API.
resolveCompositionByIdGets a composition by ID with the Composition API.
resolveCompositionBySlugGets a composition by slug with the Composition API.
resolvePlaygroundRouteGets the pattern of a playground code.
requireCompositionReturns the composition, or calls redirect(), permanentRedirect() or notFound().
resolveRedirectHrefReturns the target URL of a redirect result.
deserializePageStateChanges a code into a PageState.
createUniformStaticParamsMakes the codes for generateStaticParams of the [code] route.
createUniformPlaygroundStaticParamsMakes the codes for generateStaticParams of the playground route.
createCompositionCacheMakes a composition cache.
serverContextMakes a getter and a setter for a value of one server request.
findRouteMatchMatches a path to :name patterns.
getCompositionDeliveryClientComposition API client with cache tags.
getCanvasClientDeprecated. Use getCompositionDeliveryClient.
getRouteClientRoute API client with cache tags.
getProjectMapClientProject Map API client.
getManifest / getManifestClientContext manifest access.

Types: UniformCompositionProps, UniformResolvedCompositionProps, UniformContextProps, UniformPlaygroundProps, UniformPageParameters, AwaitedUniformPageParameters, PlaygroundParameters, ResolveComponentFunction, ResolveComponentResult, ResolveRouteFunction, ResolveRouteFromCodeOptions, ResolveRouteFromPathOptions, ResolveCompositionByIdOptions, ResolveCompositionBySlugOptions, ResolveRedirectHrefOptions, PageStateSource, ResolvedRouteResult, ResolvedComposition, ResolvedCompositionResult, ResolvedRedirect, ResolvedNotFound, CreateStaticParamsOptions, CompositionCache, CustomRoute, RouteMatch.

Component utilities for server and client components:

ExportDescription
UniformSlotRenders the components of a slot.
getUniformSlotReturns the rendered slot items as a ReactNode array.
UniformTextRenders a text parameter, with in-page editing in Canvas.
UniformRichTextRenders a rich text parameter.
useUniformContextHook: the browser Context instance.
useQuirksHook: the quirks of the visitor.
useScoresHook: the scores of the visitor.
createClientUniformContextMakes a browser Context.
useInitUniformContextHook: starts the browser Context.

Types: ComponentProps, ComponentParameter, ComponentContext, ClientContextComponent, UniformSlotProps, UniformTextProps.

ExportDescription
uniformMiddlewareReturns a lite mode middleware.
handleUniformRouteHandles one request in lite mode.
resolveUniformRequestReturns the code, the destination and the headers for a request, for custom middleware. For a playground request, it can return a response.
determinePreviewModeReturns "editor", "preview" or undefined from the query strings and draft mode.

Types: HandleOptions, RewriteOptions, RewriteRequestPathOptions, ResolveUniformRequestOptions, ResolveUniformRequestResult.

ExportDescription
uniformEdgeMiddlewareReturns an edge mode middleware.
handleUniformEdgeRouteHandles one request in edge mode.
UNIFORM_EDGE_ORIGIN_HEADER"x-uniform-edge-origin", the header of the origin fetch.
learnedEdgeRouteFilterSkips the pages that the store recorded without placements.
createStaticEdgeRouteFilterProcesses only the paths that you list.
createEdgeRouteStoreMakes a store for edge route records.
createCachedManifestProviderMakes a manifest provider that keeps the manifest in memory and in a shared cache.

Types: UniformEdgeMiddlewareOptions, EdgeRouteFilter, EdgeRouteFilterOptions, CreateStaticEdgeRouteFilterOptions, EdgeRouteStore, EdgeRouteStoreCache, EdgeRouteRecord, EdgeRoutePage, CreateEdgeRouteStoreOptions, RecordedPlacement, RecordedPersonalizationOptions, RecordedTestOptions, ManifestProvider, ManifestProviderOptions, ManifestCache, CreateCachedManifestProviderOptions.

Install @vercel/functions for this entry point.

ExportDescription
vercelUniformEdgeMiddlewareReturns an edge mode middleware with the Vercel defaults.
vercelManifestProviderA manifest provider that uses the Vercel runtime cache.
vercelEdgeRouteStoreAn edge route store that uses the Vercel runtime cache.
expireVercelRuntimeCacheTagsExpires tags in the Vercel runtime cache. Give it to onRevalidateTags.

Types: VercelUniformEdgeMiddlewareOptions.

The resolvers with 'use cache', for Cache Components: resolveRouteFromCode, resolveRouteFromPath, resolveCompositionById, resolveCompositionBySlug.

ExportDescription
withUniformConfigWraps the Next.js configuration, and connects uniform.server.config.
UniformServerConfigType of the server configuration.
ExportDescription
createPreviewGETRouteHandlerGET handler: starts a Canvas preview. Options: resolveFullPath, processPlaygroundPath.
createPreviewPOSTRouteHandlerPOST handler: receives Uniform webhooks. Option: onRevalidateTags.
createPreviewOPTIONSRouteHandlerOPTIONS handler: answers CORS preflight requests.

Types: CreatePreviewPOSTRouteHandlerOptions.

ExportDescription
createAdapterResolveComponentFunctionMakes a component resolver for adapted components.
isAdaptedResolveComponentResultWithTypeReturns true for an adapted mapping.
UniformTextUniformText that takes parameterId.

Types: ComponentProps, ComponentContext, ResolveComponentResultWithType, AdaptedResolveComponentResultWithType, NonAdaptedResolveComponentResultWithType, UniformTextProps.

Client-only exports. Use them for a custom client context.

ExportDescription
createClientUniformContextMakes a browser Context.
useInitUniformContextHook: starts the browser Context, and updates it on each navigation.
DefaultUniformClientContextThe default client context component.
useUniformContext, useQuirks, useScoresThe same hooks as in /component.
EdgePlacementRenders a personalization or test in edge mode. The SDK uses it.

Types: ClientContextComponent, ClientContextComponentProps.

Types that the other packages use. The other entry points do not export these types.

ExportDescription
PageStateThe values in a code. Refer to PageState.
CompositionContextThe composition data that each component gets in context.
SlotDefinitionA slot that each component gets in slots.
RewriteRequestPathResultThe return value of rewriteRequestPath.
CacheMode, CanvasCacheMode, ManifestCacheMode, ProjectMapCacheModeThe cache option of the server clients.
PersonalizeProps, TestPropsProps of the SDK placement components.
UNIFORM_MIDDLEWARE_QUIRK_COOKIE_NAME"ufqc", the cookie that sends quirks from the middleware to the browser.

Install this package with the same version as @uniformdev/next-app-router if you import these types.

ExportDescription
flattenValuesGets the values of asset parameters.
AssetParamValueType for asset parameter values
LinkParamValueType for link parameter values. It includes the optional attributes with the custom link attributes of the author.
RichTextParamValueType for rich text parameter values
ExportDescription
linkParamValueToAnchorPropsChanges a LinkParamValue into React anchor props. It makes the href (with anchors and the mailto: and tel: prefixes), adds the sanitized custom link attributes, and changes class to className.
ExportDescription
linkParamValueToHrefChanges a LinkParamValue into an href string.
linkParamValueToHtmlAttributesChanges a LinkParamValue into sanitized HTML attributes, for output that is not React.

The behavior of the SDK depends on the type of the request:

RequestHow the SDK finds itWhat the middleware doesComposition stateCached by Next.jsWho chooses the variantsAdded for Canvas
Published, lite modeNo draft mode. uniformMiddleware.Rewrites to /uniform/[code].64YesThe browser, after hydration. The server renders the defaults.Nothing
Published, edge mode, documentNo draft mode. An edge middleware. A GET request for an HTML document.Fetches the cached page with x-uniform-edge-origin: 1, and keeps the variants of the visitor.64, with edgeModeThe origin page, yes. The response is private.The edge middlewareNothing
Published, edge mode, client navigation or prefetchThe rsc or next-router-prefetch header, or Sec-Fetch-Dest: emptyRewrites only.64, with edgeModeYesThe browser, before the new page paintsNothing
Published, edge mode, skipped by the filterThe edge route filter answers false.Rewrites only.64YesThe browser, after hydrationNothing
Origin fetch of the edgeThe x-uniform-edge-origin headerNothing. The matcher skips the request.Same as the codeYesThe edge middleware, after the fetchNothing
Draft (preview)Draft mode is on.Rewrites to /uniform/[code].0NoThe browserThe visual editing script
Editor (visual editing)Draft mode is on, and the URL has is_incontext_editing_mode.Rewrites to /uniform/[code].63, else 0 when there is no editor stateNoThe browserThe visual editing script and the editing markers
Playground (pattern preview)Draft mode is on, the path is playgroundPath, and the URL has id.Rewrites to ${playgroundPath}/[code]. Without id, it answers 400.63, else 0NoThe browserThe visual editing script and the editing markers

In the draft and editor states, the Route API ignores Uniform redirects. Visibility rules run in the browser for all request types.

type ComponentProps< TParameters extends Record<string, ComponentParameter> | unknown = Record<string, ComponentParameter>, TSlotNames extends string = string, > = { type: string; variant: string | undefined; slots: Record<TSlotNames, SlotDefinition>; parameters: TParameters; component: ComponentContext; context: CompositionContext; };
type ComponentContext = { _id: string; _parentId: string | null; slotName: string | undefined; slotIndex: number | undefined; };
type CompositionContext = { _id: string; type: string; state: number; isContextualEditing: boolean; matchedRoute: string; dynamicInputs: Record<string, string>; pageState: PageState; };
type SlotDefinition = { name: string; items: ({ _id: string; $pzCrit: VariantMatchCriteria | undefined; variantId: string | undefined; component: ReactNode; } | null)[]; };
type ComponentParameter<TValue = unknown> = BaseComponentParameter<TValue> & { parameterId: string; _contextualEditing?: { isEditable: boolean }; };
type PageState = { compositionState: number; // 64 published, 0 draft, 63 editor routePath: string; keys: Record<string, string> | undefined; releaseId: string | undefined; defaultConsent: boolean; previewMode: "editor" | "preview" | undefined; locale: string | undefined; edgeMode?: boolean; };

The code has the format 3~{state}~{route}~{keys}~{flags}~{releaseId}~{locale}. The SDK removes empty fields at the end. Codes from version 20.81 (2~…) are not supported.

type ResolvedRouteResult = | { pageState: PageState; route: RouteGetResponseEdgehancedComposition } | { pageState: PageState; route: RouteGetResponseRedirect } | { pageState: PageState; route: undefined };
type ResolveComponentResult = { component: ComponentType<ComponentProps<any, any>> | null; suspense?: { fallback: ComponentType<any> | undefined; }; };
type UniformServerConfig = { defaultConsent?: boolean; playgroundPath?: string; context?: { disableDevTools?: boolean; personalizationSelectionAlgorithms?: ContextPlugin["personalizationSelectionAlgorithms"]; }; quirkSerialization?: boolean; };
type HandleOptions = { rewriteRequestPath?: (options: { url: URL; request: Request }) => Promise<{ path: string; keys?: Record<string, string> } | undefined>; rewriteDestinationPath?: (options: { source: "route" | "playground"; code: string; pageState: PageState }) => Promise<string>; queryStrings?: Record<string, string[]>; release?: { id: string }; quirks?: Quirks; defaultConsent?: boolean; locale?: string; };
type UniformEdgeMiddlewareOptions = HandleOptions & { manifest: ManifestV2 | ManifestProvider; onError?: (details: { error: unknown; chunk?: string }) => void; filter?: EdgeRouteFilter; store?: EdgeRouteStore; etags?: boolean; };
type EdgeRouteFilter = { shouldProcess: (options: { pageState: PageState; waitUntil: (promise: Promise<unknown>) => void; getRecord: () => Promise<EdgeRouteRecord | undefined>; }) => boolean | Promise<boolean>; };
type CreateStaticParamsOptions = { paths: string[]; rewrite?: (options: { path: string }) => Promise<{ path: string; keys?: Record<string, string> } | undefined>; locale?: string; edgeMode?: boolean | EdgeRouteFilter | (boolean | EdgeRouteFilter)[]; defaultConsent?: boolean | boolean[]; };

The cache option of the server clients:

type CacheMode = | { type: RequestInit["cache"] } // "force-cache", "no-cache", "no-store" and so on | { type: "revalidate"; interval: number }; // revalidate after the interval, in seconds