contentful.js

repository·master·Indexed 23 days ago

https://github.com/contentful/contentful.js

A 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.

Tokens
16K
Snippets
41
Records
88
Agent score
80%

What's inside contentful.js

  1. Overview of the Contentful API surface

    master

    The library is organized around the Contentful namespace and the ContentfulClientApi interface. Key capabilities include:

    Core Namespace

    • createClient: Initializes a new client instance.
    • EntryFields and EntryFieldTypes: 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.
  2. How Content Source Maps work with Preview API

    master

    Content 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:

    1. Use the Content Preview API (CPA) by setting the appropriate host (usually preview.contentful.com).
    2. Set includeContentSourceMaps: true in the createClient configuration.
    3. The SDK will include includeContentSourceMaps=true in all CPA requests.
    4. The response will contain CSM metadata which @contentful/content-source-maps uses to decorate string values with hidden metadata for mapping.
  3. How `withAllLocales` affects response types

    master

    When using the withAllLocales client chain modifier, the response type is adjusted to include all existing locales in your space.

    • For getAsset and getAssets, you can provide an optional generic parameter for the locales.
    • For parseEntries, getEntry, and getEntries, you can provide an optional second generic parameter for the locales.

    If a Locale type 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')
  4. How client chain modifiers work

    master

    Introduced in v10.0.0, client chain modifiers allow you to change the shape of the data returned by methods like getEntries, getEntry, getAssets, getAsset, sync, and parseEntries. This provides better type support and predictable data structures.

    Entries Modifiers

    Used with getEntries, getEntry, and parseEntries.

    • 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 getAssets and getAsset.

    • withAllLocales: Returns assets in all locales.
    • Default: Returns assets in a single locale.

    Sync Modifiers

    Used with sync. Note that withAllLocales is 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 })
  5. How the Sync API works

    master

    The Sync API allows for efficient data synchronization by fetching only changes (deltas) since a specific point in time. It supports two modes:

    1. 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 a nextSyncToken.
    2. 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.

  6. How link resolution works

    master

    Link 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 include parameter in your fetch call to resolve links up to 10 layers deep.
    • Disabling resolution: Use the withoutLinkResolution chain modifier on the client to keep raw link objects.
    • Handling unresolvable links: By default, links that cannot be resolved are kept as UnresolvedLink. Use the withoutUnresolvableLinks chain modifier to remove these fields entirely.
  7. How `withoutUnresolvableLinks` affects response types

    master

    The withoutUnresolvableLinks client 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')
  8. How `withoutLinkResolution` affects response types

    master

    Using the withoutLinkResolution client chain modifier prevents the client from resolving linked entities. Instead of returning the resolved object, the response will contain the raw link object containing the type, linkType, and id.

    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')
  9. Migrate to version 10.x: Use Client Chain Modifiers

    master

    Version 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.

    In v10.x, resolveLinks and removeUnresolved are no longer supported as client config options or query parameters for getEntries, getEntry, parseEntries, or initial sync calls.

    • To disable link resolution (previously resolveLinks: false): Use .withoutLinkResolution before your method call.
    • To remove unresolvable links (previously removeUnresolved: true): Use .withoutUnresolvableLinks before your method call.

    Replace locale: '*'

    In v10.x, setting the locale parameter to '*' is no longer supported for getEntries, getEntry, getAssets, getAsset, or initial sync calls.

    • To fetch all locales: Use .withAllLocales before your method call.

    Note: Setting a specific locale (e.g., locale: 'en-US') continues to work as before.

  10. Configure the Contentful client

    master

    Initialize the SDK using createClient(). You must provide a space ID and an accessToken (either for the Content Delivery API (CDA) or the Content Preview API (CPA)).

    Available configuration options:

    ParameterPurposeDefault
    spaceContentful space ID(required)
    accessTokenCDA or CPA access token(required)
    environmentEnvironment ID"master"
    hostAPI hostname"cdn.contentful.com"
    includeContentSourceMapsEnable Content Source Maps (CPA only)false
    timelinePreviewEnable Timeline Preview (CPA only)undefined
    retryOnErrorRetry on 429/5xxtrue
    retryLimitMax retry attempts5
    timeoutConnection timeout (ms)30000

    Note: To use Content Source Maps for visual editing integrations, you must use the CPA and set includeContentSourceMaps: true.

  11. Configure Contentful for React Native, SSR, or Angular Universal

    master

    Depending 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 browser or node variant 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.