Integrate contentful CMS in Nextjs
Devmnj • Wed Oct 19 2022
0 min read
The Client
Create and export the client and then we can use the module to make calls to the API.
Source code
npm i contentful
Source code
import {createClient} from 'contentful'
const client=createClient({
space:'space 🆔 ',
accessToken:'api-token'
});
export {client}
Nextjs API
I tried to directly using the client in app, but it doesn't work for me. So have to create a internal API.
Under pages/api/posts create two route, one for all posts and another for dynamic / individual posts.
Source code
// index.js
import {client} from "../../../contentful";
export default async function index(req, res) {
const r = await client.getEntries();
return res.status(200).json(r)
}
import {client} from "../../../contentful";
export default async function id(req, res) {
const
{
id
} = req.query;
const r = await client.getEntry(id);
return res.status(200).json(r)
}
try to access the the API https:// localhost:3000/api/posts
In the route and components
In the Nextjs route / component, as usual we can fetch data in getStaticProps as follows and pass it to the component. The fetching will run on the top.
Source code
import PostGrid from "../Components/PostGrid";
import {GridSkelton} from "../Components/Skeltons";
export async function getStaticProps(context) {
const res = await fetch('http:localhost:3000/api/posts')
const posts = await res.json() ;
return {
props: {
data:posts ,
}
}
}
export default function Home({data}) {
return (
<div >
{/*{JSON.stringify(data)}*/}
{data ? <PostGrid posts={data.items} />:<GridSkelton/> }
</div>
)
}
Dynamic route
For dynamic route, we have to configure the staticpaths too. This will help static generation.
Source code
//pages/posts/[id].js
import { useRouter } from 'next/router'
import SinglePost from "../../Components/SinglePost";
import {GridSkelton} from "../../Components/Skeltons";
export async function getStaticPaths() {
const res= await fetch('http:localhost:3000/api/posts')
const posts = await res.json() ;
const paths = posts.items.map((post) => ({
params: { id: post.sys.id },
}))
return {
paths,fallback: true // false or 'blocking'
};
}
export async function getStaticProps({params}) {
console.log(params)
const res = await fetch(`http:localhost:3000/api/posts/${params.id}`)
const post = await res.json() ;
return {
props: {
post:post ,
}
}
}
const Post = ({post}) => {
const router = useRouter()
const { pid } = router.query
return <>
{ post ? <SinglePost post={post}/>:<GridSkelton/>}
</>
}
export default Post
Tags :
nextjs