### Project Setup and Build Source: https://github.com/contentful/contentful.js/blob/master/CONTRIBUTING.md Clone the repository, install dependencies, and build the project. This is a prerequisite for running tests and development. ```bash git clone git@github.com:contentful/contentful.js.git cd contentful.js npm ci npm run build ``` -------------------------------- ### Conventional Commits Examples Source: https://github.com/contentful/contentful.js/blob/master/CONTRIBUTING.md Examples demonstrating the conventional commit message format used for this project, including different types like 'feat', 'fix', and 'build'. ```bash feat: add cursor-based pagination for entries fix(deps): bump axios to address CVE-2026-40175 build(deps): bump contentful-sdk-core and qs deps docs: update migration guide for v11 ``` -------------------------------- ### Install and Run Tests Source: https://github.com/contentful/contentful.js/blob/master/test/output-integration/browser/README.md Execute these commands to set up the project and run the tests, which include a browser demo. ```sh npm install && npm run test ``` -------------------------------- ### Install Contentful.js via npm Source: https://github.com/contentful/contentful.js/blob/master/README.md Use npm to install the Contentful.js library. This is the standard method for modern JavaScript projects. ```sh npm install contentful ``` -------------------------------- ### Install Contentful.js via npm Source: https://github.com/contentful/contentful.js/blob/master/README.md Install the library using npm for use in Node.js projects or modern JavaScript environments with module support. ```bash npm install contentful --save ``` -------------------------------- ### Contentful Sync API Example Source: https://github.com/contentful/contentful.js/blob/master/README.md Perform a synchronization to get all changes since the last sync. This is efficient for updating local data stores. Requires an initial sync token. ```javascript client.sync({ initial: true // Set to true for the first sync }) .then(response => { console.log('Sync response:', response); // Store response.nextSyncToken for subsequent syncs }) .catch(error => { console.error('Sync error:', error); }); // For subsequent syncs, use the stored nextSyncToken: // client.sync({ // nextSyncToken: 'your_previous_sync_token' // }) // .then(response => { // console.log('Subsequent sync response:', response); // }) // .catch(error => { // console.error('Subsequent sync error:', error); // }); ``` -------------------------------- ### Vitest Configuration Example Source: https://github.com/contentful/contentful.js/blob/master/docs/ADRs/2024-06-01-vitest-for-testing.md Minimal configuration for Vitest, enabling global test functions and setting the environment to 'node'. Coverage targets are specified for the 'lib' directory. ```typescript export default defineConfig({ globals: true, environment: 'node', coverage: { // Coverage targets include: ['lib/**/*'] }, setupFiles: ['./vitest.setup.ts'] }) ``` -------------------------------- ### Install Contentful.js via yarn Source: https://github.com/contentful/contentful.js/blob/master/README.md Install the library using yarn for use in Node.js projects or modern JavaScript environments with module support. ```bash yarn add contentful ``` -------------------------------- ### Create Client and Get Entry Source: https://github.com/contentful/contentful.js/blob/master/README.md Initialize the Contentful client with your space ID and access token, then make a request to retrieve a specific entry by its ID. ```js import * as contentful from 'contentful' const client = contentful.createClient({ // This is the space ID. A space is like a project folder in Contentful terms space: 'developer_bookshelf', // This is the access token for this space. Normally you get both ID and the token in the Contentful web app accessToken: '0b7f6x59a0', }) // This API call will request an entry with the specified ID from the space defined at the top, using a space-specific access token client .getEntry('5PeGS2SoZGSa4GuiQsigQu') .then((entry) => console.log(entry)) .catch((err) => console.log(err)) ``` -------------------------------- ### Fetch Assets with Contentful.js Source: https://github.com/contentful/contentful.js/blob/master/README.md Retrieve assets from Contentful. This example fetches all assets. Assets typically include images, videos, and documents. ```javascript client.getAssets() .then(assets => console.log(assets)) .catch(error => console.log(error)) ``` -------------------------------- ### Timeline Preview Client Initialization Source: https://github.com/contentful/contentful.js/blob/master/README.md Example of how to initialize the Contentful client with timeline preview options, allowing queries by future date or specific release. This feature was removed in v10.0.0. ```APIDOC ## Timeline Preview Client Initialization ### Description Initializes the Contentful client with options for timeline preview, enabling queries based on future dates or specific releases. Note: This feature has been removed in `v10.0.0`. ### Method `createClient` ### Parameters - `space` (string) - Required - The Contentful space ID. - `accessToken` (string) - Required - The Contentful access token. - `host` (string) - Required - The Contentful API host, e.g., `preview.contentful.com`. - `timelinePreview` (object) - Optional - Configuration for timeline preview. - `release` (object) - Optional - Filter by release, e.g., `{ lte: 'black-friday' }`. - `timestamp` (object) - Optional - Filter by timestamp, e.g., `{ lte: '2025-11-29T08:46:15Z' }`. ### Request Example ```js import * as contentful from 'contentful' const client = contentful.createClient({ space: 'developer_bookshelf', accessToken: 'preview_0b7f6x59a0', host: 'preview.contentful.com', timelinePreview: { release: { lte: 'black-friday' }, timestamp: { lte: '2025-11-29T08:46:15Z' }, }, }) ``` ``` -------------------------------- ### Get Assets in One Locale Source: https://github.com/contentful/contentful.js/blob/master/README.md Fetches assets in a single locale. This is the default behavior. ```javascript const assets = await client.getAssets() ``` -------------------------------- ### Get Assets in All Locales Source: https://github.com/contentful/contentful.js/blob/master/README.md Fetches assets across all available locales. Use the `withAllLocales` modifier. ```javascript const assets = await client.withAllLocales.getAssets() ``` -------------------------------- ### Get Assets Source: https://github.com/contentful/contentful.js/blob/master/README.md Fetches assets from Contentful. Supports chaining modifiers for locale handling. ```APIDOC ## Get Assets ### Description Fetches assets from Contentful. Supports chaining modifiers for locale handling. ### Method ```javascript client.getAssets() client.withAllLocales.getAssets() ``` ### Example ```javascript // returns assets in all locales const assets = await client.withAllLocales.getAssets() // returns assets in one locale const assets = await client.getAssets() ``` ``` -------------------------------- ### Fetch Entries with Contentful.js Source: https://github.com/contentful/contentful.js/blob/master/README.md Retrieve entries from Contentful. This example fetches all entries of a specific content type. Ensure the client is initialized with your space ID and access token. ```javascript client.getEntries() .then(entries => console.log(entries)) .catch(error => console.log(error)) ``` -------------------------------- ### Get Entries Source: https://github.com/contentful/contentful.js/blob/master/README.md Fetches entries from Contentful. Supports chaining modifiers for link resolution and locale handling. ```APIDOC ## Get Entries ### Description Fetches entries from Contentful. Supports chaining modifiers for link resolution and locale handling. ### Method ```javascript client.getEntries() client.withoutUnresolvableLinks.getEntries() client.withoutLinkResolution.withAllLocales.getEntries() ``` ### Example ```javascript // returns entries in one locale, resolves linked entries, removing unresolvable links const entries = await client.withoutUnresolvableLinks.getEntries() // returns entries in all locales, resolves linked entries, removing unresolvable links const entries = await client.withoutLinkResolution.withAllLocales.getEntries() // returns entries in one locale, resolves linked entries, keeping unresolvable links as link object const entries = await client.getEntries() ``` ``` -------------------------------- ### Get Entries with Cursor Pagination Source: https://github.com/contentful/contentful.js/blob/master/README.md Fetches a limited number of entries and provides a cursor for retrieving the next page. Use this for paginating through large datasets of entries. ```javascript const response = await client.getEntriesWithCursor({ limit: 10 }) console.log(response.items) // Array of items console.log(response.pages?.next) // Cursor for next page ``` -------------------------------- ### Sync Source: https://github.com/contentful/contentful.js/blob/master/README.md Perform a synchronization operation to get changes since the last sync. ```APIDOC ## GET /spaces/{space_id}/environments/{environment_id}/sync ### Description Initiates a synchronization process to retrieve changes made to content since the last sync. ### Method GET ### Endpoint /spaces/{space_id}/environments/{environment_id}/sync ### Parameters #### Query Parameters - **nextSyncToken** (string) - Required - The sync token obtained from a previous sync operation. - **initial** (boolean) - Optional - Set to true for the initial sync. ### Response #### Success Response (200) - **nextSyncToken** (string) - The token for the next sync operation. - **entries** (array) - An array of changed or added entries. - **assets** (array) - An array of changed or added assets. - **deletedEntries** (array) - An array of deleted entries. - **deletedAssets** (array) - An array of deleted assets. ``` -------------------------------- ### Get Entries in All Locales Source: https://github.com/contentful/contentful.js/blob/master/README.md Fetches entries across all available locales, resolves linked entries, and removes unresolvable links. Use `withAllLocales` modifier. ```javascript const entries = await client.withoutLinkResolution.withAllLocales.getEntries() ``` -------------------------------- ### Get Entries in One Locale Source: https://github.com/contentful/contentful.js/blob/master/README.md Fetches entries in a single locale, resolves linked entries, and removes unresolvable links. This is the default behavior. ```javascript const entries = await client.withoutUnresolvableLinks.getEntries() ``` -------------------------------- ### Get Entries Keeping Unresolvable Links Source: https://github.com/contentful/contentful.js/blob/master/README.md Fetches entries in a single locale, resolves linked entries, and keeps unresolvable links as link objects. This is the default behavior. ```javascript const entries = await client.getEntries() ``` -------------------------------- ### Get Entry with All Locales in TypeScript Source: https://github.com/contentful/contentful.js/blob/master/TYPESCRIPT.md Use `withAllLocales` to specify a generic type for all available locales in your space. This ensures that field values are typed correctly for each locale when retrieving an entry. ```typescript import * as contentful from 'contentful' const client = contentful.createClient({ space: '', accessToken: '', }) type ProductEntrySkeleton = { fields: { productName: contentful.EntryFieldTypes.Text } contentTypeId: 'product' } type Locales = 'en-US' | 'de-DE' const entry = client.withAllLocales.getEntry('some-entry-id') ``` -------------------------------- ### Get Entry with Link Resolution (Older Versions) Source: https://github.com/contentful/contentful.js/blob/master/ADVANCED.md For versions older than 7.0.0, link resolution is only available when requesting records from the collection endpoint using `client.getEntries()` or `client.sync()`. To resolve links for a single entry, use the collection endpoint with a query parameter for the entry's ID. ```javascript const contentful = require('contentful') const client = contentful.createClient({ accessToken: '', space: '', }) // getting a specific Post client .getEntries({ 'sys.id': '' }) .then((response) => { // output the author name console.log(response.items[0].fields.author.fields.name) }) .catch((err) => console.log(err)) ``` -------------------------------- ### Create Contentful Client Source: https://github.com/contentful/contentful.js/blob/master/README.md Initializes the Contentful client with necessary configuration options. Ensure all required configuration parameters are provided for successful connection. ```javascript contentful.createClient({ ...your config here... }) ``` -------------------------------- ### Fetch Data with Preview API Source: https://github.com/contentful/contentful.js/blob/master/README.md Initialize the client to use the Content Preview API for fetching draft or unpublished content. Requires a Content Delivery API access token and a specific host. ```javascript const previewClient = contentful.createClient({ space: 'your_space_id', accessToken: 'your_preview_access_token', host: 'preview.contentful.com' }) previewClient.getEntries() .then(entries => console.log(entries)) .catch(error => console.log(error)) ``` -------------------------------- ### Initialize Client with Timeline Preview Source: https://github.com/contentful/contentful.js/blob/master/README.md Use this configuration to query content by future date or specific release. Ensure you are using a version of contentful.js that supports timeline preview. ```javascript import * as contentful from 'contentful' const client = contentful.createClient({ space: 'developer_bookshelf', accessToken: 'preview_0b7f6x59a0', host: 'preview.contentful.com', // either release or timestamp or both can be passed as a valid config timelinePreview: { release: { lte: 'black-friday' }, timestamp: { lte: '2025-11-29T08:46:15Z' }, }, }) ``` -------------------------------- ### Create Contentful Client Source: https://github.com/contentful/contentful.js/blob/master/ARCHITECTURE.md Initializes the Contentful client with space and access token. This is the entry point for configuring the SDK. ```javascript createClient({ space, accessToken }) ``` -------------------------------- ### createClient Source: https://github.com/contentful/contentful.js/blob/master/DOCS.md Initializes a new Contentful client instance. ```APIDOC ## createClient ### Description Creates a new instance of the Contentful client. ### Usage ```javascript const client = contentful.createClient({ space: 'YOUR_SPACE_ID', accessToken: 'YOUR_ACCESS_TOKEN' }); ``` ``` -------------------------------- ### Create Client for Preview API Source: https://github.com/contentful/contentful.js/blob/master/README.md Configure the Contentful client to use the Preview API by specifying the preview host and a Preview API access token. ```js import * as contentful from 'contentful' const client = contentful.createClient({ space: 'developer_bookshelf', accessToken: 'preview_0b7f6x59a0', host: 'preview.contentful.com', }) ``` -------------------------------- ### ES6 Import with Contentful SDK Source: https://github.com/contentful/contentful.js/blob/master/ADVANCED.md Demonstrates two ways to import the createClient function using ES6 syntax. Ensure your project supports ES6 modules. ```javascript import { createClient } from "contentful"; const client = createClient({...}); ``` ```javascript import * as contentful from "contentful"; const client = contentful.createClient({...}); ``` -------------------------------- ### Initialize Contentful Client Source: https://github.com/contentful/contentful.js/blob/master/README.md Create a client instance using your space ID and access token. This client is used to make requests to the Contentful API. ```javascript const contentful = require('contentful') const client = contentful.createClient({ space: 'your_space_id', accessToken: 'your_access_token' }) ``` -------------------------------- ### Full Build Pipeline Commands Source: https://github.com/contentful/contentful.js/blob/master/CONTRIBUTING.md Commands to execute the complete build process, including cleaning, TypeScript compilation, and Rollup bundling, followed by checking output formats. ```bash npm run build npm run check ``` -------------------------------- ### Testing Commands Source: https://github.com/contentful/contentful.js/blob/master/CONTRIBUTING.md Various commands to run tests, including all tests, unit tests only, integration tests only, and tests in watch mode. Also includes commands for type tests and bundle size checks. ```bash npm test npm run test:unit npm run test:integration npm run test:unit:watch npm run test:types npm run test:size npm run test:demo-projects ``` -------------------------------- ### Initial Sync Operation Source: https://github.com/contentful/contentful.js/blob/master/ADVANCED.md Perform an initial sync operation to retrieve all content from a space. Save the `nextSyncToken` from the response for subsequent delta syncs. ```javascript const contentful = require('contentful') const client = contentful.createClient({ accessToken: '', space: '', }) // first time you are syncing make sure to specify `initial: true` client .sync({ initial: true }) .then((response) => { // You should save the `nextSyncToken` to use in the following sync console.log(response.nextSyncToken) }) .catch((err) => console.log(err)) ``` -------------------------------- ### Get Entry Without Unresolvable Links in TypeScript Source: https://github.com/contentful/contentful.js/blob/master/TYPESCRIPT.md Use `withoutUnresolvableLinks` to exclude linked entries that cannot be resolved, such as deleted or unpublished entities. This ensures that your response only contains valid, resolvable links. ```typescript import * as contentful from 'contentful' const client = contentful.createClient({ space: '', accessToken: '', }) type ProductEntrySkeleton = { contentTypeId: 'product' fields: { productName: contentful.EntryFieldTypes.Text image: contentful.EntryFieldTypes.AssetLink price: contentful.EntryFieldTypes.Number } } type ReferencedProductEntrySkeleton = { fields: { relatedProduct: contentful.EntryFieldTypes.EntryLink } contentTypeId: 'referencedProduct' } const entry = client.withoutUnresolvableLinks.getEntry('some-entry-id') ``` -------------------------------- ### Development Workflow Commands Source: https://github.com/contentful/contentful.js/blob/master/CONTRIBUTING.md Commands for faster iteration during development, including building only ESM output and running tests in watch mode. ```bash npm run build:esm npm run test:unit:watch npm run test:integration:watch npm run lint npm run prettier ``` -------------------------------- ### Get Entry Without Link Resolution in TypeScript Source: https://github.com/contentful/contentful.js/blob/master/TYPESCRIPT.md Utilize `withoutLinkResolution` to retrieve entries where linked entities are represented as link objects rather than fully resolved entities. This is useful when you only need the link information. ```typescript import * as contentful from 'contentful' const client = contentful.createClient({ space: '', accessToken: '', }) type ProductEntrySkeleton = { contentTypeId: 'product' fields: { productName: contentful.EntryFieldTypes.Text image: contentful.EntryFieldTypes.AssetLink price: contentful.EntryFieldTypes.Number } } type ReferencedProductEntrySkeleton = { fields: { relatedProduct: contentful.EntryFieldTypes.EntryLink } contentTypeId: 'referencedProduct' } const entry = client.withoutLinkResolution.getEntry('some-entry-id') ``` -------------------------------- ### Sync API Initial Fetch Source: https://github.com/contentful/contentful.js/blob/master/ARCHITECTURE.md Initiates a full sync operation to retrieve all content changes since the beginning. It paginates through results and returns a next sync token. ```javascript client.sync({ initial: true }) → GET /sync?initial=true → paged-sync.ts extracts sync_token from nextPageUrl/nextSyncUrl and paginates until complete → returns { entries, assets, deletedEntries, deletedAssets, nextSyncToken } ``` -------------------------------- ### Standard Query Data Flow Source: https://github.com/contentful/contentful.js/blob/master/ARCHITECTURE.md Illustrates the sequence of operations for a standard Contentful entry query, from client creation to response resolution. ```javascript createClient({ space, accessToken }) → createHttpClient(axios, config) [contentful-sdk-core] → makeClient({ http, getGlobalOptions }) → client.getEntries(query) → normalizeSearchParameters(query) → HTTP GET /entries?... → resolveResponse(response) [contentful-resolve-response] → return typed Collection ``` -------------------------------- ### Fetch Entries with Query Parameters Source: https://github.com/contentful/contentful.js/blob/master/README.md Retrieve entries and apply various query parameters to filter, sort, and limit the results. Common parameters include 'limit', 'skip', 'order', and 'include'. ```javascript client.getEntries({ content_type: 'product', limit: 10, skip: 20, order: '-sys.createdAt', include: 2 // Expand linked entries up to 2 levels }) .then(entries => console.log(entries)) .catch(error => console.log(error)) ``` -------------------------------- ### Content Source Maps Configuration Source: https://github.com/contentful/contentful.js/blob/master/ARCHITECTURE.md Enables Content Source Maps for the Contentful Preview API. This enriches string values with metadata for Live Preview and Vercel integration. ```javascript createClient({ ..., includeContentSourceMaps: true }) → adds includeContentSourceMaps=true to all CPA requests → response includes CSM metadata → @contentful/content-source-maps decorates string values with hidden metadata → Live Preview SDK / Vercel reads the metadata for field-to-entry mapping ``` -------------------------------- ### Sync Content with Contentful.js Source: https://github.com/contentful/contentful.js/blob/master/README.md Use this snippet to sync all localized content, resolving linked entries and removing unresolvable links. The `initial: true` option is typically used for the first sync. ```javascript const { entries, assets, deletedEntries, deletedAssets } = await client.withoutUnresolvableLinks.sync({ initial: true }) ``` -------------------------------- ### Static Query Parameters for Entries Source: https://github.com/contentful/contentful.js/blob/master/TYPESCRIPT.md Use static query parameters like skip, limit, and include when fetching entries. These parameters are not dependent on the shape of your content types. ```javascript getEntries({ skip: 10, limit: 20, include: 5, }) ``` -------------------------------- ### Contentful Client Configuration Options Source: https://github.com/contentful/contentful.js/blob/master/README.md Configure the Contentful client with various options, including host, path, environment, and custom headers. This allows for advanced customization of API requests. ```javascript const client = contentful.createClient({ space: 'your_space_id', accessToken: 'your_access_token', host: 'cdn.contentful.com', // Optional: specify a custom path // path: '/custom/path', // Optional: specify an environment // environment: 'master', // Optional: add custom headers // headers: { // 'X-Custom-Header': 'value' // }, // Optional: configure request timeouts // timeout: 30000 }) ``` -------------------------------- ### Include Contentful.js in Legacy Environments Source: https://github.com/contentful/contentful.js/blob/master/README.md Use this method to include the library directly in HTML files for older browsers or environments that do not support ES Modules (import/export syntax). ```html ``` -------------------------------- ### Client Chain Modifiers: withAllLocales Source: https://github.com/contentful/contentful.js/blob/master/TYPESCRIPT.md Demonstrates how to use the `withAllLocales` modifier to retrieve entries and assets with all available locales. This ensures that field values for all locales are accessible in the response. ```APIDOC ## Client Chain Modifiers: withAllLocales ### Description If the current chain includes `withAllLocales`, `getAsset` and `getAssets` expect an optional generic parameter for all existing locales in your space. `parseEntries`, `getEntry` and `getEntries` expect an optional second generic parameter. If the `Locale` type is provided, your response type will define all locale keys for your field values. ### Usage Example (getEntry) ```typescript import * as contentful from 'contentful' const client = contentful.createClient({ space: '', accessToken: '', }) type ProductEntrySkeleton = { fields: { productName: contentful.EntryFieldTypes.Text } contentTypeId: 'product' } type Locales = 'en-US' | 'de-DE' const entry = client.withAllLocales.getEntry('some-entry-id') ``` ### Response Example (getEntry) ```json { "fields": { "productName": { "de-DE": "", "en-US": "" } } } ``` ### Usage Example (getAsset) ```typescript import * as contentful from 'contentful' const client = contentful.createClient({ space: '', accessToken: '', }) type Locales = 'en-US' | 'de-DE' const asset = client.withAllLocales.getAsset('some-asset-id') ``` ### Response Example (getAsset) ```json { "fields": { "file": { "de-DE": "", "en-US": "" } } } ``` ``` -------------------------------- ### Querying Specific Entries by ID with Contentful.js Source: https://github.com/contentful/contentful.js/blob/master/ADVANCED.md Fetch a specific entry using its system ID. This method is efficient for retrieving a single, known piece of content. Error handling is included via `.catch()`. ```javascript const contentful = require('contentful') const client = contentful.createClient({ accessToken: '', space: '', }) // getting a specific Post client .getEntries({ 'sys.id': '' }) .then((response) => { // output the author name console.log(response.items[0].fields.author.fields.name) }) .catch((err) => console.log(err)) ``` -------------------------------- ### Migrate locale='*' to withAllLocales Source: https://github.com/contentful/contentful.js/blob/master/MIGRATION.md Use the `withAllLocales` client chain modifier instead of the deprecated `locale: '*'` query parameter. ```javascript const entries = client.getEntries({ locale: '*', // locale='*' no longer supported }) ``` ```javascript // get entries with all locales (previously `locale: '*'`) const entries = client.withAllLocales.getEntries() ``` -------------------------------- ### Migrate resolveLinks: false to withoutLinkResolution Source: https://github.com/contentful/contentful.js/blob/master/MIGRATION.md Use the `withoutLinkResolution` client chain modifier instead of the deprecated `resolveLinks: false` option or query parameter. ```javascript const client = contentful.createClient({ accessToken: '', space: '', resolveLinks: false, // resolveLinks no longer supported removeUnresolved: true, // removeUnresolved no longer supported }) // query params const entries = client.getEntries({ resolveLinks: false, // resolveLinks no longer supported }) ``` ```javascript const client = contentful.createClient({ accessToken: '', space: '', }) // get entries without link resolution (previously `resolveLinks: false`) const entries = client.withoutLinkResolution.getEntries() // get entries without unresolvable links (previoulsy `removeUnresolved: true`) const entries = client.withoutUnresolvableLinks.getEntries() ``` -------------------------------- ### Fetch a Single Entry by ID Source: https://github.com/contentful/contentful.js/blob/master/README.md Retrieve a specific entry using its unique ID. This is useful when you know exactly which piece of content you need. ```javascript client.getEntry('your_entry_id') .then(entry => console.log(entry)) .catch(error => console.log(error)) ``` -------------------------------- ### Fetch Next Page with Cursor Source: https://github.com/contentful/contentful.js/blob/master/README.md Retrieves the subsequent page of entries using the cursor obtained from a previous `getEntriesWithCursor` call. This is essential for iterating through all available entries. ```javascript const nextPageResponse = await client.getEntriesWithCursor({ limit: 10, pageNext: response.pages?.next, }) console.log(nextPageResponse.items) // Array of items console.log(nextPageResponse.pages?.next) // Cursor for next page console.log(nextPageResponse.pages?.prev) // Cursor for prev page ``` -------------------------------- ### ContentfulClientApi Source: https://github.com/contentful/contentful.js/blob/master/DOCS.md Methods available on the Contentful client API. ```APIDOC ## ContentfulClientApi Methods ### getEntry #### Description Retrieves a single entry by its ID. #### Method `getEntry(entryId, query)` ### getEntries #### Description Retrieves multiple entries, with options for filtering and searching. #### Method `getEntries(query)` ### getAsset #### Description Retrieves a single asset by its ID. #### Method `getAsset(assetId, query)` ### getAssets #### Description Retrieves multiple assets, with options for filtering. #### Method `getAssets(query)` ### getContentType #### Description Retrieves a single content type by its ID. #### Method `getContentType(contentTypeId, query)` ### getContentTypes #### Description Retrieves multiple content types. #### Method `getContentTypes(query)` ### getSpace #### Description Retrieves information about the current space. #### Method `getSpace(query)` ### getLocales #### Description Retrieves the locales for the current space. #### Method `getLocales(query)` ### sync #### Description Synchronizes content changes. #### Method `sync(query)` ### createAssetKey #### Description Creates a new asset key. #### Method `createAssetKey(assetId, key)` ### getTag #### Description Retrieves a single tag by its ID. #### Method `getTag(tagId, query)` ### getTags #### Description Retrieves multiple tags. #### Method `getTags(query)` ### parseEntries #### Description Parses entries from a raw response. #### Method `parseEntries(rawEntries)` ``` -------------------------------- ### Fetch Entries by Content Type Source: https://github.com/contentful/contentful.js/blob/master/README.md Retrieve entries filtered by a specific content type. This is useful for fetching specific kinds of content, like blog posts or products. ```javascript client.getEntries({ content_type: 'blogPost' }) .then(entries => console.log(entries)) .catch(error => console.log(error)) ``` -------------------------------- ### Webpack 5 Fallback Configuration Source: https://github.com/contentful/contentful.js/blob/master/MIGRATION.md Configure Webpack 5 to bundle Contentful.js for the browser by providing fallbacks for Node.js core modules. ```javascript module.exports = { resolve: { fallback: { os: false, zlib: false, tty: false, }, }, }; ``` -------------------------------- ### Require Contentful.js CJS Bundle Source: https://github.com/contentful/contentful.js/blob/master/README.md Directly require the CommonJS bundle if the default require syntax does not work in your legacy environment. ```js const contentful = require('contentful/dist/contentful.cjs') ``` -------------------------------- ### Custom Paginated Sync with Contentful.js Source: https://github.com/contentful/contentful.js/blob/master/ADVANCED.md Implement a custom recursive function to handle paginated sync operations. Ensure `paginate` is set to `false` for each sync call. This is useful for processing sync results page by page or saving them incrementally. ```javascript const contentful = require('contentful') const client = contentful.createClient({ accessToken: '', space: '', }) function customPaginatedSync(query) { // Call sync, make sure you set paginate to false for every call return client.sync(query, { paginate: false }).then((response) => { // Do something with the respond. For example save result to disk. console.log('Result of current sync page:', response.items) // Sync finished when `nextSyncToken` is available if (response.nextSyncToken) { console.log('Syncing done. Start a new sync via ' + response.nextSyncToken) return } // Otherwise, just continue to next page of the current sync run return customPaginatedSync({ nextPageToken: response.nextPageToken }) }) } customPaginatedSync({ initial: true }).then(() => console.log('Sync done')) ``` -------------------------------- ### Fetch a Single Asset by ID Source: https://github.com/contentful/contentful.js/blob/master/README.md Retrieve a specific asset using its unique ID. This is useful for directly accessing a particular file like an image. ```javascript client.getAsset('your_asset_id') .then(asset => console.log(asset)) .catch(error => console.log(error)) ``` -------------------------------- ### Sync API Incremental Fetch Source: https://github.com/contentful/contentful.js/blob/master/ARCHITECTURE.md Performs an incremental sync using a provided sync token to fetch only the content changes that have occurred since the last sync. ```javascript client.sync({ nextSyncToken }) → GET /sync?sync_token=... → returns incremental delta ``` -------------------------------- ### Querying Single Entry with Parameters Source: https://github.com/contentful/contentful.js/blob/master/ADVANCED.md Retrieve a single entry while passing additional query parameters. This allows for filtering or specifying details for the requested entry. ```javascript client.getEntry('', { key: value }) ``` -------------------------------- ### Including Regenerator Runtime for Older Browsers Source: https://github.com/contentful/contentful.js/blob/master/MIGRATION.md Provides the script tag to include the Regenerator Runtime for supporting older browsers with the legacy bundle of contentful.js. ```html ``` -------------------------------- ### Assets Source: https://github.com/contentful/contentful.js/blob/master/README.md Retrieve assets from Contentful. Assets are typically media files like images and documents. ```APIDOC ## GET /spaces/{space_id}/environments/{environment_id}/assets ### Description Retrieves a collection of assets from a specific environment within a space. ### Method GET ### Endpoint /spaces/{space_id}/environments/{environment_id}/assets ### Parameters #### Query Parameters - **limit** (integer) - Optional - Limits the number of assets returned. - **skip** (integer) - Optional - Skips a specified number of assets. ### Response #### Success Response (200) - **items** (array) - An array of asset objects. - **total** (integer) - The total number of assets available. - **skip** (integer) - The number of assets skipped. - **limit** (integer) - The limit of assets returned. ``` -------------------------------- ### Contentful Entry Response Without Link Resolution Source: https://github.com/contentful/contentful.js/blob/master/ADVANCED.md Illustrates the structure of a Contentful entry response when linked entries are not resolved, showing a 'Link' object instead of the full entry data. ```json { "sys": { ... }, "metadata": { ... }, "fields": { "referencedEntry": { "type": "Link", "linkType": "Entry", "id": "" } } } ``` -------------------------------- ### Contentful Entry Response With Link Resolution Source: https://github.com/contentful/contentful.js/blob/master/ADVANCED.md Shows the structure of a Contentful entry response after link resolution, where linked entries are inlined directly into the response object. ```json { "sys": { ... }, "metadata": { ... }, "fields": { "referencedEntry": { "sys": { ... }, "metadata": { ... }, "fields": { ... } } } } ``` -------------------------------- ### Include Specific Version of Contentful.js in Browser Source: https://github.com/contentful/contentful.js/blob/master/README.md Include a specific version of the Contentful.js library in your HTML via CDN by specifying the version number in the URL. ```html ``` -------------------------------- ### Node.js Conditional Exports for Dual Package Source: https://github.com/contentful/contentful.js/blob/master/docs/ADRs/2022-06-01-dual-package-esm-cjs.md Configure package.json to use Node.js conditional exports for ESM and CJS compatibility. This allows consumers to import using `import` or `require()` without additional configuration. ```json { "type": "module", "exports": { ".": { "types": "./dist/types/index.d.ts", "import": "./dist/esm/index.js", "require": "./dist/contentful.cjs" } } } ``` -------------------------------- ### Include Contentful.js in Browser via CDN Source: https://github.com/contentful/contentful.js/blob/master/README.md Include the Contentful.js library in your HTML using a script tag from a CDN. This makes the library available globally. ```html ``` -------------------------------- ### Rollup Browser Bundle Configuration Source: https://github.com/contentful/contentful.js/blob/master/MIGRATION.md Configure Rollup to bundle Contentful.js for the browser by disabling the use of Node.js built-in modules. ```javascript nodeResolve({ browser: true, preferBuiltins: false }) ```