Getting Types of Data created in Contentful CMS
This procedure is from Sean Davis’ “Generating Typescript Types from Contentful” youtube video. If you follow the steps from the video, you’ll get the expected result as of this writing, July 16, 2024. There’s just an additional step at the end due to changes in Contentful Type, specifically the EntrySkeletonType. Please note I’m doing this using NextJs app router folder structure.
I will be using the Contentful data created for the blog section of my website portfolio.
Install contentful-cli to export our data from contentful.npm install contentful-cli
Add this script to the package.json file. You can call the script however you want, but i’ll just copy the one from the video.
"cf-export": "contentful space export --config contentful/export-config.json --management-token <MANAGEMENT_TOKEN> --space-id <SPACE_ID>“
Before running the script:
- create a contentful folder and inside, create file export-config.json.
- Inside the export-config.json file, add these content:
{
"exportDir": "contentful", // which folder the exported file will be saved
3. Run the script,
"contentFile": "export.json", // name of the exported json file
"downloadAssets": true // this allows to download
}npm run cf-export
This will create the export.json file containing the date of our contentful model.
Next is to install type generator.npm install cf-content-types-generator
Add another script in package.json"cf-generate-types": "cf-content-types-generator contentful/export.json --out types/contentful"
This tells the generator to get the types of the contentful data from export.json and put the result in the folder types/contentful. *If you still don’t have this folder, it will be automatically created for you after you run the script.
Run the script, npm run c-generate-types.
That’s it! It will generate all the types of your content model.
In my case, there was still a type error showing.Type 'BlogEntry' does not satisfy the constraint 'EntrySkeletonType'.
To resolve this, just add a contentTypeId: string in the BlogEntry.
Property 'contentTypeId' is missing in type 'BlogEntry' but required in type 'EntrySkeletonType'.