Contentful is a JavaScript client library for accessing Contentful's Content Delivery API and Content Preview API. It enables developers to easily retrieve and work with content stored in Contentful spaces from JavaScript applications, supporting both Node.js and browser environments with full TypeScript definitions.
npm install contentfulimport { createClient } from "contentful";For CommonJS:
const { createClient } = require("contentful");import { createClient } from "contentful";
// Create a client instance
const client = createClient({
space: "your-space-id",
accessToken: "your-access-token"
});
// Fetch entries
const entries = await client.getEntries();
console.log(entries.items);
// Fetch a specific entry
const entry = await client.getEntry("entry-id");
console.log(entry.fields);
// Fetch assets
const assets = await client.getAssets();
console.log(assets.items);Contentful.js is built around several key components:
ContentfulClientApi interface providing access to all Contentful resourceswithAllLocales, withoutLinkResolution, withoutUnresolvableLinks) for configuring response behaviorCore functionality for creating and configuring Contentful client instances with authentication and environment settings.
function createClient(params: CreateClientParams): ContentfulClientApi<undefined>;
interface CreateClientParams {
space: string;
accessToken: string;
environment?: string;
host?: string;
insecure?: boolean;
retryOnError?: boolean;
timeout?: number;
// ... additional configuration options
}Comprehensive entry retrieval and parsing capabilities for accessing Contentful content with flexible querying and type safety.
interface ContentfulClientApi<Modifiers> {
getEntry<EntrySkeleton, Locales>(
id: string,
query?: EntryQueries<Modifiers>
): Promise<Entry<EntrySkeleton, Modifiers, Locales>>;
getEntries<EntrySkeleton, Locales>(
query?: EntriesQueries<EntrySkeleton, Modifiers>
): Promise<EntryCollection<EntrySkeleton, Modifiers, Locales>>;
parseEntries<EntrySkeleton, Locales>(
data: EntryCollection<EntrySkeleton, AddChainModifier<Modifiers, 'WITHOUT_LINK_RESOLUTION'>, Locales>
): EntryCollection<EntrySkeleton, Modifiers, Locales>;
}Asset retrieval and management for accessing binary files, images, and media stored in Contentful.
interface ContentfulClientApi<Modifiers> {
getAsset<Locales>(
id: string,
query?: AssetQueries<Modifiers>
): Promise<Asset<Modifiers, Locales>>;
getAssets<Locales>(
query?: AssetsQueries<AssetFields, Modifiers>
): Promise<AssetCollection<Modifiers, Locales>>;
createAssetKey(expiresAt: number): Promise<AssetKey>;
}Advanced querying capabilities for filtering, searching, and retrieving specific content with type-safe parameter validation.
// Query interfaces for different resource types
interface EntriesQueries<EntrySkeleton, Modifiers> {
content_type?: string;
'fields.fieldName'?: any;
limit?: number;
skip?: number;
order?: string;
// ... extensive query parameters
}
interface AssetsQueries<Fields, Modifiers> {
'fields.title'?: string;
'fields.file.contentType'?: string;
mimetype_group?: AssetMimeType;
// ... asset-specific queries
}Real-time content synchronization with delta updates for keeping local content in sync with Contentful.
interface ContentfulClientApi<Modifiers> {
sync<EntrySkeleton, Modifiers, Locales>(
query: SyncQuery,
syncOptions?: SyncOptions
): Promise<SyncCollection<EntrySkeleton, Modifiers, Locales>>;
}
interface SyncQuery {
initial?: boolean;
nextSyncToken?: string;
nextPageToken?: string;
type?: 'Entry' | 'Asset' | 'Deletion';
content_type?: string;
}Access to space metadata, content types, locales, and other Contentful configuration.
interface ContentfulClientApi<Modifiers> {
getSpace(): Promise<Space>;
getLocales(): Promise<LocaleCollection>;
getContentType(id: string): Promise<ContentType>;
getContentTypes(query?: { query?: string }): Promise<ContentTypeCollection>;
}Access to content tags for organizing and categorizing content with metadata labels.
interface ContentfulClientApi<Modifiers> {
getTag(id: string): Promise<Tag>;
getTags(query?: TagQueries): Promise<TagCollection>;
}
interface Tag {
name: string;
sys: TagSys;
}
interface TagSys {
id: string;
type: 'Tag';
version: number;
visibility: string;
createdAt: string;
updatedAt: string;
createdBy: { sys: UserLink };
updatedBy: { sys: UserLink };
}Access to Contentful's taxonomy system for managing hierarchical classification structures and concepts.
interface ContentfulClientApi<Modifiers> {
getConcept(id: string): Promise<Concept<'en-US'>>;
getConcepts(query?: ConceptsQueries): Promise<ConceptCollection<'en-US'>>;
getConceptScheme(id: string): Promise<ConceptScheme<'en-US'>>;
getConceptSchemes(query?: ConceptSchemesQueries): Promise<ConceptSchemeCollection<'en-US'>>;
}
interface Concept<Locales extends LocaleCode> {
sys: ConceptSys;
uri?: string;
prefLabel: { [locale in Locales]: string };
altLabels?: { [locale in Locales]: string[] };
definition?: { [locale in Locales]: string } | null;
broader?: UnresolvedLink<'TaxonomyConcept'>[];
related?: UnresolvedLink<'TaxonomyConcept'>[];
conceptSchemes?: UnresolvedLink<'TaxonomyConceptScheme'>[];
}
interface ConceptScheme<Locales extends LocaleCode> {
sys: ConceptSchemeSys;
uri?: string;
prefLabel: { [locale in Locales]: string };
definition?: { [locale in Locales]: string } | null;
topConcepts: UnresolvedLink<'TaxonomyConcept'>[];
concepts: UnresolvedLink<'TaxonomyConcept'>[];
totalConcepts: number;
}Contentful client supports fluent chain modifiers for configuring response behavior:
withAllLocales: Returns all locale versions of content fieldswithoutLinkResolution: Disables automatic link resolution between entrieswithoutUnresolvableLinks: Removes unresolvable links from responses// Use chain modifiers
const allLocalesClient = client.withAllLocales;
const noLinksClient = client.withoutLinkResolution;
// Chain modifiers maintain type safety
const entries = await allLocalesClient.getEntries();
// entries now have all locale datainterface TagQueries {
'name[exists]'?: boolean;
name?: string;
'name[ne]'?: string;
'name[match]'?: string;
'name[in]'?: string[];
'name[nin]'?: string[];
'sys.visibility'?: 'public' | 'private';
'sys.createdAt'?: string;
'sys.updatedAt'?: string;
limit?: number;
skip?: number;
order?: string;
}
interface ConceptsQueries {
conceptScheme?: string;
'prefLabel[match]'?: string;
limit?: number;
prevPage?: string;
nextPage?: string;
order?: string;
}
interface ConceptSchemesQueries {
'prefLabel[match]'?: string;
limit?: number;
prevPage?: string;
nextPage?: string;
order?: string;
}interface ConceptSys {
id: string;
type: 'TaxonomyConcept';
createdAt: string;
updatedAt: string;
version: number;
}
interface ConceptSchemeSys {
id: string;
type: 'TaxonomyConceptScheme';
createdAt: string;
updatedAt: string;
version: number;
}
interface UnresolvedLink<LinkType extends string> {
sys: {
type: 'Link';
linkType: LinkType;
id: string;
};
}
interface UserLink {
type: 'Link';
linkType: 'User';
id: string;
}
type LocaleCode = string;
interface TagCollection {
sys: { type: 'Array' };
items: Tag[];
limit: number;
skip: number;
total: number;
}
interface ConceptCollection<Locale extends LocaleCode> {
sys: { type: 'Array' };
items: Concept<Locale>[];
limit: number;
pages?: {
prev?: string;
next?: string;
};
}
interface ConceptSchemeCollection<Locale extends LocaleCode> {
sys: { type: 'Array' };
items: ConceptScheme<Locale>[];
limit: number;
pages?: {
prev?: string;
next?: string;
};
}Contentful client handles various error conditions including network failures, authentication errors, and rate limiting with automatic retry logic.
try {
const entry = await client.getEntry("non-existent-id");
} catch (error) {
if (error.sys?.id === 'NotFound') {
console.log('Entry not found');
}
}