Security News
Research
Data Theft Repackaged: A Case Study in Malicious Wrapper Packages on npm
The Socket Research Team breaks down a malicious wrapper package that uses obfuscation to harvest credentials and exfiltrate sensitive data.
contentful-management
Advanced tools
The contentful-management npm package is a JavaScript client for the Contentful Content Management API. It allows developers to manage content, assets, and other resources within a Contentful space programmatically.
Create an Entry
This code sample demonstrates how to create a new entry in a Contentful space. You need to provide your access token and space ID, and specify the content type and fields for the new entry.
const contentfulManagement = require('contentful-management');
contentfulManagement.createClient({
accessToken: 'your-access-token'
}).then(client => {
return client.getSpace('your-space-id')
.then(space => space.createEntry('contentType', {
fields: {
title: {
'en-US': 'Hello, World!'
}
}
}))
.then(entry => console.log(entry))
.catch(console.error);
});
Update an Entry
This code sample shows how to update an existing entry in a Contentful space. You need to provide your access token, space ID, and the ID of the entry you want to update. The example updates the title field of the entry.
const contentfulManagement = require('contentful-management');
contentfulManagement.createClient({
accessToken: 'your-access-token'
}).then(client => {
return client.getSpace('your-space-id')
.then(space => space.getEntry('entry-id'))
.then(entry => {
entry.fields.title['en-US'] = 'Updated Title';
return entry.update();
})
.then(entry => console.log(entry))
.catch(console.error);
});
Delete an Entry
This code sample demonstrates how to delete an entry from a Contentful space. You need to provide your access token, space ID, and the ID of the entry you want to delete.
const contentfulManagement = require('contentful-management');
contentfulManagement.createClient({
accessToken: 'your-access-token'
}).then(client => {
return client.getSpace('your-space-id')
.then(space => space.getEntry('entry-id'))
.then(entry => entry.delete())
.then(() => console.log('Entry deleted'))
.catch(console.error);
});
Upload an Asset
This code sample shows how to upload an asset to a Contentful space. You need to provide your access token, space ID, and the path to the file you want to upload. The example also processes and publishes the asset.
const contentfulManagement = require('contentful-management');
const fs = require('fs');
contentfulManagement.createClient({
accessToken: 'your-access-token'
}).then(client => {
return client.getSpace('your-space-id')
.then(space => space.createAssetFromFiles({
fields: {
title: {
'en-US': 'My Asset'
},
file: {
'en-US': {
contentType: 'image/jpeg',
fileName: 'my-asset.jpg',
file: fs.createReadStream('path/to/your/file.jpg')
}
}
}
}))
.then(asset => asset.processForAllLocales())
.then(asset => asset.publish())
.then(asset => console.log(asset))
.catch(console.error);
});
Strapi is an open-source headless CMS that provides a robust API and a user-friendly admin panel. Unlike Contentful, which is a SaaS product, Strapi can be self-hosted, giving you more control over your data and infrastructure.
Prismic is another headless CMS that offers a content management API. The prismic-javascript package allows you to query and manage content in Prismic. It is similar to Contentful in terms of functionality but offers different pricing and features.
# contentful-management.js
JavaScript Library for Contentful's Content Management API.
Contentful provides a content infrastructure for digital teams to power content in 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 enable developers and content creators to ship digital products faster.
Browsers and Node.js:
Other browsers should also work, but at the moment we're only running automated tests on the browsers and Node.js versions specified above.
To get started with the Contentful Management JS library you'll need to install it, and then get credentials which will allow you to access your content in Contentful.
Using npm:
npm install contentful-management
Using yarn:
yarn add contentful-management
For browsers, we recommend to download 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:
<script src="https://cdn.jsdelivr.net/npm/contentful-management@latest/dist/contentful-management.browser.min.js"></script>
It's not recommended to use the above URL for production.
Using contentful@latest
will always get you the latest version, but you can also specify a specific version number:
<!-- Avoid using the following url for production. You can not rely on its availability. -->
<script src="https://cdn.jsdelivr.net/npm/contentful-management@7.3.0/dist/contentful-management.browser.min.js"></script>
The Contentful Management library will be accessible via the contentfulManagement
global variable.
Check the releases page to know which versions are available.
This library also comes with typings to use with typescript.
To get content from Contentful, an app should authenticate with an OAuth bearer token.
If you want to use this library for a simple tool or a local app that you won't redistribute or make available to other users, you can get an API key for the Management API at our Authentication page.
If you'd like to create an app which would make use of this library but that would be available for other users, where they could authenticate with their own Contentful credentials, make sure to also check out the section about Creating an OAuth Application
You can use the es6 import with the library as follow
// import createClient directly
import contentful from 'contentful-management'
const client = contentful.createClient({
// This is the access token for this space. Normally you get the token in the Contentful web app
accessToken: 'YOUR_ACCESS_TOKEN',
})
//....
The following code snippet is the most basic one you can use to get content from Contentful with this library:
const contentful = require('contentful-management')
const client = contentful.createClient({
// This is the access token for this space. Normally you get the token in the Contentful web app
accessToken: 'YOUR_ACCESS_TOKEN',
})
// This API call will request a space with the specified ID
client.getSpace('spaceId').then((space) => {
// This API call will request an environment with the specified ID
space.getEnvironment('master').then((environment) => {
// Now that we have an environment, we can get entries from that space
environment.getEntries().then((entries) => {
console.log(entries.items)
})
// let's get a content type
environment.getContentType('product').then((contentType) => {
// and now let's update its name
contentType.name = 'New Product'
contentType.update().then((updatedContentType) => {
console.log('Update was successful')
})
})
})
})
You can try and change the above example at Tonic.
Starting contentful-management@7
this library provides an alternative plain client which exposes all CMA endpoints in a simple flat manner oppose to a default waterfall structure.
const contentful = require('contentful-management')
const plainClient = contentful.createClient(
{
// This is the access token for this space. Normally you get the token in the Contentful web app
accessToken: 'YOUR_ACCESS_TOKEN',
},
{ type: 'plain' }
)
const environment = await plainClient.environment.get({
spaceId: '<space_id>',
environmentId: '<environment_id>',
})
const entries = await plainClient.entry.getMany({
spaceId: '123',
environmentId: '',
query: {
skip: 10,
limit: 100,
},
})
// With scoped space and environment
const scopedPlainClient = contentful.createClient(
{
// This is the access token for this space. Normally you get the token in the Contentful web app
accessToken: 'YOUR_ACCESS_TOKEN',
},
{
type: 'plain',
defaults: {
spaceId: '<space_id>',
environmentId: '<environment_id>',
},
}
)
// entries from '<space_id>' & '<environment_id>'
const entries = await scopedPlainClient.entry.getMany({
query: {
skip: 10,
limit: 100,
},
})
The benefits of using the plain version of the library are:
toPlainObject
function call.spaceId
, environmentId
, and organizationId
when initializing the client.
defaults
and omit specifying these params in actual CMA methods calls.Starting @contentful/app-sdk@4
you can use this client to make requests
from your apps built for Contentful.
A dedicated Adapter grants your apps access to the supported space-environment scoped entities without compromising on security as you won't need to expose a management token, and without coding any additional backend middleware.
const contentfulApp = require('@contentful/app-sdk')
const contentful = require('contentful-management')
contentfulApp.init((sdk) => {
const cma = contentful.createClient(
{ apiAdapter: sdk.cmaAdapter },
{
type: 'plain',
defaults: {
environmentId: sdk.ids.environmentAlias ?? sdk.ids.environment,
spaceId: sdk.ids.space,
},
}
)
// ...rest of initialization code
})
Please Note
Requests issued by the App SDK adapter will count towards the same rate limiting quota as the ones made by other APIs exposed by App SDK (e.g., Space API). Ultimately, they will all fall into the same bucket as the calls performed by the host app (i.e., Contentful web app, Compose, or Launch).
contentful-management
and not contenful-management
¯\_(ツ)_/¯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: const { createClient } = require('contentful-management/dist/contentful-management.browser.min.js')
To help you get the most out of this library, we've prepared 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:
contentful.createClient({
... your config here ...
})
apiAdapter
is not set)Your CMA access token.
'api.contentful.com'
)Set the host used to build the request URI's.
'upload.contentful.com'
)Set the host used to build the upload related request uri's.
This path gets appended to the host to allow request urls like https://gateway.example.com/contentful/
for custom gateways/proxies.
undefined
)Custom agent to perform HTTP requests. Find further information in the axios request config documentation.
undefined
)Custom agent to perform HTTPS requests. Find further information in the axios request config documentation.
{}
)Additional headers to attach to the requests. We add/overwrite the following headers:
application/vnd.contentful.management.v1+json
sdk contentful-management.js/1.2.3; platform node.js/1.2.3; os macOS/1.2.3
(Automatically generated)undefined
)Axios proxy configuration. See the axios request config documentation for further information about the supported values.
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.
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.
function (config) {}
)Interceptor called on every request. Takes Axios request config as an arg. Default does nothing. Pass your own function to log any desired data.
function (response) {}
)Interceptor called on every response. Takes Axios response object as an arg. Default does nothing. Pass your own function to log any desired data.
new RestAdapter(configuration)
)An Adapter
that can be utilized to issue requests. It defaults to a RestAdapter
initialized with provided configuration.
Please Note
The Adapter will take precedence over the other options. Therefore, ensure you're providing the Adapter all the information it needs to issue the request (e.g., host or auth headers)
0
)Maximum number of requests per second.
1
-30
(fixed number of limit),'auto'
(calculated limit based on your plan),'0%'
- '100%'
(calculated % limit based on your plan)The Contentful's 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.
You can start by looking at the top level contentfulManagement
namespace.
The ContentfulClientAPI
namespace defines the methods at the Client level which allow you to create and get spaces.
The ContentfulSpaceAPI
namespace defines the methods at the Space level which allow you to create and get entries, assets, content types and other possible entities.
The Entry
, Asset
and ContentType
namespaces show you the instance methods you can use on each of these entities, once you retrieve them from the server.
From version 1.0.0 onwards, you can access documentation for a specific version by visiting
https://contentful.github.io/contentful-management.js/contentful-management/<VERSION>
Read the Contentful for JavaScript page for Tutorials, Demo Apps, and more information on other ways of using JavaScript with Contentful
This library is a wrapper around our Contentful Management REST API. Some more specific details such as search parameters and pagination are better explained on the REST API reference, and you can also get a better understanding of how the requests look under the hood.
This project strictly follows Semantic Versioning by use of semantic-release.
This means that new versions are released automatically as fixes, features or breaking changes are released.
You can check the changelog on the releases page.
contentful.js 1.x was a major rewrite, with some API changes. While the base functionality remains the same, some method names have changed, as well as some internal behaviors.
See the migration guide for more information.
If you have a problem with this library, please file an issue here on GitHub.
If you have other problems with Contentful not related to this library, you can contact Customer Support.
See CONTRIBUTING.md
MIT
FAQs
Client for Contentful's Content Management API
The npm package contentful-management receives a total of 368,428 weekly downloads. As such, contentful-management popularity was classified as popular.
We found that contentful-management demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 6 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Research
The Socket Research Team breaks down a malicious wrapper package that uses obfuscation to harvest credentials and exfiltrate sensitive data.
Research
Security News
Attackers used a malicious npm package typosquatting a popular ESLint plugin to steal sensitive data, execute commands, and exploit developer systems.
Security News
The Ultralytics' PyPI Package was compromised four times in one weekend through GitHub Actions cache poisoning and failure to rotate previously compromised API tokens.