1. Developer guides

Angular middleware

Version: 1.x

The src/server.ts file in a Content SDK Angular application contains customizable server-side pre-processing logic for incoming requests. This logic runs through Express.js middleware. This topic describes the built-in middleware and their roles.

Middleware overview

The following table summarizes each middleware, when it runs, and its purpose. For detailed configuration options, see Middleware reference.

Middleware

Server navigation

Browser navigation

Editing/preview modes

Description

Loader data service

Provides layout, dictionary, and other loader data during browser navigation.

Personalize

Resolves personalization data for the current route.

Multisite

Resolves the target site by hostname in multi-site configurations.

Bot detection

Detects bot requests and reports bot page views, skipping personalization for bot traffic.

Redirects

Matches requests against SXA redirect items and redirects when there's a match.

Editing config

Handles /api/editing/config requests used internally by Pages Editor.

Editing render

Handles /api/editing/render requests that enable editing in Pages Editor.

Cache revalidate

Processes /api/revalidate requests to revalidate loader cache entries.

Sitemap

Generates and serves XML sitemaps.

Robots

Generates and serves the robots.txt file.

Middleware reference

The following sections explain the middleware available in the Content SDK for Angular.

Loader data service middleware

This middleware is required for the Angular application to function correctly. Do not remove it. The Loader data service middleware supplies layout, dictionary, and other loader data to Content SDK loaders during browser navigation.

Register this middleware in server.ts using the createLoaderDataServiceMiddleware() factory function.

Options reference

interface LoaderDataServiceOptions {
  loaders: LoaderRegistry;
  cache: LoaderCache;
}

Property

Type

Description

loaders

LoaderRegistry

The loader registry, equivalent to provideLoaderRegistry(LOADERS).

Required

cache

LoaderCache

The loader cache instance initialized earlier in server.ts.

Required

Personalize middleware

The Personalize middleware resolves personalization data for the current route. The resulting variantId is used when resolving layout data from the SitecoreAI Edge endpoint.

Register this middleware in server.ts using the createPersonalizeMiddleware() factory function.

Options reference

type PersonalizeMiddlewareOptions = {
  enabled?: boolean;
  skip?: (req: ExpressRequest) => boolean;
  // configure paths to run middleware for
  matcher?: {
    includePaths?: (string | RegExp)[];
    excludePaths?: (string | RegExp)[];
  };
  // Mirrors the SitecoreConfig['personalize'] section
  personalize: {
    enabled?: boolean;
    edgeTimeout?: number;
    cdpTimeout?: number;
    scope?: string;
    channel?: string;
    currency?: string;
  };
  // Mirrors the SitecoreConfig['api']['edge'] section
  api: {
    edge: {
      contextId?: string;
      clientContextId?: string;
      edgeUrl?: string;
    }
  };
  locales?: string[];              // list of locales for personalize to use
  defaultLanguage?: string;        // default: 'en'
  defaultSite?: string;
  personalizeService?: PersonalizeService;
  getExtraUtmParams?: (req: ExpressRequest) => Partial<{
    campaign?: string;
    source?: string;
    medium?: string;
    content?: string;
    [key: string]: string | undefined;
  }>;
};

Property

Type

Description

enabled

boolean

Enables or disables the middleware.

Optional

skip

(req: ExpressRequest) => boolean

A callback that skips middleware execution for specific requests.

Optional

matcher

object

Configures path inclusion and exclusion rules for the middleware.

Optional

personalize

object

Personalization settings. Maps to the personalize section of your Sitecore configuration.

Required

api

object

API endpoint settings. Maps to the api.edge section of your Sitecore configuration.

Required

locales

string[]

List of locales for personalization.

Optional

defaultLanguage

string

Fallback language.

Default: 'en'.

Optional

defaultSite

string

Fallback site name.

Optional

personalizeService

PersonalizeService

A custom personalize service instance.

Optional

getExtraUtmParams

function

Returns additional UTM parameters to include in personalization requests.

Optional

Multisite middleware

The Multisite middleware resolves the target site for an incoming request based on hostname. Use this middleware when you have multiple sites configured in Sitecore.

Register this middleware in server.ts using the createMultisiteMiddleware() factory function.

Options reference

type MultisiteMiddlewareOptions = BaseMiddlewareOptions & {
  // From AngularSitecoreConfig['multisite']
  enabled?: boolean;
  // configure if site should be resolved from sc_site cookie. default false
  useCookieResolution?: (
    req?: ExpressRequest,
    res?: ExpressResponse
  ) => boolean;
  // sites to consider for resolution
  sites?: SiteInfo[];
  defaultSite?: string;            // fallback when resolution fails
};

Property

Type

Description

enabled

boolean

Enables or disables the middleware.

Optional

useCookieResolution

function

When it returns true, the site is resolved from the sc_site cookie. Defaults to false.

Optional

sites

SiteInfo[]

The list of sites to consider during resolution.

Optional

defaultSite

string

Fallback site name when resolution fails.

Optional

Editing config middleware

The Editing config middleware processes /api/editing/config requests used internally by Pages Editor. We recommend that you do not customize this middleware.

Register this middleware in server.ts using the createEditingConfigMiddleware() factory function.

Options reference

interface CreateEditingConfigMiddlewareOptions {
  components: ComponentMap;        // required  same as SITECORE_COMPONENT_MAP
  metadata?: Metadata;             // inline; if set, metadataImport is ignored
  metadataImport?: MetadataImportFn; // dynamic function for metadata resolution
}

Property

Type

Description

components

ComponentMap

The component map, equivalent to SITECORE_COMPONENT_MAP.

Required

metadata

Metadata

Inline metadata. If set, metadataImport is ignored.

Optional

metadataImport

MetadataImportFn

A dynamic function for metadata resolution.

Optional

Editing render middleware

The Editing render middleware processes /api/editing/render requests that enable editing in Pages Editor.

Register this middleware in server.ts using the createEditingRenderMiddleware() factory function.

Options reference

interface CreateEditingRenderMiddlewareOptions {
  // Allows apps to remap the editor's `route` query parameter to their own URL
  resolvePageUrl?: (
    itemPath: string,
    previewData: EditingPreviewData
  ) => string;
  // Extra query parameters propagated into the editing preview data
  // (e.g. deployment-protection bypass tokens).
  allowedQueryParams?: AllowedQueryParams;
}

Property

Type

Description

resolvePageUrl

function

Remaps the editor's route query parameter to a custom URL.

Optional

allowedQueryParams

AllowedQueryParams

Extra query parameters propagated into the editing preview data, such as deployment-protection bypass tokens.

Optional

Cache revalidate middleware

The Cache revalidate middleware processes the /api/revalidate endpoint. You can use this endpoint in combination with webhooks to revalidate loader cache entries. For more information, see Loaders cache layer and tags revalidation.

Register this middleware in server.ts using the createSitecoreRevalidateMiddleware() factory function.

Options reference

interface SitecoreRevalidateMiddlewareOptions {
  cache: LoaderCache;              // loader cache instance initialized earlier in the file
  secret?: string;                 // default: process.env.SITECORE_REVALIDATE_SECRET
  defaultLocale?: string;          // default: 'en'
}

Property

Type

Description

cache

LoaderCache

The loader cache instance initialized earlier in server.ts.

Required

secret

string

The revalidation secret. Defaults to process.env.SITECORE_REVALIDATE_SECRET.

Optional

defaultLocale

string

Fallback locale. Defaults to 'en'.

Optional

Sitemap middleware

The Sitemap middleware generates and serves XML sitemaps at /sitemap.xml and numbered /sitemap-{id}.xml paths.

Register this middleware in server.ts using the createSitemapMiddleware() factory function.

Options reference

interface CreateSitemapMiddlewareOptions {
  client: SitecoreClient;
  sites: SiteInfo[];
}

Property

Type

Description

client

SitecoreClient

The Sitecore client instance.

Required

sites

SiteInfo[]

The list of sites to include in the sitemap.

Required

Robots middleware

The Robots middleware generates and serves the robots.txt file at the /robots.txt path.

Register this middleware in server.ts using the createRobotsMiddleware() factory function.

Options reference

interface CreateRobotsMiddlewareOptions {
  client: SitecoreClient;
  sites: SiteInfo[];
}

Property

Type

Description

client

SitecoreClient

The Sitecore client instance.

Required

sites

SiteInfo[]

The list of sites to use for robots.txt generation.

Required

Bot detection middleware

This middleware runs bot detection once per request. It detects bots based on the User-Agent, marks the request/response with the sc_bot cookie, and dispatches a dedicated bot page-view event for the resolved site/language. For more information, see Lightweight tracking.

Register this middleware in server.ts using the createBotTrackingMiddleware() factory function.

Options reference

type BotTrackingMiddlewareOptions = Omit<BaseMiddlewareOptions, 'enabled'> & {
  // Mirrors the AngularSitecoreConfig['api']['edge'] section
  api: {
    edge: {
      contextId?: string;
      clientContextId?: string;
      edgeUrl?: string;
    }
  };
  // locales used to extract the language from the request path
  locales?: string[];
  // fallback language when the path has no locale prefix. Default 'en'
  defaultLanguage?: string;
  // fallback site when not resolved by multisite or the site cookie
  defaultSite?: string;
};

Property

Type

Description

contextId

string

Edge context ID. Required to send bot page-view events.

Optional

clientContextId

string

Edge client context ID.

Optional

edgeUrl

string

URL of the SitecoreAI Edge endpoint that bot page-view events are sent to.

Optional

locales

string[]

Locales used to extract the language from the request path.

Optional

defaultLanguage

string

Fallback language when the request path has no locale prefix.

Default: 'en'.

Optional

defaultSite

string

Fallback site name when not resolved by the multisite middleware or the site cookie.

Optional

Note

This middleware does not accept an enabled option. It is skipped automatically for editing/preview requests, non-matching paths, prefetch requests, and on localhost or in a development environment, unless the SITECORE_ENABLE_BOT_TRACKING environment variable is set to true.

Redirects middleware

The Redirects middleware matches the current request against SXA redirect items and redirects the request when there's a matching item.

Register this middleware in server.ts using the createRedirectsMiddleware() factory function.

Note

This logic runs on both server and browser navigation. However, due to Angular routing API limitations, 301/302 redirects produce browser navigation only.

Options reference

type RedirectsMiddlewareOptions = BaseMiddlewareOptions & {
  // Mirrors the SitecoreConfig['redirects'] section
  enabled?: boolean;
  // Mirrors the SitecoreConfig['api']['edge'] section
  contextId?: string;
  clientContextId?: string;
  edgeUrl?: string;
  // Mirrors the SitecoreConfig['api']['local'] section
  apiHost?: string;
  apiKey?: string;
  path?: string;
  // Locales configured for the app (derived from angular.locales)
  locales?: string[];
  defaultLanguage?: string;
  defaultSite?: string;
  // Sites used to resolve the site's default language for the $siteLang token
  sites?: SiteInfo[];
  // Override the redirects service instance (e.g. for testing)
  redirectsService?: RedirectsService;
};

Property

Type

Description

enabled

boolean

Enables or disables the middleware.

Optional

contextId

string

Edge context ID used to fetch redirects, unless local API configuration is provided instead.

Optional

clientContextId

string

Edge client context ID.

Optional

edgeUrl

string

URL of the SitecoreAI Edge endpoint that redirects are fetched from.

Optional

apiHost

string

Local API hostname used to fetch redirects from a local instance instead of Edge.

Optional

apiKey

string

Local API key, used together with apiHost.

Optional

path

string

GraphQL endpoint path appended to apiHost to form the full endpoint URL.

Optional

locales

string[]

Locales configured for the app, used to match locale-versioned redirect rules. Derived from angular.locales.

Optional

defaultLanguage

string

Fallback language when the request path has no locale prefix.

Default: 'en'.

Optional

defaultSite

string

Fallback site name when not resolved by the multisite middleware or the site cookie.

Optional

sites

SiteInfo[]

Sites used to resolve the target site's default language for the $siteLang redirect token.

Optional

redirectsService

RedirectsService

Override the redirects service instance, for example for testing.

Optional

If you have suggestions for improving this article, let us know!