contentful.js
repository·master·Indexed 23 days ago
https://github.com/contentful/contentful.jsA JavaScript library for interacting with Contentful's Content Delivery API and Content Preview API. It enables developers to retrieve structured content, implement cursor-based pagination, and manage link resolution. The SDK supports modern ESM, legacy CommonJS, and direct browser usage via CDN, with specialized configurations for React Native, SSR, and Angular Universal.
What's inside contentful.js
- contentful.js is a JavaScript and TypeScript library designed to interact with the Contentful Content Delivery API and Content Preview API. It provides a programmatic interface for fetching content, assets, and metadata from your Contentful space.
Overview of the Contentful API surface
masterThe library is organized around the
Contentfulnamespace and theContentfulClientApiinterface. Key capabilities include:Core Namespace
createClient: Initializes a new client instance.EntryFieldsandEntryFieldTypes: Types used for defining and interacting with entry data.
Client API Methods
Once a client is created, you can use the following methods to interact with the Contentful APIs:
- Entries:
getEntries,getEntry,parseEntries. - Assets:
getAssets,getAsset,createAssetKey. - Content Types:
getContentTypes,getContentType. - Metadata & Organization:
getSpace,getLocales,getTags,getTag. - Synchronization:
sync.
How Content Source Maps work with Preview API
masterContent Source Maps (CSM) enable visual editing integrations (like Live Preview SDK or Vercel Content Link) by mapping field values back to their source entries.
To use them:
- Use the Content Preview API (CPA) by setting the appropriate
host(usuallypreview.contentful.com). - Set
includeContentSourceMaps: truein thecreateClientconfiguration. - The SDK will include
includeContentSourceMaps=truein all CPA requests. - The response will contain CSM metadata which
@contentful/content-source-mapsuses to decorate string values with hidden metadata for mapping.
- Use the Content Preview API (CPA) by setting the appropriate
How `withAllLocales` affects response types
masterWhen using the
withAllLocalesclient chain modifier, the response type is adjusted to include all existing locales in your space.- For
getAssetandgetAssets, you can provide an optional generic parameter for the locales. - For
parseEntries,getEntry, andgetEntries, you can provide an optional second generic parameter for the locales.
If a
Localetype is provided, field values will be mapped to the locale keys (e.g.,fieldValue: { 'en-US': 'value', 'de-DE': 'value' }).import * as contentful from 'contentful' const client = contentful.createClient({ space: '<space-id', accessToken: '<content-delivery-token>', }) type ProductEntrySkeleton = { fields: { productName: contentful.EntryFieldTypes.Text } contentTypeId: 'product' } type Locales = 'en-US' | 'de-DE' const entry = client.withAllLocales.getEntry<ProductEntrySkeleton, Locales>('some-entry-id')- For
How client chain modifiers work
masterIntroduced in
v10.0.0, client chain modifiers allow you to change the shape of the data returned by methods likegetEntries,getEntry,getAssets,getAsset,sync, andparseEntries. This provides better type support and predictable data structures.Entries Modifiers
Used with
getEntries,getEntry, andparseEntries.withAllLocales: Returns entries in all locales.withoutLinkResolution: All linked entries will be rendered as link objects.withoutUnresolvableLinks: Removes link objects if the linked entries are not resolvable.withLocaleBasedPublishing: Returns only content from published locales.- Default: Returns entries in a single locale with resolvable links inlined.
Assets Modifiers
Used with
getAssetsandgetAsset.withAllLocales: Returns assets in all locales.- Default: Returns assets in a single locale.
Sync Modifiers
Used with
sync. Note thatwithAllLocalesis accepted but ignored because the Sync API always retrieves all localized content.withoutLinkResolution: Linked content will be rendered as link objects.withoutUnresolvableLinks: Removes link objects if the linked content is not resolvable.- Default: Returns content in all locales.
You can chain multiple modifiers together.
// returns entries in one locale, resolves linked entries, removing unresolvable links const entries = await client.withoutUnresolvableLinks.getEntries() // returns entries in all locales, resolves linked entries, removing unresolvable links const entries = await client.withoutLinkResolution.withAllLocales.getEntries() // returns parsed entries in all locales const entries = client.withAllLocales.parseEntries(localizedData) // returns assets in all locales const assets = await client.withAllLocales.getAssets() // returns content in all locales, resolves linked entries, removing unresolvable links const { entries, assets, deletedEntries, deletedAssets } = await client.withoutUnresolvableLinks.sync({ initial: true })How the Sync API works
masterThe Sync API allows for efficient data synchronization by fetching only changes (deltas) since a specific point in time. It supports two modes:
- Initial Sync: Fetches the full state of your content. Use
client.sync({ initial: true }). This returns entries, assets, deleted entries, and deleted assets, along with anextSyncToken. - Incremental Sync: Fetches only the changes that occurred after the last sync. Use
client.sync({ nextSyncToken: 'YOUR_TOKEN' })using the token received from the previous sync.
The SDK handles the orchestration of paginated sync responses automatically.
- Initial Sync: Fetches the full state of your content. Use
How link resolution works
masterLink resolution allows the SDK to automatically inline the content of linked or referenced entries into the response object, rather than just returning a link object with an ID. This makes parsing responses easier as you don't have to manually fetch every linked entry.
- Default behavior: Links are resolved one level deep.
- Deep resolution: Use the
includeparameter in your fetch call to resolve links up to 10 layers deep. - Disabling resolution: Use the
withoutLinkResolutionchain modifier on the client to keep raw link objects. - Handling unresolvable links: By default, links that cannot be resolved are kept as
UnresolvedLink. Use thewithoutUnresolvableLinkschain modifier to remove these fields entirely.
How `withoutUnresolvableLinks` affects response types
masterThe
withoutUnresolvableLinksclient chain modifier ensures that the returned type does not include linked entries that cannot be resolved (e.g., if the linked entity is deleted or not yet published). In these cases, the field will effectively be empty in the resulting object.import * as contentful from 'contentful' const client = contentful.createClient({ space: '<space-id>', accessToken: '<content-delivery-token>', }) type ProductEntrySkeleton = { contentTypeId: 'product' fields: { productName: contentful.EntryFieldTypes.Text image: contentful.EntryFieldTypes.AssetLink price: contentful.EntryFieldTypes.Number } } type ReferencedProductEntrySkeleton = { fields: { relatedProduct: contentful.EntryFieldTypes.EntryLink<ProductEntrySkeleton> } contentTypeId: 'referencedProduct' } const entry = client.withoutUnresolvableLinks.getEntry<ReferencedProductEntrySkeleton>('some-entry-id')How `withoutLinkResolution` affects response types
masterUsing the
withoutLinkResolutionclient chain modifier prevents the client from resolving linked entities. Instead of returning the resolved object, the response will contain the raw link object containing thetype,linkType, andid.import * as contentful from 'contentful' const client = contentful.createClient({ space: '<space-id>', accessToken: '<content-delivery-token>', }) type ProductEntrySkeleton = { contentTypeId: 'product' fields: { productName: contentful.EntryFieldTypes.Text image: contentful.EntryFieldTypes.AssetLink price: contentful.EntryFieldTypes.Number } } type ReferencedProductEntrySkeleton = { fields: { relatedProduct: contentful.EntryFieldTypes.EntryLink<ProductEntrySkeleton> } contentTypeId: 'referencedProduct' } const entry = client.withoutLinkResolution.getEntry<ReferencedProductEntrySkeleton>('some-entry-id')Migrate to version 10.x: Use Client Chain Modifiers
masterVersion 10.0.0 is a TypeScript rewrite that replaces several configuration options and query parameters with client chain modifiers. This change provides better type support for different response shapes.
Replace
resolveLinksandremoveUnresolvedIn v10.x,
resolveLinksandremoveUnresolvedare no longer supported as client config options or query parameters forgetEntries,getEntry,parseEntries, or initialsynccalls.- To disable link resolution (previously
resolveLinks: false): Use.withoutLinkResolutionbefore your method call. - To remove unresolvable links (previously
removeUnresolved: true): Use.withoutUnresolvableLinksbefore your method call.
Replace
locale: '*'In v10.x, setting the
localeparameter to'*'is no longer supported forgetEntries,getEntry,getAssets,getAsset, or initialsynccalls.- To fetch all locales: Use
.withAllLocalesbefore your method call.
Note: Setting a specific locale (e.g.,
locale: 'en-US') continues to work as before.- To disable link resolution (previously
Configure the Contentful client
masterInitialize the SDK using
createClient(). You must provide aspaceID and anaccessToken(either for the Content Delivery API (CDA) or the Content Preview API (CPA)).Available configuration options:
Parameter Purpose Default spaceContentful space ID (required) accessTokenCDA or CPA access token (required) environmentEnvironment ID "master"hostAPI hostname "cdn.contentful.com"includeContentSourceMapsEnable Content Source Maps (CPA only) falsetimelinePreviewEnable Timeline Preview (CPA only) undefinedretryOnErrorRetry on 429/5xx trueretryLimitMax retry attempts 5timeoutConnection timeout (ms) 30000Note: To use Content Source Maps for visual editing integrations, you must use the CPA and set
includeContentSourceMaps: true.Configure Contentful for React Native, SSR, or Angular Universal
masterDepending on your environment, you may need specific configurations:
React Native & Server Side Rendering (SSR)
While webpack usually handles this automatically, you can explicitly require the
browserornodevariant if needed:const contentful = require('contentful/dist/contentful.browser.min.js')Angular Universal
To use the SDK with Angular Universal SSR, you must provide a custom Axios adapter, such as
ngx-axios-adapter.