Common API

Contents

Exports from @enonic/nextjs-adapter may be used in shared code unless their behavior requires a server-only Next.js API.

Usage

import {
    ComponentRegistry,
    getLocaleMapping,
    I18n,
    imageUrl,
    imageUrlQuery,
    validateData
} from '@enonic/nextjs-adapter';

Functions

getContentBranch

Returns the XP branch for a request context: master for direct Next.js and live requests, draft for editing contexts.

Parameters

getContentBranch() takes an optional Context object. Without it, the branch follows the RENDER_MODE environment variable, defaulting to master.

Returns

string — master or draft.

getLocaleMapping

Resolves the locale, project, and site mapping for a request. The Content Studio project header takes precedence over the route locale.

Parameters

getLocaleMapping() takes a single Context object.

Returns

LocaleMapping.

getLocaleMappingByLocale

Returns the mapping for locale. The optional useDefault boolean defaults to true and controls fallback to the default mapping.

Parameters

Name Type Description

locale

string

Optional. Locale to find.

useDefault

boolean

Optional. Fall back to the default mapping. Default: true.

Returns

LocaleMapping or undefined.

getLocaleMappingByProjectId

Returns the mapping for an XP project ID. Matching is case-insensitive; useDefault defaults to true.

Parameters

Name Type Description

projectId

string

Optional. XP project ID to find.

useDefault

boolean

Optional. Fall back to the default mapping. Default: true.

Returns

LocaleMapping or undefined.

getRequestLocaleInfo

Returns {locale, locales, defaultLocale} for a request context. The project header is used in Content Studio; otherwise the route locale or default locale is used.

Parameters

getRequestLocaleInfo() takes a single Context object.

Returns

An object containing the selected locale, all configured locales, and defaultLocale.

localizeMappings

Prefixes the targets of URL mapping rules with a locale, for the /api/mappings response. Targets of the default mapping are returned unchanged, because default-locale URLs carry no prefix. Sources stay site-relative.

Parameters

Name Type Description

mappings

UrlMappingRule`[]`

Rules to localize.

mapping

{locale, default}

Locale mapping of the project, normally from getLocaleMappingByProjectId().

Returns

Example

const MAPPINGS: UrlMappingRule[] = [
    {sources: ['/.*'], target: '/${siteRelativePath}'}
];

return NextResponse.json({mappings: localizeMappings(MAPPINGS, mapping)});

encryptParams

Encrypts a JSON-serializable object with AES-256-GCM, using the SHA-256 hash of secret as the key. The result is the xp blob format the Next.XP app sends. Requires Node.js crypto, so call it only from server code.

Parameters

Name Type Description

params

Record<string, any>

Values to encrypt.

secret

string

Shared secret, normally ENONIC_API_TOKEN.

Returns

string — base64url-encoded IV, ciphertext, and authentication tag.

decryptParams

Decrypts an xp blob produced by the Next.XP app or encryptParams(). Successful decryption proves that the sender knows the shared secret. Requires Node.js crypto, so call it only from server code.

Parameters

Name Type Description

blob

string

Value of the xp parameter.

secret

string

Shared secret, normally ENONIC_API_TOKEN.

Returns

Record<string, any> with the decrypted values, such as xpProject, or null when the blob is invalid or was encrypted with another secret.

imageUrlQuery

Returns the Guillotine selection for an image URL: imageUrl(<args>) with every field of the ImageUrl type. Use it inside a …​ on media_Image selection.

Parameters

imageUrlQuery() takes a single args object with these properties:

Name Type Description

scale

string

Image scale, for example width(500) or block(100,100).

quality

number

Optional. JPEG quality.

background

string

Optional. Background color for transparent images.

format

string

Optional. Output format, for example webp.

filter

string

Optional. Image filter.

params

Record<string, unknown>

Optional. Extra query parameters added to the URL.

Returns

string.

Example

`... on media_Image { ${imageUrlQuery({scale: 'width(500)'})} }`

mediaUrlQuery

Returns the Guillotine selection mediaUrl(<args>) with every field of the AttachmentUrl type.

Parameters

mediaUrlQuery() takes an optional MediaUrlArgs object.

Returns

string.

attachmentUrlQuery

Returns the Guillotine selection attachmentUrl(<args>) with every field of the AttachmentUrl type.

Parameters

attachmentUrlQuery() takes an optional MediaUrlArgs object.

Returns

string.

pageUrlQuery

Returns the Guillotine selection pageUrl(<args>) { url path queryString }.

Parameters

pageUrlQuery() takes an optional args object with these properties:

Name Type Description

params

Record<string, unknown>

Optional. Extra query parameters added to the URL.

Returns

string.

imageUrl

Builds an absolute image URL from the result of imageUrlQuery(): the media base URL (ENONIC_MEDIA_CDN, default ENONIC_API) followed by the media part of path and the queryString. In client code without a NEXT_PUBLIC_ copy of these variables, the path is returned unchanged.

Parameters

data (ImageUrl, or any object with path and an optional queryString) — URL object from Guillotine. May be null or undefined.

Returns

string, or undefined when data is empty.

mediaUrl

Builds an absolute media URL from the result of mediaUrlQuery(), in the same way as imageUrl().

Parameters

data (AttachmentUrl, or any object with path and an optional queryString) — URL object from Guillotine. May be null or undefined.

Returns

string, or undefined when data is empty.

attachmentUrl

Builds an absolute attachment URL from the result of attachmentUrlQuery(), in the same way as imageUrl().

Parameters

data (AttachmentUrl, or any object with path and an optional queryString) — URL object from Guillotine. May be null or undefined.

Returns

string, or undefined when data is empty.

pageUrl

Builds a relative Next.js URL from the result of pageUrlQuery(). The site-relative path is prefixed with meta.locale unless it equals meta.defaultLocale.

Parameters

Name Type Description

data

PageUrl

URL object from Guillotine. Only path is required, so {path: '/'} gives the site root. May be null or undefined.

meta

{locale, defaultLocale}

Usually the page’s MetaData. Without defaultLocale, the locale prefix is always added, which gives the internal /[locale] route path.

Returns

string, or undefined when data is empty.

Example

<Link href={pageUrl(parent.pageUrl, meta)}>Back</Link>
<Link href={pageUrl({path: '/'}, meta)}>Home</Link>

richTextFragments

Returns the GraphQL fragment definitions spread by richTextQuery(), including the registered macros. fetchGuillotine() appends them automatically; use this function for queries sent through another client.

Returns

string.

withRichTextFragments

Appends the rich-text fragment definitions a query spreads but does not define.

Parameters

query (string) — GraphQL document.

Returns

string.

sanitizeGraphqlName

Converts text into a valid GraphQL name by replacing unsupported characters and prefixing names that begin with a number.

Parameters

text (string) — value to sanitize.

Returns

string.

validateData

Validates a FetchContentResult. Missing content invokes Next.js not-found handling; XP shortcuts invoke redirect handling.

Parameters

props (FetchContentResult) — result returned by fetchContent().

Returns

void. The function may invoke Next.js navigation handling.

Classes

ComponentRegistry

Static registry connecting XP descriptors to queries, processors, and React views.

addContentType

Registers a content-type mapping by application-qualified name.

addPage

Registers an XP page descriptor.

addLayout

Registers an XP layout descriptor.

addPart

Registers an XP part descriptor.

addMacro

Registers an XP macro descriptor.

addComponent

Registers a generic component kind such as the built-in part, layout, or text handling.

Each registration method accepts a name and a ComponentDefinitionParams object. Repeated registration merges properties for the same name.

setCommonQuery

Sets the query whose processed result is returned as common for every render.

getCommonQuery

Returns the registered shared query.

getByComponent

Resolves the definition for a normalized PageComponent from its type and descriptor.

getContentType

Returns a content-type definition by name, falling back to CATCH_ALL when registered.

getPage

Returns a page definition by descriptor, with catch-all fallback.

getLayout

Returns a layout definition by descriptor, with catch-all fallback.

getPart

Returns a part definition by descriptor, with catch-all fallback.

getMacro

Returns a macro definition by descriptor, with catch-all fallback.

getComponent

Returns a generic component-kind definition, with catch-all fallback.

getContentTypes

Returns all explicitly registered content-type definitions as name-definition pairs.

getPages

Returns all explicitly registered page definitions.

getLayouts

Returns all explicitly registered layout definitions.

getParts

Returns all explicitly registered part definitions.

getMacros

Returns all explicitly registered macro definitions.

getComponents

Returns all explicitly registered generic component definitions.

I18n

Static localization helper for server-rendered front-end phrases.

setLocale

Loads @phrases/<locale>.json and returns its dictionary.

localize

Returns the phrase for a key and substitutes positional {} or indexed {0} placeholders. A missing phrase is returned as <key>.

getLocale

Returns the active locale.

getDictionary

Returns the loaded phrase dictionary.

Type Definitions

Context

Name Type Description

contentPath

string or string[]

Site-relative path requested from XP.

headers

Headers

Optional. Request headers.

locale

string

Optional. Active front-end locale.

LocaleMapping

Name Type Description

default

boolean

Whether this is the fallback mapping.

project

string

XP project ID.

site

string

Site path inside the project.

locale

string

Front-end locale.

ComponentDefinitionParams

Name Type Description

query

SelectedQueryMaybeVariablesFunc

Optional. Guillotine query and optional variables function.

configQuery

string

Optional. Query selection for component configuration.

processor

DataProcessor

Optional. Asynchronous data transformation.

view

React.FunctionComponent

Optional. React renderer.

GlobalVariables

Variables the adapter supplies to every registered query. A variables function must return them, optionally with additional variables.

Name Type Description

path

string

Full XP content path, including the site.

siteKey

string

Site path from the locale mapping.

project

string

XP project from the locale mapping.

branch

string

draft in draft mode, otherwise master.

UrlMappingRule

One rule of the /api/mappings response.

Name Type Description

sources

string[]

Conditions a content item must meet. A field:value entry compares a content field, for example type:portal:site; any other entry is a regular expression matched against the item’s site-relative path.

target

string

Next.js URL template. ${siteRelativePath} is replaced by the item’s site-relative path; other ${field} placeholders are replaced by content field values.

matchAny

boolean

Optional. Match when any source matches instead of all. Default: false.

ImageUrl

Result of imageUrlQuery().

Name Type Description

url

string

Ready-made URL, with the base URL resolved by XP.

path

string

Full media API path with a leading slash.

queryString

string

URL-escaped query string with a ? prefix.

context

string

Project context segment.

id

string

Content ID.

fingerprint

string

Media fingerprint.

scale

string

Processed scale segment.

name

string

File name, with the requested format extension.

AttachmentUrl

Result of mediaUrlQuery() and attachmentUrlQuery(). It has the url, path, queryString, context, id, fingerprint, and name fields of ImageUrl, plus:

Name Type Description

intent

string

download or inline.

PageUrl

Result of pageUrlQuery().

Name Type Description

url

string

URL as XP resolves it.

path

string

Site-relative content path.

queryString

string

URL-escaped query string.

MediaUrlArgs

Name Type Description

download

boolean

Optional. Serve the file as a download.

params

Record<string, unknown>

Optional. Extra query parameters added to the URL.

MetaData

Runtime information returned by fetchContent(): content identity and path, project, site, branch, XP base URL, locale, render mode, request type, renderability, and requested component.

Constants

Export Purpose

APP_NAME, APP_NAME_DASHED, APP_NAME_UNDERSCORED

Application key from the environment and descriptor-safe variants.

IS_DEV_MODE

Whether NODE_ENV is development, as under next dev.

CATCH_ALL

Registry key for a fallback definition.

RENDER_MODE

Direct, edit, preview, inline, live, and admin rendering modes.

XP_COMPONENT_TYPE, XP_REQUEST_TYPE

Normalized page-component kinds and fetch request kinds.

FROM_XP_PARAM

Name of the query parameter carrying the encrypted blob from XP: xp.

RENDER_MODE_HEADER, PROJECT_ID_HEADER, XP_BASE_URL_HEADER, JSESSIONID_HEADER

Header names shared with the XP preview proxy.

PORTAL_COMPONENT_ATTRIBUTE, PORTAL_REGION_ATTRIBUTE

DOM attributes used by Content Studio editing.

richTextQuery

Guillotine selection required for processed rich-text references.

Prefer these exports to duplicated string values in application code.


Contents

Contents