contentful-server-lib
v1.1.6
Published
A server-side TypeScript library for fetching, transforming, and serving Contentful content in Next.js applications. It abstracts the Contentful Delivery and Preview APIs behind a layered architecture: raw API access → ETL transformation → page-level asse
Maintainers
Readme
@aligntech-cw/contentful-server-lib2
Overview
A server-side TypeScript library for fetching, transforming, and serving Contentful content in Next.js applications. It abstracts the Contentful Delivery and Preview APIs behind a layered architecture: raw API access → ETL transformation → page-level assembly → Next.js request handling.
Key features:
- Contentful Delivery API (CDA) and Preview API (PDA) support
- ETL pipeline that normalises raw Contentful entries into flat, dependency-resolved
InternalEntryobjects - Page-level service that resolves slugs, redirects (301/302/Rewrite/regex), and feature flags
- Next.js App Router / RSC compatible request handling (Next.js 13–15)
- In-memory caching with configurable TTLs
- S3 fallback for pre-exported content
- Geo-location and geo-based domain redirect support
- Contentful embargoed asset signing (JWT)
- Multi-site / multi-locale routing
- Type-safe public API with full TypeScript types exported
Technologies: TypeScript 5, Contentful SDK v10, Next.js 15, AWS SDK v3 (S3), React 19, axios, jsonwebtoken.
Installation
npm install @aligntech-cw/contentful-server-lib2yarn add @aligntech-cw/contentful-server-lib2Requirements
- Node.js ≥ 18
- TypeScript ≥ 5.0 (if using TypeScript)
- Next.js 13, 14, or 15 (peer dependency for
NextPageService)
Configuration
The library reads configuration from environment variables. Use configService to build typed config objects from them.
| Variable | Description |
|---|---|
| CONTENTFUL_API | cda (default) or pda for Preview API |
| CONTENTFUL_SPACE_ID | Contentful Space ID |
| CONTENTFUL_DELIVERY_TOKEN | Delivery API access token |
| CONTENTFUL_PREVIEW_TOKEN | Preview API access token |
| CONTENTFUL_DELIVERY_API_HOST | Delivery API host (e.g. cdn.contentful.com) |
| CONTENTFUL_PREVIEW_API_HOST | Preview API host (e.g. preview.contentful.com) |
| CONTENTFUL_ENVIRONMENT | Contentful environment (e.g. master) |
| CONTENTFUL_API_OVER_HTTP | true to use HTTP instead of HTTPS |
| CONTENTFUL_BASE_PATH | Optional base path |
| CORE_QUERY_CACHE_TIME | Cache TTL (seconds) for core query |
| SHARED_QUERY_CACHE_TIME | Cache TTL (seconds) for shared query |
| GENERAL_DEFAULT_CACHE_TIME | Default ETL cache TTL in seconds (default 60) |
| GENERAL_MAX_RENDER_DEPTH | Max dependency resolution depth (default 10) |
| GENERAL_USE_S3_CONTENT | true to load content from S3 instead of Contentful |
| GENERAL_ENABLE_FEATURES | true to enable feature-flag filtering |
| GENERAL_USE_HTTPS | true to redirect HTTP → HTTPS |
| GENERAL_ALLOW_ADMIN_MODE | true to allow preview/admin mode |
| GENERAL_ENABLE_GEO_REDIRECT | true to enable geo-based domain redirects |
| GENERAL_ENABLE_GEOLOCATION | true to enable geo-location lookups |
| GENERAL_DISABLE_GEOLOCATION_FOR_HOSTS | Comma-separated hostnames to skip geo-location |
| GEOIP_SERVICE_URL | URL of the geo-IP lookup service |
| GEOIP_SERVICE_TIMEOUT | Timeout in ms for geo-IP requests (default 2000) |
| GEO_COOKIE_NAME | Cookie name for cached geo data (default _geo) |
| GEO_COOKIE_EXPIRE | Geo cookie max-age in ms (default 9000000) |
| GEO_TEST_IP | Override IP for geo testing |
| PREVIEW_DATA_CACHE_TIME | Preview result cache TTL in seconds (default 3600) |
| GENERAL_SECURE_SIGN_ASSET_URLS | true to enable embargoed asset URL signing |
| SECURE_SIGN_ASSET_URLS_EXTENSIONS | Comma-separated file extensions to sign |
| ASSET_URL_LIFETIME_MS | Signed asset URL lifetime in ms (default 600000) |
| ASSET_REQUIRE_LOCAL_COOKIE_FOR_FILE_EXTENSIONS | Comma-separated extensions that require __uid cookie |
| S3_BUCKET_NAME | S3 bucket name |
| S3_KEY_ID | AWS access key ID |
| S3_SECRET | AWS secret access key |
| S3_PATH | S3 path prefix |
| S3_REGION | AWS region (default eu-west-1) |
| DEFAULT_CACHE_TIME | In-memory cache default TTL in seconds (default 60) |
Quick Start
import { configService, NextPageService } from "@aligntech-cw/contentful-server-lib2";
// Build all options from environment variables
const options = configService.getNextPageServiceOptions();
const pageService = new NextPageService(options);
// Inside a Next.js page (App Router)
const [pageResult, helpers] = await pageService.getResultForSlugAndQuery(
"my-page-slug",
{}
);Project Structure
src/
├── services/
│ ├── configService.ts # Builds typed config objects from env vars
│ ├── cacheService.ts # In-memory TTL cache
│ ├── contentfulApiService.ts # Raw Contentful / S3 API calls
│ ├── contentfulEtlService.ts # ETL: raw entries → InternalEntry
│ ├── contentfulPageService.ts# Slug resolution, redirects, page assembly
│ ├── nextPageService.ts # Next.js request handling, geo, preview
│ ├── siteLocaleService.ts # Multi-site / multi-locale routing
│ ├── assetEmbargoService.ts # Embargoed asset URL signing
│ ├── featureService.ts # Feature-flag evaluation
│ ├── geoService.ts # Geo-IP lookup
│ ├── geoRedirectService.ts # Geo-based domain redirect logic
│ └── s3Service.ts # AWS S3 file download
├── types/
│ └── index.ts # All exported TypeScript types
├── util/
│ ├── index.ts # General-purpose utilities
│ ├── etlFuncs.ts # Built-in ETL functions (button, nav, feature)
│ ├── pageSvcFuncs.ts # Header/footer injection, footnote calculation
│ ├── expandRefs.ts # Expand sys-link references in-place
│ ├── renderHelper.tsx # React component renderer factory
│ ├── cookieContext.ts # Cookie read/write abstraction
│ └── simpleHttpContext.ts # Next.js request context wrapper
└── index.ts # Public exportsPublic API
configService
Singleton that reads environment variables and returns typed config objects.
import { configService } from "@aligntech-cw/contentful-server-lib2";
configService.getContentfulApiConfig() // → ContentfulApiConfig
configService.getS3Config() // → S3Config
configService.getContentfulETLConfig() // → ContentfulETLConfig
configService.getContentfulPageConfig(useAllContentQuery: boolean) // → ContentfulPageConfig
configService.getNextPageConfig() // → NextPageConfig
configService.getGeoDataConfig() // → GeoDataConfig
configService.getSiteLocaleConfig(siteConfigs?: SiteConfig[]) // → SiteLocaleConfig
configService.getAssetEmbargoServiceConfig() // → AssetEmbargoServiceConfig
configService.getAssetEmbargoServiceOptions() // → AssetEmbargoServiceOptions
// Convenience: builds the full NextPageServiceOptions from env vars
configService.getNextPageServiceOptions(
siteConfigs?: SiteConfig[],
useAllContentQuery?: boolean,
modifyFn?: (options: NextPageServiceOptions) => NextPageServiceOptions
) // → NextPageServiceOptionscacheService
Singleton in-memory TTL cache.
import { cacheService } from "@aligntech-cw/contentful-server-lib2";
// Get a value, or call getFunc() to populate it
const data = await cacheService.getOrInsertFromCache(
"my-cache-key",
async () => fetchSomething(),
60 // TTL in seconds; -1 uses DEFAULT_CACHE_TIME env var
);
// Direct read (returns null on miss or expiry)
const value = cacheService.get<MyType>("my-cache-key");
// Direct write
cacheService.put("my-cache-key", value, 120);contentulEtlService
Fetches raw Contentful entries and transforms them into ETLEntryQueryResult.
import { contentulEtlService } from "@aligntech-cw/contentful-server-lib2";
import type { ContentfulETLGetEntriesOptions } from "@aligntech-cw/contentful-server-lib2";
// Cached fetch + ETL
const result = await contentulEtlService.getETLEntriesCached(options);
// Uncached fetch + ETL (always hits Contentful)
const result = await contentulEtlService.getETLEntries(options);Both methods accept ContentfulETLGetEntriesOptions and return ETLEntryQueryResult:
type ETLEntryQueryResult = {
items: InternalEntry[];
itemMap: Record<string, InternalEntry>;
itemsPerContentType: Record<string, InternalEntry[]>;
configMap: Record<string, string>; // key→value from "config" content type
featureConditionMap: Record<string, FeatureConditionETLEntry>;
routeData?: ETLEntryRouteData; // slug/redirect maps (when initRouteData=true)
};ContentfulPageService
Resolves a URL slug to a fully assembled ContentfulPageResult, handling redirects, feature flags, and additional entries (header/footer).
import { ContentfulPageService } from "@aligntech-cw/contentful-server-lib2";
import type { ContentfulPageServiceOptions } from "@aligntech-cw/contentful-server-lib2";
const pageService = new ContentfulPageService(options);
// Resolve a page by slug
const pageResult = await pageService.getPageResult("/my-slug", { param: "value" });
// Resolve a single entry by ID (for preview)
const entryResult = await pageService.getEntryResult("entryId");ContentfulPageResult shape:
{
items: EntryEx[]; // root page entry
includes: EntryIncludes; // { Entry: EntryEx[], Asset: AssetEntry[] }
is404: boolean;
redirectLocation?: string;
redirectType?: string; // "301" | "302"
isCustomRedirect?: boolean;
urlParams: Record<string, string>;
modifiedFeatureState?: Record<string, boolean>;
entryDependencyMap?: Record<string, DependencyList>;
}NextPageService
Wraps ContentfulPageService with full Next.js request handling: geo-location, geo redirects, HTTPS redirect, multi-locale routing, preview mode, cookie management, and asset URL signing.
import { NextPageService } from "@aligntech-cw/contentful-server-lib2";
const service = new NextPageService(options); // options: NextPageServiceOptions
// App Router / RSC — uses Next.js async storage internally
const [result, helpers] = await service.getResultForSlugAndQuery("my-slug", query);
// From a Next.js getServerSideProps context
const [result, helpers] = await service.getResultForNextContext(context);
// Preview mode (no slug, uses entryid + locale query params)
const [result, helpers] = await service.getResultForPreview(query);
// Update a cached preview entry (call from a preview webhook API route)
await service.updateCachedPreviewData({ cacheKey: "...", entry: contentfulEntry });
// Access the raw Next.js request from anywhere in the request lifecycle
const req = NextPageService.getNextRequest(); // static methodNextPageResult extends ContentfulPageResult with:
{
site: SiteConfig;
localeId: string;
slug: string;
geoData?: GeoData;
adminMode: boolean;
supportsWebp: boolean;
isIOS: boolean;
isRSC: boolean;
userAgent: string;
cookies: Partial<Record<string, string>>;
isPopup: boolean;
previewCacheKey?: string;
unsentCookies?: CookieData[];
}NextPageResultHelpers:
helpers.getResultForEntry(entryId: string, includeDescendants: boolean): ContentfulPageResultBasesiteLocaleService
Resolves the correct SiteConfig and LocaleConfig for a given request.
import { siteLocaleService } from "@aligntech-cw/contentful-server-lib2";
// Resolve by domain + URL path (used in normal page requests)
const [siteConfig, localeConfig] = siteLocaleService.getSiteLocaleConfigForDomain(
siteLocaleConfig,
"www.example.com",
"/de/my-page"
);
// Resolve by locale ID (used in preview mode)
const [siteConfig, localeConfig] = siteLocaleService.getSiteLocaleConfigForLocale(
siteLocaleConfig,
"de-DE"
);AssetEmbargoService
Generates signed Contentful asset URLs for embargoed content.
import { AssetEmbargoService, configService } from "@aligntech-cw/contentful-server-lib2";
const service = new AssetEmbargoService(configService.getAssetEmbargoServiceOptions());
// Returns a signed URL string, empty string if __uid cookie is missing, or null on error
const signedUrl = await service.getSignedUrl(
"/images/space-id/asset-id/filename.jpg",
{ w: "800" }, // query params (e.g. image transforms)
req.cookies
);expandReferenceLinks
Expands sys link references in EntryEx.fields in-place, replacing link objects with the actual EntryEx or AssetEntry from includes.
import { expandReferenceLinks } from "@aligntech-cw/contentful-server-lib2";
const expandedItems = expandReferenceLinks(pageResult.items, pageResult.includes);
// fields that were { sys: { id: "..." } } are now the full EntryEx objectsgenRenderContentItemComponent
Factory that creates a React render function from a component map, used for server-side rendering of Contentful content trees.
import { genRenderContentItemComponent } from "@aligntech-cw/contentful-server-lib2";
import type { ServerTemplateTypeComponentMap } from "@aligntech-cw/contentful-server-lib2";
const templateMap: ServerTemplateTypeComponentMap = {
content: {
_default: DefaultComponent,
hero: HeroComponent,
},
};
const renderContentItem = genRenderContentItemComponent(templateMap, ["template"]);
// Use inside a server component:
renderContentItem(contentEntry, parentProps, "key");ETLFuncs
Named exports of built-in ETL transform functions. These are registered automatically via configService, but can be used or extended directly.
import { ETLFuncs } from "@aligntech-cw/contentful-server-lib2";
ETLFuncs.ETLNavigationNode // resolves page slug + calculatedUrl for navigationNode entries
ETLFuncs.ETLButton // resolves calculatedUrl, isVideo, isDownload for button entries
ETLFuncs.ETLFeatureCondition // normalises geo/userAgent condition fields into lookup mapsEach function matches the InternalEntryETLFunc signature:
type InternalEntryETLFunc = (
entry: InternalEntry,
itemMap: Record<string, InternalEntry>,
options: ContentfulETLGetEntriesOptions
) => FieldsType;PageServiceFuncs
Helper functions used by ContentfulPageService for additional entry injection and calculated field population.
import { PageServiceFuncs } from "@aligntech-cw/contentful-server-lib2";
// Fetches header + footer entries and injects them into the page entry fields
PageServiceFuncs.getAdditionalEntriesHeaderFooter
// Walks the entry tree and sets ContentCalculatedFields (depth, idx, heading levels, footnote numbers)
PageServiceFuncs.setCalculatedFieldsFootnotes
// Default helper for determining heading counts and reference fields per entry
PageServiceFuncs.defaultEntryFieldHelerutil
General-purpose utility singleton.
import { util } from "@aligntech-cw/contentful-server-lib2";
util.toMap(arr, keyFn, valueFn?, filterFn?) // array → Record
util.groupBy(arr, keyFn, valueFn?, filterFn?) // array → Record<string, T[]>
util.getUniqueItems(arr, keyFn, excludeKeys?) // deduplicate array
util.getNonNullArray(arr) // filter null/undefined
util.formatUrlWithParams(url, params) // append query string
util.createSysLink(id, linkType?) // create { sys: { id, type, linkType } }
util.isSysLink(o) // type guard
util.isObject(o) // plain object check
util.isYoutubeVideoUrl(url) // YouTube URL check
util.isVimeoVideoUrl(url) // Vimeo URL check
util.execAsyncOnce(key, asyncFunc) // deduplicate concurrent async calls
util.visitNotRefExpandedEntriesRecursively(...) // depth-first entry tree traversal
util.addToRegexGlobalMap(rawRegex, re) // cache compiled RegExp
util.getFromRegexGlobalMap(rawRegex, flags?) // retrieve or compile RegExpTypeScript Examples
import type {
NextPageResult,
NextPageResultHelpers,
ContentfulPageResult,
EntryEx,
AssetEntry,
InternalEntry,
ETLEntryQueryResult,
SiteConfig,
LocaleConfig,
SiteLocaleConfig,
ContentfulApiConfig,
ContentfulETLConfig,
ContentfulPageConfig,
NextPageConfig,
NextPageServiceOptions,
ContentfulPageServiceOptions,
AssetEmbargoServiceOptions,
GeoData,
GeoDataConfig,
CookieData,
SysLink,
EntryIncludes,
ContentCalculatedFields,
InternalEntryETLFunc,
RenderContentItemComponentFunc,
ServerContentItemComponentProps,
ServerTemplateTypeComponentMap,
UpdateLivePreviewInput,
} from "@aligntech-cw/contentful-server-lib2";Common Usage Examples
Fetch a page by slug (Next.js App Router)
import { configService, NextPageService } from "@aligntech-cw/contentful-server-lib2";
const service = new NextPageService(
configService.getNextPageServiceOptions([
{ id: "us", domain: "www.example.com", locales: [{ id: "en-US" }] },
])
);
// In a Next.js page component (RSC)
const [pageResult, helpers] = await service.getResultForSlugAndQuery(
"about-us",
{}
);
if (pageResult.is404) { /* handle 404 */ }
if (pageResult.redirectLocation) { /* handle redirect */ }
const pageEntry = pageResult.items[0];Fetch a page with getServerSideProps
export const getServerSideProps = async (context) => {
const [result, helpers] = await service.getResultForNextContext(context);
return { props: { pageResult: result } };
};Preview mode
// URL: /preview?locale=en-US&entryid=abc123
const [result, helpers] = await service.getResultForPreview(query);Update live preview cache (webhook handler)
import type { UpdateLivePreviewInput } from "@aligntech-cw/contentful-server-lib2";
export async function POST(req: Request) {
const input: UpdateLivePreviewInput = await req.json();
await service.updateCachedPreviewData(input);
return new Response("ok");
}Expand entry references for rendering
import { expandReferenceLinks } from "@aligntech-cw/contentful-server-lib2";
const expanded = expandReferenceLinks(pageResult.items, pageResult.includes);
// expanded[0].fields.hero is now an EntryEx, not a SysLinkMulti-site / multi-locale setup
import { configService } from "@aligntech-cw/contentful-server-lib2";
import type { SiteConfig } from "@aligntech-cw/contentful-server-lib2";
const siteConfigs: SiteConfig[] = [
{
id: "us",
domain: "www.example.com",
locales: [{ id: "en-US" }],
},
{
id: "de",
domain: "www.example.de",
locales: [{ id: "de-DE", slugPrefix: "de/" }],
},
];
const options = configService.getNextPageServiceOptions(siteConfigs);Custom ETL function
import { configService } from "@aligntech-cw/contentful-server-lib2";
import type { InternalEntryETLFunc } from "@aligntech-cw/contentful-server-lib2";
const ETLMyContentType: InternalEntryETLFunc = (entry, itemMap, options) => {
return { ...entry.fields, calculatedTitle: entry.fields.title?.toUpperCase() };
};
const options = configService.getNextPageServiceOptions(
undefined,
false,
(opts) => ({
...opts,
etlConfig: {
...opts.etlConfig,
contentTypeEntryEtlFuncMap: {
...opts.etlConfig.contentTypeEntryEtlFuncMap,
myContentType: ETLMyContentType,
},
},
})
);Signed asset URLs (embargoed assets)
import { AssetEmbargoService, configService } from "@aligntech-cw/contentful-server-lib2";
const embargoService = new AssetEmbargoService(
configService.getAssetEmbargoServiceOptions()
);
// In an API route: /api/secureasset/[...path]
const signedUrl = await embargoService.getSignedUrl(
req.params.path.join("/"),
Object.fromEntries(new URL(req.url).searchParams),
req.cookies
);
if (signedUrl) {
return Response.redirect(signedUrl);
}In-memory cache
import { cacheService } from "@aligntech-cw/contentful-server-lib2";
const data = await cacheService.getOrInsertFromCache(
`product-${id}`,
() => fetchProductFromApi(id),
300 // 5 minutes
);Error handling
The library does not throw custom error types. Errors from Contentful, S3, or geo-IP services are caught internally and logged via console.log. Check the return values:
const [result] = await service.getResultForSlugAndQuery(slug, query);
if (result.is404) {
// page not found
}
if (result.redirectLocation) {
// redirect to result.redirectLocation with result.redirectType ("301" | "302")
}
// getSignedUrl returns null on error, empty string when access is denied
const url = await embargoService.getSignedUrl(path, params, cookies);
if (!url) {
// access denied or signing failed
}Build
npm run buildOutput is written to dist/. The package exports dist/src/index.js (CJS) and dist/src/index.d.ts (types).
Testing
npm testNo automated tests are currently configured. The
testcliscript runs a manual CLI test:npm run testcli
Contributing
- Follow the existing TypeScript coding style.
- Add tests for new functionality.
- Update this README when public APIs change.
- Do not expose internal/private methods in
src/index.ts.
Blog Setup Example
This section documents how to build a blog using the existing library APIs. No new APIs are introduced — everything shown here uses additionalQueryConfigs, getAdditionalEntries, buildGetAdditionalEntries, selectAllOfType, and pageResult.additionalEntries as they exist in the library today.
Contentful Content Model
Define three content types in Contentful:
| Content Type | Key Fields |
|---|---|
| blogContainer | slug, title, categories (refs to blogCategory) |
| blogCategory | slug, title, posts (refs to blogPost) |
| blogPost | slug, title, body, category (ref to blogCategory), publishedAt, featured |
The relationship tree:
blogContainer
├── blogCategory (e.g. "Orthodontics")
│ ├── blogPost
│ ├── blogPost
│ └── blogPost
└── blogCategory (e.g. "Invisalign")
├── blogPost
└── blogPostURL Structure
| Route | Content loaded |
|---|---|
| /blog | blogContainer + all blogCategory entries + latest blogPost entries |
| /blog/{category} | blogContainer + selected blogCategory + its blogPost entries |
| /blog/{category}/{post} | blogContainer + selected blogCategory + selected blogPost |
Each route maps to a Contentful page entry whose slug field matches the URL path. The library resolves the slug via the coreQueryConfig route map and fetches the page entry via pageQueryConfig. Blog-specific entries (blogCategory, blogPost) are fetched in parallel as additional entries.
How additionalEntries Works
ContentfulPageConfig.getAdditionalEntries is a hook called by ContentfulPageService after the main page entry is resolved. It receives the assembled pageResult, the raw ETL data, and a helper object.
helper.queryEntries(queryType, selectEntries) issues a Contentful query keyed by queryType. The queryType must match a key in ContentfulPageConfig.additionalQueryConfigs. The selectEntries function receives the full ETLEntryQueryResult for that query and returns the subset of InternalEntry items you want.
All queries issued inside getAdditionalEntries run in parallel. Results are stored on pageResult.additionalEntries as a Record<string, EntryEx[]>, keyed by the resultKey you specify.
Use additionalEntries when:
- You need content that is not part of the page entry's dependency tree (e.g. a global list of blog categories for a sidebar).
- You want to avoid multiple separate Contentful requests from the page component.
- You want the data available on every page result without the page component needing to fetch it.
buildGetAdditionalEntries and selectAllOfType
buildGetAdditionalEntries (from src/util/additionalEntriesUtil.ts) is a factory that takes an array of AdditionalEntriesConfig descriptors and returns a ContentfulPageGetAdditionalEntriesFunc ready to assign to pageConfig.getAdditionalEntries.
Each descriptor has three fields:
type AdditionalEntriesConfig = {
queryType: string; // key in additionalQueryConfigs
resultKey: string; // key under pageResult.additionalEntries
selectEntries: (etlData: ETLEntryQueryResult) => InternalEntry[];
};selectAllOfType(contentType) is a convenience selector that returns every entry of a given content type from an ETL result:
selectAllOfType("blogPost")
// equivalent to: (etlData) => etlData.itemsPerContentType["blogPost"] ?? []Configuration
1. Define additionalQueryConfigs
Add a query config entry for each content type you want to fetch as additional entries. These sit alongside the standard coreQueryConfig, sharedEntriesQueryConfig, and pageQueryConfig.
import { configService, PageServiceFuncs } from "@aligntech-cw/contentful-server-lib2";
import type {
AdditionalEntriesConfig,
NextPageServiceOptions,
} from "@aligntech-cw/contentful-server-lib2";
import { buildGetAdditionalEntries, selectAllOfType } from "./additionalEntriesUtil";
const blogAdditionalConfigs: AdditionalEntriesConfig[] = [
{
queryType: "blogCategory",
resultKey: "blogCategories",
selectEntries: selectAllOfType("blogCategory"),
},
{
queryType: "blogPost",
resultKey: "blogPosts",
selectEntries: selectAllOfType("blogPost"),
},
];
const options = configService.getNextPageServiceOptions(
[{ id: "us", domain: "www.example.com", locales: [{ id: "en-US" }] }],
false,
(opts): NextPageServiceOptions => ({
...opts,
pageConfig: {
...opts.pageConfig,
// Register the Contentful queries for each additional content type.
// The key must match the queryType in blogAdditionalConfigs above.
additionalQueryConfigs: {
blogCategory: {
queries: [
{
"sys.contentType.sys.id": "blogCategory",
include: 1,
},
],
queryUniqueKey: "blogcategory",
},
blogPost: {
queries: [
{
"sys.contentType.sys.id": "blogPost",
include: 1,
order: "-fields.publishedAt",
},
],
queryUniqueKey: "blogpost",
},
},
// Wire up the additional entries fetcher.
// This runs after the page entry is resolved, in parallel for all configs.
getAdditionalEntries: buildGetAdditionalEntries([
// Keep the existing header/footer injection from the default config.
// Replace with your own header/footer config descriptor if needed,
// or omit if your page entries already carry header/footer refs.
...blogAdditionalConfigs,
]),
},
})
);If you also need the default header/footer injection, compose it alongside the blog configs.
buildGetAdditionalEntriesaccepts any number of descriptors and runs them all in parallel.
2. Access additionalEntries in the page result
After getResultForSlugAndQuery (or getResultForNextContext) resolves, pageResult.additionalEntries contains the keyed arrays:
const [pageResult, helpers] = await service.getResultForSlugAndQuery("blog", {});
const blogCategories = pageResult.additionalEntries?.["blogCategories"] ?? [];
const blogPosts = pageResult.additionalEntries?.["blogPosts"] ?? [];Each value is an EntryEx[] — the same shape as pageResult.items and pageResult.includes.Entry.
3. Pass data to page components via pageProps
pageResult.additionalEntries is a plain object on the result. Pass it to your page component however your application layer handles props. A common pattern is to shape it into a pageProps object before handing it to the component:
// app/blog/page.tsx (Next.js App Router)
const [pageResult, helpers] = await service.getResultForSlugAndQuery("blog", {});
const pageProps = {
blogContainer: pageResult.items[0],
blogCategories: pageResult.additionalEntries?.["blogCategories"] ?? [],
blogPosts: pageResult.additionalEntries?.["blogPosts"] ?? [],
};
return <BlogPage pageResult={pageResult} pageProps={pageProps} helpers={helpers} />;The page component receives typed, pre-fetched data without issuing any additional Contentful requests.
4. Derive extraProps from additionalEntries
extraProps is a consumer-side convention — not a library type — for grouping derived or filtered views of additionalEntries before passing them to a component. Populate it in the same place you build pageProps:
const allPosts = pageResult.additionalEntries?.["blogPosts"] ?? [];
const allCategories = pageResult.additionalEntries?.["blogCategories"] ?? [];
const extraProps = {
latestPosts: allPosts.slice(0, 5),
featuredPosts: allPosts.filter((p) => p.fields.featured === true),
blogCategories: allCategories,
};
const pageProps = {
blogContainer: pageResult.items[0],
...extraProps,
};extraProps values are derived in the server component / getServerSideProps handler, not inside the library. They are passed to page components as regular props.
Complete Blog Example
Contentful structure
blogContainer (slug: "blog")
├── Categories
│ ├── Orthodontics (slug: "blog/orthodontics")
│ ├── Invisalign (slug: "blog/invisalign")
│ └── News (slug: "blog/news")Each blogPost has a slug such as blog/orthodontics/invisible-braces.
Route examples
/blog → blogContainer page
/blog/orthodontics → blogCategory page
/blog/orthodontics/invisible-braces → blogPost pageFull configuration
import {
configService,
NextPageService,
PageServiceFuncs,
} from "@aligntech-cw/contentful-server-lib2";
import type {
AdditionalEntriesConfig,
NextPageServiceOptions,
} from "@aligntech-cw/contentful-server-lib2";
import { buildGetAdditionalEntries, selectAllOfType } from "./additionalEntriesUtil";
const blogAdditionalConfigs: AdditionalEntriesConfig[] = [
{
queryType: "blogCategory",
resultKey: "blogCategories",
selectEntries: selectAllOfType("blogCategory"),
},
{
queryType: "blogPost",
resultKey: "blogPosts",
selectEntries: selectAllOfType("blogPost"),
},
];
const options = configService.getNextPageServiceOptions(
[{ id: "us", domain: "www.example.com", locales: [{ id: "en-US" }] }],
false,
(opts): NextPageServiceOptions => ({
...opts,
pageConfig: {
...opts.pageConfig,
additionalQueryConfigs: {
blogCategory: {
queries: [{ "sys.contentType.sys.id": "blogCategory", include: 1 }],
queryUniqueKey: "blogcategory",
},
blogPost: {
queries: [
{
"sys.contentType.sys.id": "blogPost",
include: 1,
order: "-fields.publishedAt",
},
],
queryUniqueKey: "blogpost",
},
},
getAdditionalEntries: buildGetAdditionalEntries(blogAdditionalConfigs),
setCalculatedFields: PageServiceFuncs.setCalculatedFieldsFootnotes,
},
})
);
export const blogService = new NextPageService(options);Fetching data for /blog
// app/blog/page.tsx
import { blogService } from "@/lib/blogService";
export default async function BlogPage() {
const [pageResult, helpers] = await blogService.getResultForSlugAndQuery(
"blog",
{}
);
if (pageResult.is404) return notFound();
if (pageResult.redirectLocation) redirect(pageResult.redirectLocation);
const allPosts = pageResult.additionalEntries?.["blogPosts"] ?? [];
const allCategories = pageResult.additionalEntries?.["blogCategories"] ?? [];
const pageProps = {
blogContainer: pageResult.items[0],
blogCategories: allCategories,
extraProps: {
latestPosts: allPosts.slice(0, 10),
featuredPosts: allPosts.filter((p) => p.fields.featured === true),
},
};
return <BlogIndexPage pageResult={pageResult} pageProps={pageProps} helpers={helpers} />;
}Fetching data for /blog/{category}
// app/blog/[category]/page.tsx
import { blogService } from "@/lib/blogService";
export default async function BlogCategoryPage({
params,
}: {
params: { category: string };
}) {
const slug = `blog/${params.category}`;
const [pageResult, helpers] = await blogService.getResultForSlugAndQuery(slug, {});
if (pageResult.is404) return notFound();
const allPosts = pageResult.additionalEntries?.["blogPosts"] ?? [];
const allCategories = pageResult.additionalEntries?.["blogCategories"] ?? [];
// The page entry IS the blogCategory entry for this slug.
const selectedCategory = pageResult.items[0];
const pageProps = {
blogContainer: allCategories[0]?.fields.blogContainer ?? null,
selectedCategory,
blogCategories: allCategories,
extraProps: {
categoryPosts: allPosts.filter(
(p) => p.fields.category?.sys?.id === selectedCategory?.id
),
},
};
return <BlogCategoryPage pageResult={pageResult} pageProps={pageProps} helpers={helpers} />;
}Fetching data for /blog/{category}/{post}
// app/blog/[category]/[post]/page.tsx
import { blogService } from "@/lib/blogService";
export default async function BlogPostPage({
params,
}: {
params: { category: string; post: string };
}) {
const slug = `blog/${params.category}/${params.post}`;
const [pageResult, helpers] = await blogService.getResultForSlugAndQuery(slug, {});
if (pageResult.is404) return notFound();
const allPosts = pageResult.additionalEntries?.["blogPosts"] ?? [];
const allCategories = pageResult.additionalEntries?.["blogCategories"] ?? [];
const selectedPost = pageResult.items[0];
const selectedCategory = allCategories.find(
(c) => c.id === selectedPost?.fields.category?.sys?.id
);
const pageProps = {
selectedPost,
selectedCategory,
blogCategories: allCategories,
extraProps: {
// Related posts: same category, excluding the current post
relatedPosts: allPosts
.filter(
(p) =>
p.fields.category?.sys?.id === selectedCategory?.id &&
p.id !== selectedPost?.id
)
.slice(0, 3),
},
};
return <BlogPostPage pageResult={pageResult} pageProps={pageProps} helpers={helpers} />;
}Example response shape
The assembled data available to your page component looks like this:
{
// Standard NextPageResult fields
items: [{ id: "abc", contentType: "page", fields: { slug: "blog/orthodontics/invisible-braces", ... } }],
includes: { Entry: [...], Asset: [...] },
is404: false,
urlParams: {},
site: { id: "us", domain: "www.example.com", locales: [...] },
localeId: "en-US",
slug: "blog/orthodontics/invisible-braces",
// Populated by buildGetAdditionalEntries
additionalEntries: {
blogCategories: [
{ id: "cat1", contentType: "blogCategory", fields: { slug: "blog/orthodontics", title: "Orthodontics" } },
{ id: "cat2", contentType: "blogCategory", fields: { slug: "blog/invisalign", title: "Invisalign" } },
],
blogPosts: [
{ id: "post1", contentType: "blogPost", fields: { slug: "blog/orthodontics/invisible-braces", title: "Invisible Braces", featured: true, publishedAt: "2024-06-01" } },
{ id: "post2", contentType: "blogPost", fields: { slug: "blog/orthodontics/retainers", title: "Retainers", featured: false, publishedAt: "2024-05-15" } },
],
},
// Shaped by the consumer before passing to the component
// (pageProps and extraProps are not library types — they are your own conventions)
// pageProps: {
// selectedPost: { ... },
// selectedCategory: { ... },
// blogCategories: [ ... ],
// extraProps: {
// relatedPosts: [ ... ],
// },
// }
}Blog Best Practices
- Use
additionalQueryConfigs+buildGetAdditionalEntriesinstead of issuing separate Contentful requests from page components. All additional queries run in parallel with a single round-trip per query type. - Keep
selectEntriesfunctions pure and cheap — they receive the already-fetched ETL result and should only filter, not fetch. - Use
selectAllOfTypefor simple full-type fetches. Write a customselectEntriesfunction when you need to filter by a field value at selection time. - Shape
pagePropsandextraPropsin the server component orgetServerSidePropshandler, not inside the library. This keeps page components independent of Contentful query logic. - Reuse the same
blogServiceinstance across all blog routes. The ETL layer caches results byqueryUniqueKey, soblogCategoryandblogPostqueries are only issued once per cache TTL regardless of how many routes are rendered. - Keep
queryUniqueKeyvalues stable and unique across alladditionalQueryConfigs. Changing a key invalidates the cache for that query type. - Keep routing consistent: use
blog/{category}andblog/{category}/{post}slug patterns in Contentful so the library's slug-to-ID map resolves them correctly without custom redirect rules. - Pass
additionalEntriesdata throughpagePropsrather than reading it directly in deeply nested components. This makes data flow explicit and keeps components testable.
