Skip to content

Adding a slug field to an existing content type

Sam Bauers edited this page Aug 29, 2022 · 3 revisions

This migration script uses the slugify NPM package, which can be installed with:

$ npm install --save-dev slugify

This script edits an existing content type called page. It creates a short text field called slug, with a slugEditor field control which sources its initial value from the title field when new entries are created.

The script also fetches all the existing page entries and populates the new slug field for each.

import type { MigrationFunction } from 'contentful-migration'
import slugify from 'slugify'

const migrationFunction: MigrationFunction = function (migration) {
  // get the page content type
  const page = migration.editContentType('page')

  // add a slug field after the title field
  page
    .createField('slug')
    .type('Symbol')
    .name('Slug')
    .required(true)
    .validations([{ unique: true }])
  page.changeFieldControl('slug', 'builtin', 'slugEditor', {
    trackingFieldId: 'title',
  })
  page.moveField('slug').afterField('title')

  // populate the slug field with a slugified title from the existing entries
  migration.transformEntries({
    contentType: 'page',
    from: ['title'],
    to: ['slug'],
    shouldPublish: true,
    transformEntryForLocale: (fromFields, currentLocale) => {
      const title = fromFields.title[currentLocale]
      return typeof title === 'string'
        ? { slug: slugify(title, { lower: true, strict: true }) }
        : undefined
    },
  })
}

export = migrationFunction