Type-Safe Contentstack: TypeScript SDK and Generated Types

Catch content model mismatches before production

A content type changes, a field gets renamed, and your frontend silently renders undefined. TypeScript types generated from your content model catch this at build time.

Generate Types

The Contentstack CLI can generate TypeScript interfaces from your stack's content types:

csdx tsgen -a "delivery-token-alias" -o "types/contentstack.d.ts"

You get interfaces like:

export interface BlogPost {
  uid: string;
  title: string;
  url: string;
  summary?: string;
  author: Author[];
  body: any; // JSON RTE
}

Typed Queries

import contentstack from '@contentstack/delivery-sdk';
import type { BlogPost } from '../types/contentstack';

const stack = contentstack.stack({
  apiKey: process.env.CS_API_KEY!,
  deliveryToken: process.env.CS_DELIVERY_TOKEN!,
  environment: 'production',
});

const result = await stack.contentType('blog_post').entry().find<BlogPost>();
result.entries?.forEach((post) => console.log(post.title));

Keep Types in Sync

  • Regenerate types in CI after content model changes
  • Fail the build if generated types differ from committed types
  • Combine with branches: generate types from the feature branch during development

Benefits

  • Autocomplete for fields
  • Compile-time errors when fields change
  • Self-documenting content models

Generated types turn your content model into a contract between editors and developers.

Arivanandhan Chitheshwaran