Skip to content
brix.v2.15.0+b120c49

Search documentation

Loading search…

    Documentation menu
    Docs / Integrations / ContentfulRead Markdown
    On this page

    Contentful Type Generation

    Generate deterministic TypeScript types from published Contentful content models, then use the resulting map to type Delivery queries and rendering adapters.

    Generate the model

    #

    Provide CONTENTFUL_CMA_TOKEN through your secret manager or trusted process environment before running the command. Do not paste the token into a checked-in script or shell command history. The command accepts exactly --space, --out, and the optional --environment and --host flags:

    brix contentful typegen \
      --space <space-id> \
      --environment master \
      --out src/contentful-types.ts
    

    --space and --out are required. --environment defaults to master, and parent directories for --out are created. --host defaults to api.contentful.com; pass --host api.eu.contentful.com for a space on Contentful's EU data residency, or a loopback URL for a local mock. Unknown flags are rejected. When --out is inside the project, Brix formats the generated file with the project's oxfmt.config.mts, so brix check passes right after generation. Typegen reads published content types through the Management API's /public/content_types endpoint, so unpublished draft models are excluded. Regenerate after model changes and do not hand-edit the output.

    For each content type, the generated file exports a fields interface and an entry interface named from its ID, for example IBlogPostFields and IBlogPost extends Entry<IBlogPostFields> for blogPost, plus a ContentTypeMap from each content-type ID to its fields interface. Generation:

    • sorts models by ID in code-unit order, so output is identical on every machine and host locale;
    • omits fields marked as omitted and keeps optional fields optional;
    • turns Symbol in validations, including on Symbol arrays, into string-literal unions, escaping quotes, backslashes, and control characters (do not pre-escape the model's values);
    • types Rich Text as RichTextDocument, JSON objects as Record<string, unknown>, asset links as Asset | null, and validated entry links as a nullable union of the linked entry interfaces (Entry<unknown> | null when unvalidated), because unresolved links become null;
    • rejects content-type IDs whose generated entry or fields interface names collide, asking you to rename one model.

    Models without a description or title field, and validations that store null size bounds or regular-expression flags, generate normally. If the Management API returns a malformed model, the validation error names the content-type index and field path.

    After generation, src/contentful-types.ts is the application-owned import point used by the Delivery client and rendering adapter factory. A later model change produces a reviewable diff when you rerun the same command; do not add hand-written exports to this generated file.

    import { createContentfulClient } from "brix/contentful/server";
    import type { ContentTypeMap } from "#/contentful-types.ts";
    
    const contentful = createContentfulClient<ContentTypeMap>({
      spaceId,
      accessToken,
    });
    

    In an application, create this client per request from server configuration as shown in Contentful clients. The map types content-type IDs, fields, filters, clients, and adapter definitions. It is compile-time guidance; Delivery responses still receive structural envelope validation rather than runtime validation against every generated field type.

    Required fields are non-optional because published entries must contain them. Contentful enforces required validations only on publish, so Preview API reads and Live Preview can return drafts that omit them, such as a new entry before its title is typed. Locales configured to allow empty required fields can also omit them on the Delivery API. Adapters that render drafts must tolerate absent required fields, for example entry.fields.title ?? "".

    Use resource types

    #

    Browser-safe brix/contentful exports Entry<T>, Asset, SyncAsset, Link, RichTextDocument, ContentfulCollection<T>, the DeletedEntry and DeletedAsset stubs, content-type schema types, and Contentful system and metadata types. Query option types such as GetEntriesOptions and FieldFilters come from server-only brix/contentful/server with the client.

    The typed client already separates sync output into entries, assets, deletedEntries, and deletedAssets. Use the guards when a value's shape is not known statically, such as a raw direct contract response, an unresolved field value, or an entry carried through untyped props:

    import { isDeletedAsset, isDeletedEntry, isEntry, isLink } from "brix/contentful";
    
    export function describeResource(value: unknown): string {
      if (isEntry(value)) return `entry ${value.sys.id}`;
      if (isDeletedEntry(value) || isDeletedAsset(value)) return `deleted ${value.sys.id}`;
      if (isLink(value)) return `unresolved ${value.sys.linkType} link ${value.sys.id}`;
      return "unknown";
    }
    

    The guards check resource shape and sys.type; they do not infer an application-specific field interface. isLink accepts Entry and Asset links. isAsset validates single-locale Delivery assets with a processed file and does not accept locale-mapped sync assets; read those from the typed assets collection instead. A guard lets you transport an entry without inspecting it. In managed application source, inspect entry fields and sys only in rendering adapters; use the generated map with typed client methods for model-specific fields.