FAQ

How to get all unused components?

You can get a list of all unused components of a space by utilizing our management API. We’ve prepared following Node.js script for you. You will than receive an array of used and unused components as a result:

// Install dependency: npm install storyblok-js-client
const StoryblokClient = require('storyblok-js-client')

// This token allows CRUD operations to all your spaces and can be found in the
// "my account" section of our app: https://app.storyblok.com/#!/me/account
// DO NOT COMMIT THAT OAUTHTOKEN!!
const oauthToken = 'your_oauth_token'

// Initialize the client with the oauth token
const Storyblok = new StoryblokClient({
  oauthToken: oauthToken
})

// The space id you want to check - can be found in your spaces settings
const spaceId = '51455'

const start = async () => {
  let usedComponents = []
  let unusedComponents = []

  // Some more output, so you see what is going on here
  console.log('Loading list of components')

  // load information of first 100 components - otherwise we would need to use paging as 100 is max.
  let components = await Storyblok.get(`spaces/${spaceId}/components/`, { per_page: 100 })

  // Some more output, so you see what is going on here
  console.log('Looking for unused components')

  // loop through all components
  for (let index = 0, max = components.data.components.length; index < max; index++) {
    let component = components.data.components[index];  

    // call the management api with the contain_component query parameter and the per_page
    // parameter 1 to reduce payload and speed up to process even tho it is sync
    let stories = await Storyblok.get(`spaces/${spaceId}/stories/`, {
      contain_component: component.name,
      per_page: 1
    })
    
    // check if at least one story returned; if no story would contain a component
    // the stories array of the call above would be empty, and assign component accordingly.
    if (stories.data.stories.length > 0) {
      usedComponents.push(component.name)
    } else {
      unusedComponents.push(component.name)
    }

    // Some more output, so you see what is going on here
    console.log(`Looking for unused components (${index + 1}/${max})`)
  }

  // Output
  console.log('Used Components: ', usedComponents)
  console.log('Unused Components: ', unusedComponents)
}

start()