Contentful Management JS Client

repository·master·Indexed 43 days ago

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

A JavaScript client for interacting with the Contentful Content Management API (CMA). It enables developers to programmatically manage content, assets, content types, and environments. The library features a flat API surface for direct endpoint access, cursor-based pagination for collections, and integration with the Contentful App Framework via a pluggable adapter system.

Tokens
18.6K
Snippets
58
Records
88
Agent score
55%

What's inside Contentful Management JS

  1. Understand the contentful-management support policy

    master

    The support lifecycle for contentful-management is divided into three stages based on the major version in use:

    1. Active Support: The latest major version receives all new features, enhancements, bug fixes, security patches, and performance improvements.
    2. Maintenance Period: For 6 months after a new major version is released, the previous major version receives only critical bug fixes and security vulnerability patches. No new features or minor improvements are backported.
    3. End of Life (EOL): After the 6-month maintenance period, versions no longer receive any updates, including security patches. While existing installations will continue to function, unresolved issues can only be addressed by upgrading to a supported version.

    Current Version Support Status:

    • v12.x: Active
    • v11.x: Maintenance (ends 6 months after v12 release)
    • v10.x and earlier: End of Life
  2. Understand the request lifecycle

    master

    Every call to the Content Management API (CMA) follows a four-stage pipeline:

    1. createClient(): Builds the user-agent, initializes the adapter, and selects the client surface (Plain or Legacy).
    2. Client Surface: The Plain or Legacy client produces a MakeRequestOptions object containing { entityType, action, params, payload, headers, userAgent } via a makeRequest(opts) closure.
    3. Adapter.makeRequest: The adapter (typically RestAdapter) uses an axios instance to handle the request, including built-in rate limiting and retries.
    4. Endpoint Lookup: The adapter resolves the entityType and action against a registry to determine the specific HTTPS endpoint and method (GET, POST, etc.) to call api.contentful.com.
  3. ESM target updated to 2021

    master

    The library now targets ECMAScript 2021. Babel transpilation for older JavaScript versions has been removed. Modern features like optional chaining (?.), nullish coalescing (??), and Promise.any() are used directly.

    Affected environments:

    • Internet Explorer (all versions)
    • Chrome < 85
    • Firefox < 79
    • Safari < 14
    • Edge < 85
    • Node.js < 14.17

    If you must support these environments, you will need to add an additional transpilation step (e.g., using Babel) to your build process.

  4. Choose between the Plain Client and the Legacy (Chained) Client

    master

    Starting with v12, the contentful-management SDK provides two distinct client surfaces. You must choose the one that matches your existing code patterns or architectural needs.

    Plain Client (Default)

    Recommended for most use cases, especially non-linear code like front-end applications.

    • Structure: A flat namespace where you call actions directly on the client: client.<entity>.<action>(params).
    • Return Value: Returns plain JSON objects.
    • Benefits:
      • Reach any CMA endpoint without awaiting intermediate async requests.
      • Easier to serialize (no non-enumerable methods).
      • Supports scoping at construction time via defaults (spaceId, environmentId, etc.).
      • Required for @contentful/app-sdk@4 integration.
    • Note: Newer features (like Experiences/ExO entities) are only available on the Plain Client.

    Legacy Client (Chained/Nested)

    • Structure: A sequence of nested requests: client.getSpace(id) → space.getEnvironment(id) → environment.getEntries().
    • Return Value: Returns entity objects with attached methods.
    • Status: Deprecated. It will be removed in the next major version. Using it will trigger a console.warn.
    // Using the Plain Client (Default)
    import { createClient } from 'contentful-management';
    const client = createClient({ accessToken: '...' });
    const entries = await client.environment.entries.list({ spaceId: '...', environmentId: '...' });
    
    // Using the Legacy Client (Explicitly requested)
    const legacyClient = createClient({ accessToken: '...' }, { type: 'legacy' });
    const space = await legacyClient.getSpace('...');
    const env = await space.getEnvironment('...');
  5. Identify experimental features subject to breaking changes

    master

    The following APIs are currently experimental and may change without notice:

    • AI Agents: getAgent, getAgents, getAgentRun, getAgentRuns, generateWithAgent, resumeAgentRun.
    • Experiences: componentType, template, fragment, experience, dataAssembly, designToken.
  6. Use a pluggable adapter to replace the REST transport

    master

    The SDK allows you to replace the default RestAdapter with a custom implementation of the Adapter interface. This is useful for:

    • Contentful Apps: Passing sdk.cmaAdapter as the apiAdapter to proxy requests through the host web app.
    • Unit Testing: Providing a mock adapter to avoid network calls.

    To use a custom adapter, pass an object containing apiAdapter in the createClient options. This is mutually exclusive with providing RestAdapterParams (like accessToken).

    // Example: Using a custom adapter (e.g., in a Contentful App)
    const client = createClient({
      apiAdapter: sdk.cmaAdapter
    });
  7. Switch from nested to plain client by default

    master

    In v12, createClient returns the plain client by default. The legacy nested client is deprecated and will be removed in the next major version.

    Migration:

    • Recommended: Migrate your code to use the plain client API.
    • To keep using the legacy client: Explicitly pass { type: 'legacy' } in the options.
    // Before - implicitly used nested client
    const client = createClient({ accessToken: 'token' })
    
    // After - explicitly request legacy nested client
    const client = createClient({ accessToken: 'token' }, { type: 'legacy' })
  8. Install contentful-management

    master

    You can install the library via npm or yarn for Node.js environments, or include it via a script tag for browser usage.

    Node.js

    Use npm:

    npm install contentful-management

    Use yarn:

    yarn add contentful-management

    Browser

    Include the library via jsDelivr using a script tag. It is recommended to specify a version to ensure stability.

    <script src="https://cdn.jsdelivr.net/npm/contentful-management@12"></script>

    When using the script tag, the library is accessible via the global contentfulManagement variable.

  9. Use the client in a Contentful App

    master

    When building apps for the Contentful App Framework using @contentful/app-sdk, you should use the provided apiAdapter to make requests. This allows your app to access space-environment scoped entities securely without exposing a management token.

    const contentfulApp = require('@contentful/app-sdk')
    const contentful = require('contentful-management')
    
    contentfulApp.init((sdk) => {
      const cma = contentful.createClient(
        { apiAdapter: sdk.cmaAdapter },
        {
          defaults: {
            environmentId: sdk.ids.environmentAlias ?? sdk.ids.environment,
            spaceId: sdk.ids.space,
          },
        },
      )
    
      // ...rest of initialization code
    })

    Note: Requests issued via the sdk.cmaAdapter count towards the same rate-limiting quota as other APIs exposed by the App SDK.

  10. Migrate from Legacy to Plain Client

    master

    If you are upgrading to v12 or later and your code relies on the nested/chained client pattern (e.g., client.getSpace(id).getEnvironment(id)), your code will break because createClient() now defaults to the Plain Client.

    To restore the old behavior temporarily, you must explicitly pass { type: 'legacy' } as the second argument to createClient.

    Warning: The legacy client is scheduled for removal in the next major version. You should plan to migrate your logic to the Plain Client's flat namespace as soon as possible.

    // BREAKING CHANGE: This used to return a nested client, now it returns a plain client
    // const client = createClient({ accessToken }); 
    
    // FIX for existing code: 
    const client = createClient({ accessToken }, { type: 'legacy' });
  11. Importing Types from 'contentful-management/types'

    master

    The exports field in package.json now restricts access to internal modules. If you are using contentful-management/types and encounter errors, you have two options:

    Option 1: Update tsconfig.json Set moduleResolution to a modern value like node16, nodenext, or bundler.

    {
      "compilerOptions": {
        "moduleResolution": "node16"
      }
    }

    Option 2: Import from the main package Import types directly from contentful-management instead of the /types subpath.

    // Instead of
    import type { Space } from 'contentful-management/types'
    
    // Use
    import type { Space } from 'contentful-management'