Search code examples
reactjscontentfulnext.js13headless-cms

Need help setting up Contentful headless cms with Nextjs 13 using the new app directory


I am currently teaching myself how to fetch content in NextJs 13 using the new app directory instead of the old pages directory. I am building a mock recipe app that will pull data from Contentful. The traditional method is to use the pages directory utilizing the getStaticProps() method. That is no longer supported in the app directory. The app directory supports the fetch api. Can someone help me set this up properly.

Here is my current code in the main page.tsx file

import { createClient } from 'contentful';

const client = createClient({
  space: process.env.CONTENTFUL_SPACE_ID as string, 
  accessToken: process.env.CONTENTFUL_ACCESS_KEY as string, 
});

async function getData() {
  const res = await fetch(
    `https://cdn.contentful.com/spaces/${process.env.CONTENTFUL_SPACE_ID}/entries?access_token=${process.env.CONTENTFUL_ACCESS_KEY}&content_type=recipe`
  );

  return res.json()
}


export default async function Recipes() {
const data = await getData();
console.log(data)
  return (
    <div className='recipe-list'>
      Recipe List
    </div>
  )
}

I'm not even sure if I need createClient


Solution

  • You don't need createClient with the new fetch API.

    First of all your page.tsx needs to be under /app/recipes/page.tsx if you want the route for the recipes to be www.yourdomain.com/recipes.

    And then try this code in your page.tsx to see if you get what you want. Otherwise I need more information as to what is not working as expected.

    async function getRecipes() {
      const res = await fetch(
        `https://cdn.contentful.com/spaces/${process.env.CONTENTFUL_SPACE_ID}/entries?access_token=${process.env.CONTENTFUL_ACCESS_KEY}&content_type=recipe`
      );
    
      return res.json()
    }
    
    
    export default async function Recipes() {
    const recipes = await getRecipes();
    
      return (
        <ul>
          {recipes.map((recipe) => (
            <li key={recipe.id}>{recipe.name}</li>
          ))}
        </ul>
      );
    }

    make sure to change recipe.id and recipe.name to whatever fields you have created in Contentful.

    Please run the local development server and then go to localhost:3001/recipes to see if it works.