Next.js
AstraCMS integration for Next.js
The @astracms/next package provides optimized utilities for using AstraCMS with Next.js, including server components support and automatic caching.
Installation
npm install @astracms/nextpnpm add @astracms/nextyarn add @astracms/nextbun add @astracms/nextEnvironment Variables
Create a .env.local file in your Next.js project:
ASTRACMS_API_KEY=your_api_key_hereConfiguration
Create a client instance in your app:
import { createAstraCMSClient } from '@astracms/next'
export const astracms = createAstraCMSClient({
apiKey: process.env.ASTRACMS_API_KEY!,
})Server Components
Use the client directly in server components:
import { astracms } from '@/lib/astracms'
export default async function BlogPage() {
const posts = await astracms.getPosts()
return (
<ul>
{posts.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
)
}With Caching
Enable Next.js caching for optimal performance:
const posts = await astracms.getPosts({
next: { revalidate: 60 }, // Revalidate every 60 seconds
})Static Generation
For fully static sites:
import { astracms } from '@/lib/astracms'
import { notFound } from 'next/navigation'
export async function generateStaticParams() {
const posts = await astracms.getPosts()
return posts.map((post) => ({ slug: post.slug }))
}
export default async function PostPage({
params
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
const post = await astracms.getPost(slug)
if (!post) {
notFound()
}
return <article>{post.content}</article>
}Filtering Posts
The getPosts function supports filtering options:
import { getPosts } from '@astracms/next'
export default async function TechBlogPage() {
const posts = await getPosts({
categories: ['technology', 'tutorials'], // Filter by categories
excludeCategories: ['internal'], // Exclude categories
tags: ['javascript', 'react'], // Filter by tags
excludeTags: ['draft'], // Exclude tags
query: 'search term', // Search query
format: 'html', // Content format
limit: 10, // Max posts
page: 1, // Pagination
})
return (
<ul>
{posts.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
)
}Available Options:
| Option | Type | Description |
|---|---|---|
categories | string[] | Filter by category slugs |
excludeCategories | string[] | Exclude category slugs |
tags | string[] | Filter by tag slugs |
excludeTags | string[] | Exclude tag slugs |
query | string | Search query |
format | 'html' | 'markdown' | Content format |
limit | number | Max posts to return |
page | number | Page number |
Last updated on