Integrating Payload CMS with Next.js API Routes

To create a custom API route in Next.js to interact with Payload CMS.

Steps:

  1. Create an API Route in Next.js
ts

Copy

Edit
import { NextApiRequest, NextApiResponse } from 'next';
import payload from 'payload';

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  await payload.init({ secret: process.env.PAYLOAD_SECRET });

  if (req.method === 'GET') {
    const posts = await payload.find({
      collection: 'posts',
      where: {},
    });

    return res.status(200).json(posts);
  }

  return res.status(405).json({ message: 'Method Not Allowed' });
}
  1. Fetch Data in a Next.js Page
tsx

Copy

Edit
import { useEffect, useState } from 'react';

const BlogPage = () => {
  const [posts, setPosts] = useState([]);

  useEffect(() => {
    fetch('/api/posts')
      .then((res) => res.json())
      .then((data) => setPosts(data.docs));
  }, []);

  return (
    <div>
      <h1>Blog Posts</h1>
      {posts.map((post) => (
        <div key={post.id}>
          <h2>{post.title}</h2>
          <p>{post.content}</p>
        </div>
      ))}
    </div>
  );
};

export default BlogPage;

Leave a comment

Your email address will not be published. Required fields are marked *