Next.js Integration
-
Install required packages:
We have to install the following packages:
@content-collections/core@content-collections/next
pnpm add -D @content-collections/core @content-collections/next -
Adjust your
tsconfig.json:{ "compilerOptions": { // ... "paths": { "@/*": ["./*"], "content-collections": ["./.content-collections/generated"] } } }We require a path alias for the generated files. This is necessary because we will generate the files in the
.content-collections/generatedfolder. -
Modify your
next.config.js:const { withContentCollections } = require("@content-collections/next"); /** @type {import('next').NextConfig} */ const nextConfig = { // your next.js config }; module.exports = withContentCollections(nextConfig);This will add content collections to the build of your next.js app.
-
Create a
content-collections.tsfile at the root of your project:import { defineCollection, defineConfig } from "@content-collections/core"; const posts = defineCollection({ name: "posts", directory: "src/posts", include: "**/*.md", schema: (z) => ({ title: z.string(), summary: z.string(), }), }); export default defineConfig({ collections: [posts], });This file defines a collection named
postsin thesrc/postsfolder. The collection will include all markdown files (**/*.md) and the schema will validate thetitleandsummaryfields. -
Create your content files (e.g.:
src/posts/hello-world.md):--- title: "Hello world" summary: "This is my first post!" --- # Hello world This is my first post! ... rest of the contentYou can create unlimited content files. These files will be validated against the schema defined in the
content-collections.tsfile. If the files are valid, they will be automatically added to thepostscollection. -
Usage in your code:
import { allPosts } from "content-collections"; export function Posts() { return ( <ul> {allPosts.map((post) => ( <li key={post._meta.path}> <a href={`/posts/${post._meta.path}`}> <h3>{post.title}</h3> <p>{post.summary}</p> </a> </li> ))} </ul> ); }Now you can just import the
allPostscollection and use it in your code. TheallPostscollection will contain all posts that are valid. Thepostobject will contain thetitle,summaryandcontentfields as well as some meta information in the_metafield.