Gathering detailed insights and metrics for contentful
Gathering detailed insights and metrics for contentful
Gathering detailed insights and metrics for contentful
Gathering detailed insights and metrics for contentful
contentful-sdk-core
Core modules for the Contentful JS SDKs
contentful-resolve-response
[![npm](https://img.shields.io/npm/v/contentful-resolve-response.svg)](https://www.npmjs.com/package/contentful-resolve-response)
contentful-migration
Migration tooling for contentful
contentful-cli
Contentful CLI tool
JavaScript library for Contentful's Delivery API (node & browser)
npm install contentful
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
1,195 Stars
2,514 Commits
200 Forks
88 Watching
31 Branches
271 Contributors
Updated on 26 Nov 2024
TypeScript (97.58%)
JavaScript (2.27%)
HTML (0.15%)
Cumulative downloads
Total Downloads
Last day
-1.1%
134,289
Compared to previous day
Last week
0.1%
674,734
Compared to previous week
Last month
21.9%
3,198,888
Compared to previous month
Last year
21.2%
30,353,823
Compared to previous year
7
39
Readme · Migration · Advanced · TypeScript · Contributing
JavaScript library for the Contentful Content Delivery API and Content Preview API. It helps you to easily access your content stored in Contentful with your JavaScript applications.
What is Contentful?
Contentful provides content infrastructure for digital teams to power websites, apps, and devices. Unlike a CMS, Contentful was built to integrate with the modern software stack. It offers a central hub for structured content, powerful management and delivery APIs, and a customizable web app that enables developers and content creators to ship their products faster.
v6.0.0
)For the minimum supported browser versions, refer to the package.json of this library.
To ensure compatibility across various JavaScript environments, this library is built as an ECMAScript Module (ESM) by default, using the "type": "module"
declaration in package.json
.
We also offer a bundle for the legacy CommonJS (CJS) require syntax, allowing usage in environments that do not support ESM.
Additionally, there is a bundle available for direct usage within browsers.
For more details on the different variants of this library, see Installation.
In order to get started with the Contentful JS library you'll need not only to install it, but also to get credentials which will allow you to have access to your content in Contentful.
1npm install contentful
In a modern environment, you can import this library using:
1import * as contentful from 'contentful'
Typically, your system will default to our CommonJS export when you use the require syntax:
1const contentful = require('contentful')
If this does not work, you can directly require the CJS-compatible code:
1const contentful = require('contentful/dist/contentful.cjs')
For browsers, we recommend downloading the library via npm or yarn to ensure 100% availability.
If you'd like to use a standalone built file you can use the following script tag or download it from jsDelivr, under the dist
directory:
1<script src="https://cdn.jsdelivr.net/npm/contentful@latest/dist/contentful.browser.min.js"></script>
Using contentful@latest
will always get you the latest version, but you can also specify a specific version number.
1<script src="https://cdn.jsdelivr.net/npm/contentful@9.0.1/dist/contentful.browser.min.js"></script>
The Contentful Delivery library will be accessible via the contentful
global variable.
Check the releases page to know which versions are available.
The following code snippet is the most basic one you can use to get some content from Contentful with this library:
1import * as contentful from "contentful"
2const client = contentful.createClient({
3 // This is the space ID. A space is like a project folder in Contentful terms
4 space: 'developer_bookshelf',
5 // This is the access token for this space. Normally you get both ID and the token in the Contentful web app
6 accessToken: '0b7f6x59a0',
7})
8// This API call will request an entry with the specified ID from the space defined at the top, using a space-specific access token
9client
10 .getEntry('5PeGS2SoZGSa4GuiQsigQu')
11 .then((entry) => console.log(entry))
12 .catch((err) => console.log(err))
Check out this JSFiddle version of our Product Catalogue demo app.
This library can also be used with the Preview API. In order to do so, you need to use the Preview API Access token, available on the same page where you get the Delivery API token, and specify the host of the preview API, such as:
1import * as contentful from "contentful"
2const client = contentful.createClient({
3 space: 'developer_bookshelf',
4 accessToken: 'preview_0b7f6x59a0',
5 host: 'preview.contentful.com',
6})
You can find all available methods of our client in our reference documentation.
To get your own content from Contentful, an app should authenticate with an OAuth bearer token.
You can create API keys using the Contentful web interface. Go to the app, open the space that you want to access (top left corner lists all the spaces), and navigate to the APIs area. Open the API Keys section and create your first token. Done.
Don't forget to also get your Space ID.
For more information, check the Contentful REST API reference on Authentication.
To help you get the most out of this library, we've prepared all available client configuration options, a reference documentation, tutorials and other examples that will help you learn and understand how to use this library.
The createClient
method supports several options you may set to achieve the expected behavior:
1contentful.createClient({
2 ...your config here...
3})
The configuration options belong to two categories: request config and response config.
Name | Default | Description |
---|---|---|
accessToken | Required. Your CDA access token. | |
space | Required. Your Space ID. | |
environment | 'master' | Set the environment that the API key has access to. |
host | 'cdn.contentful.com' | Set the host used to build the request URI's. |
basePath | '' | This path gets appended to the host to allow request urls like https://gateway.example.com/contentful/ for custom gateways/proxies. |
httpAgent | undefined | Custom agent to perform HTTP requests. Find further information in the axios request config documentation. |
httpsAgent | undefined | Custom agent to perform HTTPS requests. Find further information in the axios request config documentation. |
adapter | undefined | Custom adapter to handle making the requests. Find further information in the axios request config documentation. |
headers | {} | Additional headers to attach to the requests. We add/overwrite the following headers:
|
proxy | undefined | Axios proxy configuration. See the axios request config documentation for further information about the supported values. |
retryOnError | true | By default, this library is retrying requests which resulted in a 500 server error and 429 rate limit response. Set this to false to disable this behavior. |
application | undefined | Application name and version e.g myApp/version. |
integration | undefined | Integration name and version e.g react/version. |
timeout | 30000 | in milliseconds - connection timeout. |
retryLimit | 5 | Optional number of retries before failure. |
logHandler | function (level, data) {} | Errors and warnings will be logged by default to the node or browser console. Pass your own log handler to intercept here and handle errors, warnings and info on your own. |
requestLogger | function (config) {} | Interceptor called on every request. Takes Axios request config as an arg. |
responseLogger | function (response) {} | Interceptor called on every response. Takes Axios response object as an arg. |
:warning: Response config options have been removed in
v10.0.0
in favor of the new client chain modifiers approach.
Introduced in
v10.0.0
.
The contentful.js library returns calls to sync
, parseEntries
, getEntries
, getEntry
, getAssets
and getAsset
in different shapes, depending on the configurations listed in the respective sections below.
In order to provide type support for each configuration, we provide the possibility to chain modifiers to the Contentful client, providing the correct return types corresponding to the used modifiers.
This way, we make developing with contentful.js
much more predictable and safer.
When initialising a client, you will receive an instance of the ContentfulClientApi
shape.
Chain | Modifier |
---|---|
none (default) | Returns entries in a single locale. Resolvable linked entries will be inlined while unresolvable links will be kept as link objects. Read more on link resolution |
withAllLocales | Returns entries in all locales. |
withoutLinkResolution | All linked entries will be rendered as link objects. Read more on link resolution |
withoutUnresolvableLinks | If linked entries are not resolvable, the corresponding link objects are removed from the response. |
1// returns entries in one locale, resolves linked entries, removing unresolvable links 2const entries = await client.withoutUnresolvableLinks.getEntries()
You can also combine client chains:
1// returns entries in all locales, resolves linked entries, removing unresolvable links 2const entries = await client.withoutLinkResolution.withAllLocales.getEntries()
The default behaviour doesn't change, you can still do:
1// returns entries in one locale, resolves linked entries, keeping unresolvable links as link object 2const entries = await client.getEntries()
The same chaining approach can be used with parseEntries
. Assuming this is the raw data we want to parse:
1const localizedData = { 2 total: 1, 3 skip: 0, 4 limit: 100, 5 items: [ 6 { 7 metadata: { tags: [] }, 8 sys: { 9 space: { 10 sys: { type: 'Link', linkType: 'Space', id: 'my-space-id' }, 11 }, 12 id: 'my-zoo', 13 type: 'Entry', 14 createdAt: '2020-01-01T00:00:00.000Z', 15 updatedAt: '2020-01-01T00:00:00.000Z', 16 environment: { 17 sys: { id: 'master', type: 'Link', linkType: 'Environment' }, 18 }, 19 revision: 1, 20 contentType: { sys: { type: 'Link', linkType: 'ContentType', id: 'zoo' } }, 21 locale: 'en-US', 22 }, 23 fields: { 24 animal: { 25 'en-US': { sys: { type: 'Link', linkType: 'Entry', id: 'oink' } }, 26 }, 27 anotheranimal: { 28 'en-US': { sys: { type: 'Link', linkType: 'Entry', id: 'middle-parrot' } }, 29 }, 30 }, 31 }, 32 ], 33 includes: { 34 Entry: [ 35 { 36 metadata: { tags: [] }, 37 sys: { 38 space: { 39 sys: { type: 'Link', linkType: 'Space', id: 'my-space-id' }, 40 }, 41 id: 'oink', 42 type: 'Entry', 43 createdAt: '2020-01-01T00:00:00.000Z', 44 updatedAt: '2020-02-01T00:00:00.000Z', 45 environment: { 46 sys: { id: 'master', type: 'Link', linkType: 'Environment' }, 47 }, 48 revision: 2, 49 contentType: { sys: { type: 'Link', linkType: 'ContentType', id: 'animal' } }, 50 locale: 'en-US', 51 }, 52 fields: { 53 name: { 54 'en-US': 'Pig', 55 de: 'Schwein', 56 }, 57 friend: { 58 'en-US': { sys: { type: 'Link', linkType: 'Entry', id: 'groundhog' } }, 59 }, 60 }, 61 }, 62 ], 63 }, 64}
It can be used to receive parsed entries with all locales:
1// returns parsed entries in all locales 2const entries = client.withAllLocales.parseEntries(localizedData)
Similarly, raw data without locales information can be parsed as well:
1const data = { 2 total: 1, 3 skip: 0, 4 limit: 100, 5 items: [ 6 { 7 metadata: { tags: [] }, 8 sys: { 9 space: { sys: { type: 'Link', linkType: 'Space', id: 'my-space-id' } }, 10 id: 'my-zoo', 11 type: 'Entry', 12 createdAt: '2020-01-01T00:00:00.000Z', 13 updatedAt: '2020-01-01T00:00:00.000Z', 14 environment: { sys: { id: 'master', type: 'Link', linkType: 'Environment' } }, 15 revision: 1, 16 contentType: { sys: { type: 'Link', linkType: 'ContentType', id: 'zoo' } }, 17 locale: 'en-US', 18 }, 19 fields: { 20 animal: { sys: { type: 'Link', linkType: 'Entry', id: 'oink' } }, 21 anotheranimal: { sys: { type: 'Link', linkType: 'Entry', id: 'middle-parrot' } }, 22 }, 23 }, 24 ], 25 includes: { 26 Entry: [ 27 { 28 metadata: { tags: [] }, 29 sys: { 30 space: { sys: { type: 'Link', linkType: 'Space', id: 'my-space-id' } }, 31 id: 'oink', 32 type: 'Entry', 33 createdAt: '2020-01-01T00:00:00.000Z', 34 updatedAt: '2020-02-01T00:00:00.000Z', 35 environment: { sys: { id: 'master', type: 'Link', linkType: 'Environment' } }, 36 revision: 2, 37 contentType: { sys: { type: 'Link', linkType: 'ContentType', id: 'animal' } }, 38 locale: 'en-US', 39 }, 40 fields: { 41 name: 'Pig', 42 friend: { sys: { type: 'Link', linkType: 'Entry', id: 'groundhog' } }, 43 }, 44 }, 45 ], 46 }, 47}
1// returns parsed entries keeping unresolvable links as link object 2const entries = client.withoutLinkResolution.parseEntries(data)
Chain | Modifier |
---|---|
none (default) | Returns assets in a single locale. |
withAllLocales | Returns assets in all locales. |
1// returns assets in all locales 2const assets = await client.withAllLocales.getAssets()
The default behaviour doesn't change, you can still do:
1// returns assets in one locale 2const assets = await client.getAssets()
The Sync API always retrieves all localized content, therefore withAllLocales
is accepted, but ignored.
Chain | Modifier |
---|---|
none (default) | Returns content in all locales. |
withoutLinkResolution | Linked content will be rendered as link objects. Read more on link resolution |
withoutUnresolvableLinks | If linked content is not resolvable, the corresponding link objects are removed from the response. |
1// returns content in all locales, resolves linked entries, removing unresolvable links 2const { entries, assets, deletedEntries, deletedAssets } = 3 await client.withoutUnresolvableLinks.sync({ initial: true })
More information on behavior of the Sync API can be found in the sync section in ADVANCED.md
The JS library reference documents what objects and methods are exposed by this library, what arguments they expect and what kind of data is returned.
Most methods also have examples which show you how to use them.
http
.
Our library is supplied as node and browser version. Most non-node environments, like React Native, act like a browser. To force using of the browser version, you can require it via:1const { createClient } = require('contentful/dist/contentful.browser.min.js')
This library is 100% written in TypeScript. Type definitions are bundled. Find out more about the advantages of using this library in conjunction with TypeScript in the TYPESCRIPT document.
More information about how to use the library in advanced or special ways can be found in the ADVANCED document.
We gathered all information related to migrating from older versions of the library in our MIGRATION document.
We appreciate any help on our repositories. For more details about how to contribute see our CONTRIBUTING document.
This repository is published under the MIT license.
We want to provide a safe, inclusive, welcoming, and harassment-free space and experience for all participants, regardless of gender identity and expression, sexual orientation, disability, physical appearance, socioeconomic status, body size, ethnicity, nationality, level of experience, age, religion (or lack thereof), or other identity markers.
No vulnerabilities found.
Reason
30 commit(s) and 11 issue activity found in the last 90 days -- score normalized to 10
Reason
all changesets reviewed
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
security policy file detected
Details
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
1 existing vulnerabilities detected
Details
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More