@scayle/storefront-cms-contentful
v1.0.0
Published
Contentful CMS provider integration for the SCAYLE Storefront Application V3
Maintainers
Keywords
Readme
@scayle/storefront-cms-contentful
Contentful CMS provider integration for the SCAYLE Storefront Application V3.
Requires Storefront Application V3. This package implements
CMSProviderServicefrom@scayle/storefront. Controllers resolve the constructed provider from theServiceRegistryand callfetchPageData/fetchListingPageDatadirectly. It has no standalone use outside a Storefront Application V3 project.
Package entrypoint
| Export | Use |
| --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| ContentfulCMSService | CMSProviderService implementation. Generic over your generated Contentful content-type shape (TPageData), defaulting to MinimalContentfulPageData so the package builds standalone. Manages delivery and preview API clients. |
| MinimalContentfulPageData | Minimal interface for the { entry, previewSource? } page payload envelope the service produces. |
| isUnconfiguredLocaleError | Predicate identifying a Contentful BadRequest "Unknown locale" error, used for the locale-fallback retry. |
| cspConfig | CMSCspConfig for the Contentful web app: iframe embedding, editor scripts, Live Preview worker, and API connect rules. |
See Contentful's Content Delivery API documentation
and the contentful SDK docs
for the underlying client.
Configuration
ContentfulCMSService requires four configuration fields. The Storefront Application reads these from environment variables via getRequiredEnv (or, for draftContentEnabled, a bare process.env read since it has a default) in src/server/cms/providers/contentful/service.ts. See .env.example for the variable names.
| Field | Required | Purpose | Tenant setup location | Documentation |
| --------------------- | -------- | --------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------- |
| accessToken | Yes | Content Delivery API access token used to authenticate published-content requests | Settings → API keys → select or create an API key → copy the Content Delivery API - access token field | Authentication |
| space | Yes | Contentful space ID that identifies the CMS workspace | Settings → API keys → shown in the list, or Settings → General settings → space ID field | API keys |
| previewAccessToken | Yes | Content Preview API access token used to authenticate draft-content requests | Settings → API keys → select or create an API key → copy the Content Preview API - access token field | Authentication |
| draftContentEnabled | Yes | Whether draft/unpublished content may be served during an editor session | Set via the storefront's own STOREFRONT_CMS_ALLOW_DRAFTS environment variable, not a Contentful setting | — |
These values map to environment variables as CONTENTFUL_CMS_ACCESS_TOKEN, CONTENTFUL_CMS_SPACE, CONTENTFUL_CMS_PREVIEW_ACCESS_TOKEN, and STOREFRONT_CMS_ALLOW_DRAFTS respectively.
Usage
The Storefront Application instantiates ContentfulCMSService directly in
src/server/cms/providers/contentful/service.ts and binds TPageData to its generated CMSPageData type:
import { ContentfulCMSService } from '@scayle/storefront-cms-contentful'
import type { CMSPageData } from '@shared/types/cms/contentful'
export const createCMSService = (storefront: StorefrontContext) =>
new ContentfulCMSService<CMSPageData>(
{
accessToken: getRequiredEnv('CONTENTFUL_CMS_ACCESS_TOKEN'),
space: getRequiredEnv('CONTENTFUL_CMS_SPACE'),
previewAccessToken: getRequiredEnv('CONTENTFUL_CMS_PREVIEW_ACCESS_TOKEN'),
draftContentEnabled:
process.env.STOREFRONT_CMS_ALLOW_DRAFTS?.toLowerCase() === 'true',
},
storefront,
)The storefront context is used for the service's own application-level caching.
The Storefront Application registers createCMSService(storefront) as the cms slot on the ServiceRegistry
(src/server/registries.ts), alongside every other domain. A controller resolves it from there and
calls fetchPageData/fetchListingPageData with this.request (the inbound IncomingRequest):
const pageData = await this.services.cms.fetchPageData(slug, this.request)See @scayle/storefront's CMS module for the CMSProviderService contract this package implements.
Architecture
ContentfulCMSService implements CMSProviderService directly — there is no shared base class. Each
provider package owns its own caching, error handling, and constructor validation, so this package can
diverge from Storyblok/Contentstack without a @scayle/storefront release touching them:
fetchPageDataandfetchListingPageDatawrap the raw fetch with application-level caching (context.cache.getOrSet(...), 5-minute TTL, bypassed entirely in preview mode) under the cache-key patternscms:contentful:page:${slug}:${locale}andcms:contentful:plp:${categoryId}:${locale}. The raw fetches query Contentful'sPageComponentandproductListingPageComponentcontent types byfields.slug, retrying once without alocalefilter when Contentful reports the requested locale is unconfigured in the space (the retry happens inside the cached fetch, so it's still cached once under the originally requested locale's key).fetchListingPageDataalso converts aCMSContentNotFoundErrorintoundefined, and rethrows any other error for the caller to log. The query itself comes frombuildPageQuery/buildListingQuery, and the response shape fromtransformPageResponse, bothprotectedso a subclass can override just one without touching the retry or 404 handling around them.- Two lazily initialized static singleton clients: a delivery client for published content and a preview
client (using
CONTENTFUL_CMS_PREVIEW_ACCESS_TOKEN) for draft content, selected per request based on the request's editor-mode state combined withdraftContentEnabled. Both go through@scayle/storefront/cms'swrapClientInit, so a bad space ID or token fails with a message naming the client and the env var to check, not a bare SDK error. - Preview responses run through
contentful-resolve-responseto resolve linked entries that the preview API otherwise returns unresolved. isEditorModedetects Contentful's live preview via the_editorModequery parameter.
Extending and customizing
In your project, all customization happens in the Storefront Application's
src/server/cms/providers/contentful/service.ts, by subclassing ContentfulCMSService. The class is concrete, so a project that needs no change uses it as is:
- Query shape: override
buildPageQuery(slug, locale)orbuildListingQuery(slug, locale)to query a different content type or field name than the defaultPageComponent/fields.slugshape, without touching client selection, locale-fallback retry, or 404 handling. - Response shape: override
transformPageResponse(response, useDraftContent)to keep additional response fields beyond what the default extraction produces. - CSP rules: re-export a modified
cspConfig(imported from this package as a base) if your Contentful space uses a different domain or needs additional directives.
Do not reimplement fetchPageData or fetchListingPageData from scratch. Override only the method that
needs to change and call super for everything else, so your subclass tracks fixes made to this
package.
