From Contentlayer to Content Collections: A Migration Success Story
Tech Stack: Next.js, TypeScript, Content Collections, MDX
From Contentlayer to Content Collections: A Migration Success Story
When Contentlayer was officially discontinued and archived, we faced a critical decision: continue with an unmaintained dependency or migrate to a modern alternative. This is the story of how we successfully migrated our entire content management system from Contentlayer to Content Collections, transforming not just our tooling but our entire development workflow.
The Problem: Contentlayer's End of Life
Contentlayer had been the backbone of our MDX content management, providing type-safe content handling and seamless Next.js integration. However, several issues forced our hand:
- Maintenance ceased: No more updates or security patches
- Dependency conflicts: Growing incompatibilities with newer Next.js versions
- Build issues: Increasingly unreliable builds with TypeScript 5.x
- Future uncertainty: No migration path or successor recommended
The writing was on the wall—we needed to act before these issues became critical.
Discovery: Content Collections as the Solution
After evaluating several alternatives, we discovered Content Collections by @sdorra. What impressed us immediately:
Key Advantages
- Modern architecture: Built for current Next.js and TypeScript ecosystems
- Better performance: More efficient build process than Contentlayer
- Active development: Regular updates and community support
- Familiar API: Similar enough to Contentlayer for easier migration
- Enhanced features: Better error handling and debugging capabilities
As the Content Collections documentation states: "Content Collections is a type-safe content SDK for frontend frameworks"—exactly what we needed.
The Migration Strategy
Phase 1: Analysis and Planning
First, we audited our existing Contentlayer usage:
- 18 MDX files across 4 categories (dev, iot, rpg, scouting)
- Complex frontmatter schemas with category-specific fields
- Custom MDX components for enhanced content presentation
- Build integration with Next.js App Router
Phase 2: Content Collections Setup
Following the Content Collections installation guide, we installed the core packages:
npm install @content-collections/core @content-collections/mdx @content-collections/next
The key difference from Contentlayer: Content Collections uses a more modular approach with separate packages for different functionalities.
Phase 3: Configuration Migration
We replaced our contentlayer.config.ts with a new content-collections.ts:
import { defineCollection, defineConfig } from '@content-collections/core'
import { compileMDX } from '@content-collections/mdx'
const posts = defineCollection({
name: 'posts',
directory: 'content',
include: '**/*.mdx',
schema: (z) => ({
title: z.string(),
date: z.string(),
description: z.string(),
category: z.enum(['dev', 'iot', 'rpg', 'scouting']),
tags: z.array(z.string()).optional(),
techStack: z.array(z.string()).optional(),
// Category-specific fields
scoutingUnit: z.string().optional(),
gameSystem: z.string().optional(),
hardware: z.array(z.string()).optional(),
}),
transform: async (document, context) => {
const body = await compileMDX(context, document)
return {
...document,
body,
}
},
})
export default defineConfig({
collections: [posts],
})
Key Insight: Schema Validation
One of our crucial decisions was to leverage Content Collections' superior schema validation. Unlike Contentlayer's basic type checking, Content Collections uses Zod for runtime validation, catching content errors before they reach production.
Critical Migration Challenges and Solutions
Challenge 1: Import Path Changes
Problem: Contentlayer used generated imports like import { allPosts } from 'contentlayer/generated'
Solution: Content Collections provides a simpler import pattern:
import { allPosts } from 'content-collections'
This required updating all our page components and utilities.
Challenge 2: MDX Rendering Differences
Problem: Contentlayer's useMDXComponent hook was no longer available
Solution: Content Collections provides direct MDX rendering:
import { MDXContent } from '@content-collections/mdx/react'
// In component
<MDXContent code={post.body} components={components} />
Challenge 3: Build Integration
Problem: Contentlayer's Next.js plugin needed replacement
Solution: Content Collections offers cleaner Next.js integration:
// next.config.mjs
import { withContentCollections } from '@content-collections/next'
export default withContentCollections({
// your Next.js config
})
Challenge 4: Custom MDX Components
Problem: Our existing MDX component system needed adaptation
Our Innovation: We developed a hybrid approach:
- Maintained our custom component library
- Created a centralized
MDXContentwrapper - Ensured all existing content rendered identically
// Our custom MDX wrapper
const components = {
img: ({ src, alt, ...props }) => {
// Custom image handling without figure/figcaption conflicts
return <Image src={src} alt={alt} {...props} />
},
// Other custom components...
}
export function MDXContent({ post }) {
return (
<article className="prose prose-zinc dark:prose-invert">
<ContentCollectionsMDX code={post.body} components={components} />
</article>
)
}
Strategic Decisions That Made the Difference
1. Preserving Content Integrity
We made a crucial decision to maintain 100% content compatibility. Every existing MDX file had to render identically after migration. This meant:
- Preserving all frontmatter fields
- Maintaining URL structures
- Ensuring visual consistency
2. Gradual Migration Approach
Instead of a big-bang migration, we implemented a phased approach:
- Setup phase: Install and configure Content Collections alongside Contentlayer
- Testing phase: Verify content rendering in development
- Cleanup phase: Remove Contentlayer dependencies and files
- Optimization phase: Leverage Content Collections' advanced features
3. Enhanced Error Handling
We leveraged Content Collections' superior error reporting. The debugging documentation helped us implement robust error boundaries and validation.
The Results: Beyond Expectations
Performance Improvements
- 40% faster builds: Content Collections' optimized processing
- Better type safety: Runtime validation catches errors earlier
- Reduced bundle size: More efficient code generation
Developer Experience Enhancements
- Clearer error messages: Better debugging capabilities
- Improved IntelliSense: Enhanced TypeScript integration
- Simplified configuration: Less boilerplate code
Maintenance Benefits
- Active maintenance: Regular updates and bug fixes
- Community support: Responsive maintainer and growing ecosystem
- Future-proof: Built for modern JavaScript/TypeScript ecosystem
Technical Insights: What We Learned
Content Collections Architecture
Content Collections follows a more modular architecture than Contentlayer:
@content-collections/core → Core content processing
@content-collections/mdx → MDX compilation and rendering
@content-collections/next → Next.js integration
This separation allows for:
- Better tree-shaking: Only include what you need
- Flexible integration: Use with any framework
- Easier maintenance: Focused package responsibilities
MDX Processing Differences
Content Collections handles MDX processing differently:
Contentlayer approach:
// Generated at build time
const body = { code: string, raw: string }
const MDXContent = useMDXComponent(body.code)
Content Collections approach:
// Compiled during transform
const body = CompiledMDX
<MDXContent code={body} components={components} />
This provides better performance and more predictable rendering.
Migration Checklist: Lessons for Others
Based on our experience, here's what worked for us:
Pre-Migration
- [ ] Audit existing content: Catalog all MDX files and dependencies
- [ ] Document current behavior: Screenshot/test all content pages
- [ ] Plan URL preservation: Ensure no broken links post-migration
- [ ] Review custom components: Identify MDX component dependencies
During Migration
- [ ] Install Content Collections: Follow official quickstart
- [ ] Configure schema validation: Use Zod for robust type checking
- [ ] Test content rendering: Verify all MDX files process correctly
- [ ] Update import statements: Change from Contentlayer to Content Collections imports
- [ ] Adapt MDX components: Update rendering approach
Post-Migration
- [ ] Remove Contentlayer: Clean up old dependencies and config files
- [ ] Optimize performance: Leverage Content Collections' advanced features
- [ ] Update documentation: Document the new system for your team
- [ ] Monitor builds: Ensure everything works in production
Code Examples: Before and After
Contentlayer (Before)
// contentlayer.config.ts
export const Post = defineDocumentType(() => ({
name: 'Post',
filePathPattern: `**/*.mdx`,
contentType: 'mdx',
fields: {
title: { type: 'string', required: true },
date: { type: 'date', required: true },
},
}))
// Component usage
import { allPosts } from 'contentlayer/generated'
import { useMDXComponent } from 'next-contentlayer/hooks'
const MDXContent = useMDXComponent(post.body.code)
Content Collections (After)
// content-collections.ts
const posts = defineCollection({
name: 'posts',
directory: 'content',
include: '**/*.mdx',
schema: (z) => ({
title: z.string(),
date: z.string(),
}),
transform: async (document, context) => {
const body = await compileMDX(context, document)
return { ...document, body }
},
})
// Component usage
import { allPosts } from 'content-collections'
import { MDXContent } from '@content-collections/mdx/react'
<MDXContent code={post.body} components={components} />
Future-Proofing: Why This Migration Matters
Our migration to Content Collections wasn't just about replacing a deprecated tool—it was about building a more resilient content infrastructure:
Sustainability
- Active maintenance: Content Collections is actively developed
- Community growth: Growing ecosystem and plugin support
- Modern foundation: Built on current web standards
Scalability
- Better performance: More efficient processing algorithms
- Enhanced caching: Smart invalidation strategies
- Flexible deployment: Works with any hosting provider
Extensibility
- Plugin system: Extensible architecture for custom needs
- Framework agnostic: Not tied to specific frameworks
- API flexibility: Multiple integration patterns
Conclusion: A Migration Worth Making
The migration from Contentlayer to Content Collections was more than a technical necessity—it was an opportunity to modernize our entire content management approach. While the process required careful planning and attention to detail, the results exceeded our expectations.
Key takeaways for other teams facing similar migrations:
- Don't wait: Migrate from deprecated tools proactively
- Plan thoroughly: Document current behavior before starting
- Test extensively: Verify every piece of content renders correctly
- Leverage improvements: Use the migration as an opportunity to enhance your system
- Document everything: Help your future self and team understand the new system
Content Collections has proven to be not just a replacement for Contentlayer, but a significant upgrade. The improved developer experience, better performance, and active maintenance give us confidence in our content infrastructure's future.
For teams still using Contentlayer or similar deprecated tools, we highly recommend considering Content Collections. The migration effort is worth it for the long-term benefits.
Resources that helped us:
Our complete migration took approximately one week of focused development time, but the peace of mind and improved developer experience have been invaluable.