How to remove all the entries from Contentful space

Pasan Gamage
2 min readDec 6, 2021

--

Intro

For those who are not familiar with Contentful, it is a cloud based content management system with a lot of perks.

https://www.contentful.com/why-contentful/ will be a good resource for anyone who is interested.

Recently I’ve started working with Contentful CLI and thought this will be a good place to start posting the issues and gotchas I come across.

I’ve been testing migration imports in my development environment and after testing I need to wipe the space for its data. To wipe all entries and content models manually takes time. Hence, the script.

Make sure you set the correct variables for space_id and environment_id before running the script

Code

Create a file name cleanup.js

require('dotenv').config()
const contentful = require('contentful-management')

const client = contentful.createClient({
accessToken: process.env.TOKEN
})

client.getSpace(process.env.SPACE)
.then((space) => space.getEnvironment(process.env.TEST_ENV))
.then((environment) => environment.getEntries())
.then((response) =>
response.items.forEach(element => {
element.delete()
.then(() => console.log('Entry deleted.'))
})
)
.catch(console.error)

I’m using the JS function to get all entries of a space and then iterate through them and delete the records. https://www.contentful.com/developers/docs/references/content-management-api/#/reference/entries/entries-collection/get-all-entries-of-a-space/console/js

You may have to execute this script a couple of times as it may skip entries tied with references.

If you are wondering what’s require(‘dotenv’).config() and why I’ve used process.env.SOME_NAME that’s because I’m using a npm package called Dotenv. It is a zero-dependency module that loads environment variables from a .env file.

process.env.TOKEN is content_management_api_key

process.env.SPACE is space_id

process.env.TEST_ENV is environment_id

The benefit of this is you can still commit your code while keeping your sensitive data secure locally without pushing to a repository.

--

--

Pasan Gamage
Pasan Gamage

Written by Pasan Gamage

Backend Developer | Motorbike enthusiast

No responses yet