intermediate#next.js#headless cms#strapi
Using Next.js with a Headless CMS
Learn how to use Next.js with a headless CMS, such as Strapi or Ghost.
Introduction to Headless CMS
A headless CMS is a content management system that provides a RESTful API for managing content, allowing developers to use their preferred frontend framework, such as Next.js.
Step 1: Create a New Next.js Project
To start, create a new Next.js project using npx create-next-app my-cms.
npx create-next-app my-cms
cd my-cms
Step 2: Install Required Dependencies
Install the required dependencies, including axios.
npm install axios
Step 3: Configure Strapi
Configure Strapi by creating a new Strapi project and setting up a new content type.
// pages/api/cms.js
import axios from 'axios';
const api = axios.create({
baseURL: 'https://your-strapi-domain.com/api',
});
const getPosts = async () => {
const response = await api.get('/posts');
return response.data;
};
export default getPosts;
Step 4: Fetch Data from Strapi
Fetch data from Strapi using the getStaticProps method.
// pages/index.js
import { GetStaticProps } from 'next';
import { getPosts } from '../api/cms';
const Home = ({ posts }) => (
<div>
{posts.map((post) => (
<div key={post.id}>{post.title}</div>
))}
</div>
);
export const getStaticProps: GetStaticProps = async () => {
const posts = await getPosts();
return {
props: {
posts,
},
};
};
export default Home;
Conclusion
In this tutorial, you learned how to use Next.js with a headless CMS, such as Strapi or Ghost.