Client management capabilities for creating and configuring Contentful client instances with authentication, environment settings, and various configuration options.
Creates a new Contentful client instance for accessing the Content Delivery API.
/**
* Create a client instance
* @param params - Client initialization parameters
* @returns ContentfulClientApi instance
*/
function createClient(params: CreateClientParams): ContentfulClientApi<undefined>;
interface CreateClientParams {
/** Space ID */
space: string;
/** Contentful CDA Access Token */
accessToken: string;
/** Contentful Environment ID (default: "master") */
environment?: string;
/** Requests will be made over http instead of https (default: true) */
insecure?: boolean;
/** API host. Also usable with preview.contentful.com (default: "cdn.contentful.com") */
host?: string;
/** Path appended to the host to support gateways/proxies with custom urls */
basePath?: string;
/** Optional Node.js HTTP agent for proxying */
httpAgent?: any;
/** Optional Node.js HTTPS agent for proxying */
httpsAgent?: any;
/** Optional Axios proxy configuration */
proxy?: any;
/** Optional additional headers */
headers?: Record<string, string>;
/** Optional axios request adapter */
adapter?: any;
/** Application name and version e.g myApp/version */
application?: string;
/** Integration name and version e.g react/version */
integration?: string;
/** If we should retry on errors and 429 rate limit exceptions (default: true) */
retryOnError?: boolean;
/** A log handler function to process given log messages and errors */
logHandler?: (level: ClientLogLevel, data?: Record<string, any> | string) => void;
/** Connection timeout in milliseconds (default: 30000) */
timeout?: number;
/** Optional number of retries before failure (default: 5) */
retryLimit?: number;
/** Interceptor called on every request */
requestLogger?: (request: any) => unknown;
/** Interceptor called on every response */
responseLogger?: (response: any) => unknown;
/** Enable Content Source Maps (Preview API only) */
includeContentSourceMaps?: boolean;
/** Enable alpha features */
alphaFeatures?: {
/** @deprecated Use includeContentSourceMaps option directly */
includeContentSourceMaps?: boolean;
/** Enable Timeline Preview (private beta, Preview API only) */
timelinePreview?: TimelinePreview;
};
}
type ClientLogLevel = 'error' | 'warning' | 'info' | string;
interface TimelinePreview {
timestamp: string;
}Usage Example:
import * as contentful from "contentful";
// Basic client setup
const client = contentful.createClient({
space: "your-space-id",
accessToken: "your-access-token"
});
// Client with custom configuration
const client = contentful.createClient({
space: "your-space-id",
accessToken: "your-access-token",
environment: "staging",
host: "preview.contentful.com", // For preview API
timeout: 10000,
retryLimit: 3,
headers: {
'X-Custom-Header': 'value'
},
logHandler: (level, data) => {
console.log(`[${level}]`, data);
}
});Internal system for managing global client configuration and settings.
/**
* Creates global options handler for client configuration
* @param globalSettings - Global library settings
* @returns getGlobalSettings - Method returning client settings
*/
function createGlobalOptions(
globalSettings: Required<GlobalOptionsParams>
): GetGlobalOptions;
interface GlobalOptionsParams {
environment?: string;
space?: string;
spaceBaseUrl?: string;
environmentBaseUrl?: string;
}
type GetGlobalOptions = (
globalOptions?: GlobalOptionsParams
) => Required<GlobalOptionsParams>;Client chain modifiers provide fluent interface for configuring response behavior.
interface ContentfulClientApi<Modifiers> {
/** A client that will fetch assets and entries with all locales */
withAllLocales: 'WITH_ALL_LOCALES' extends Modifiers
? never
: ContentfulClientApi<AddChainModifier<Modifiers, 'WITH_ALL_LOCALES'>>;
/** A client that will not resolve links in entries */
withoutLinkResolution: 'WITHOUT_LINK_RESOLUTION' extends Modifiers
? never
: 'WITHOUT_UNRESOLVABLE_LINKS' extends Modifiers
? never
: ContentfulClientApi<AddChainModifier<Modifiers, 'WITHOUT_LINK_RESOLUTION'>>;
/** A client that will remove unresolvable links from entries */
withoutUnresolvableLinks: 'WITHOUT_LINK_RESOLUTION' extends Modifiers
? never
: 'WITHOUT_UNRESOLVABLE_LINKS' extends Modifiers
? never
: ContentfulClientApi<AddChainModifier<Modifiers, 'WITHOUT_UNRESOLVABLE_LINKS'>>;
/** The current Contentful.js version */
version: string;
}
type ChainModifiers =
| 'WITH_ALL_LOCALES'
| 'WITHOUT_LINK_RESOLUTION'
| 'WITHOUT_UNRESOLVABLE_LINKS'
| undefined;
type AddChainModifier<
Modifiers extends ChainModifiers,
AddedModifier extends Exclude<ChainModifiers, undefined>
> = undefined extends Modifiers ? AddedModifier : Modifiers | AddedModifier;Usage Examples:
import * as contentful from "contentful";
const client = contentful.createClient({
space: "your-space-id",
accessToken: "your-access-token"
});
// Get all locales for content
const allLocalesClient = client.withAllLocales;
const entries = await allLocalesClient.getEntries();
// entries.items[0].fields now contains all locale versions
// Disable link resolution for better performance
const noLinksClient = client.withoutLinkResolution;
const rawEntries = await noLinksClient.getEntries();
// rawEntries will contain unresolved links
// Remove unresolvable links instead of keeping them
const cleanLinksClient = client.withoutUnresolvableLinks;
const cleanEntries = await cleanLinksClient.getEntries();
// cleanEntries will have unresolvable links removedThe client handles various error conditions including authentication failures, network issues, and rate limiting.
import * as contentful from "contentful";
try {
const client = contentful.createClient({
space: "invalid-space",
accessToken: "invalid-token"
});
const entries = await client.getEntries();
} catch (error) {
// Handle authentication errors
if (error.sys?.id === 'AccessTokenInvalid') {
console.error('Invalid access token');
}
// Handle rate limiting
if (error.sys?.id === 'RateLimitExceeded') {
console.error('Rate limit exceeded, retry after:', error.details.reset);
}
// Handle network errors
if (error.code === 'NETWORK_ERROR') {
console.error('Network connection failed');
}
}