Build Type-Safe Static Sites with Contentlayer: A Practical Tutorial

Contentlayer bridges the gap between your content files (Markdown, MDX, JSON, YAML) and your static site code. It generates typed data from your content, enabling autocompletion and error checking in editors like VS Code. This makes static site development faster and more reliable.

To get started, install Contentlayer in your Next.js, Gatsby, or Astro project. For Next.js, run npm install contentlayer next-contentlayer and add it to your next.config.js. After the second paragraph, insert the image placeholder as specified.

Article illustration

Define Your Content Schema

Create a contentlayer.config.ts file at your project root. Define a Document type for each content collection. For example, a blog post might include fields like title, date, and tags:

  • Write defineDocumentType with name: 'Post'
  • Set filePathPattern: '**/*.md'
  • Define fields using field: { type: 'string', required: true }

Place Content and Generate Types

Store your Markdown files in a dedicated content folder (e.g., /content/posts). Run npx contentlayer build to generate typed data and a JSON representation of your content. Contentlayer creates a .contentlayer folder with generated files you can import directly into your components.

Query Content in Components

Import the generated allPosts (or your collection name) into any page or component. Example in Next.js:

  • import { allPosts } from 'contentlayer/generated'
  • Map over allPosts to render a list of blog cards
  • Access fields with autocompletion: post.title, post.date

Contentlayer also supports MDX with embedded React components, and live reload via watch mode (npx contentlayer dev).

Conclusion

Contentlayer simplifies static site development by providing type-safe content that integrates seamlessly with your preferred framework. Start small—define one collection, generate types, and enjoy the productivity boost of a fully typed content pipeline.

sarah antaboga
Author: sarah antaboga

Leave a Reply

Your email address will not be published. Required fields are marked *