To fetch Payload CMS data at build time (SSG) and at request time (SSR) in Next.js.
Steps:
- Set Up a Payload CMS Collection
payload.config.ts:
ts
Copy
Edit
const Articles: CollectionConfig = {
slug: 'articles',
fields: [
{
name: 'title',
type: 'text',
required: true,
},
{
name: 'content',
type: 'richText',
},
],
};
export default Articles;
- Fetch Data at Build Time (SSG)
pages/blog.tsx:
tsx
Copy
Edit
import { GetStaticProps } from 'next';
export const getStaticProps: GetStaticProps = async () => {
const res = await fetch('http://localhost:3000/api/articles');
const data = await res.json();
return {
props: {
articles: data.docs,
},
revalidate: 10,
};
};
const BlogPage = ({ articles }) => {
return (
<div>
<h1>Blog</h1>
{articles.map((article) => (
<div key={article.id}>
<h2>{article.title}</h2>
<p>{article.content}</p>
</div>
))}
</div>
);
};
export default BlogPage;
- Fetch Data on Each Request (SSR)
pages/article/[id].tsx:
tsx
Copy
Edit
import { GetServerSideProps } from 'next';
export const getServerSideProps: GetServerSideProps = async ({ params }) => {
const res = await fetch(`http://localhost:3000/api/articles/${params.id}`);
const article = await res.json();
return {
props: {
article,
},
};
};
const ArticlePage = ({ article }) => (
<div>
<h1>{article.title}</h1>
<p>{article.content}</p>
</div>
);
export default ArticlePage;