Content Management systems are all the rage today, as they help businesses manage their content across different pages and websites efficiently. Strapi is a popular CMS that can be used to have dynamic websites and content for your web pages. If you have already chosen Strapi for your content needs, you have done the right thing, but next, you have to make integration decisions.

Strapi provides REST and GraphQL APIs that can be used to fetch data and content on runtime and load them on your page. While both of these API approaches are different, you can use them in your Next.js projects easily. In this article, we will explore how you can fetch strapi content using REST and GraphQL APIs.

What are Strapi APIs?

Being a headless CMS, Strapi provides APIs that you can use to manage content on the system. Strapi provides both REST and GraphQL APIs that can be consumed in a next.js project.

  • Strapi REST API: Strapi creates a new URL for every content item added to the platform and provides a way to fetch and update the content items using the REST API style. It supports the standard HTTP methods for managing content, takes care of pagination and filtering, and also does routing for your incoming requests.
  • Strapi GraphQL API: GraphQL is a new approach to creating APIs that provides a single endpoint for all queries. With GraphQL, you can query only the required data, and you don’t need to make expensive API calls that return lots of irrelevant data. The GraphQL system will handle nested and related data queries pretty easily, and it will also generate the schema based on content types that are added to the database.
  • Having learned about different strapi APIs, it is time to learn how you can integrate Next.js with the REST and GraphQL APIs.

How To Fetch Strapi Content in Next.js Using Rest API

1. Set Up Strapi

  • Before you begin anything in this project, you need to set up strapi in your instance. This can be done by running a Strapi instance with one published post collection. Once you start your local Strapi instance, you can view all posts on the /posts endpoint with a GET request.

2. Create a new Next.js Project

  • Once your Strapi service is running locally, you should create a new Next.js project. This project will host all your code to fetch content from the REST API. Open a terminal and run the below commands to create a new project.
  • npx create-next-app cd
  • The first command will use npx create-next-app to create a simple next.js project. You can change the project name to anything you like in the command, and it will create your project in a new folder. Once npx has completed creating the project, you should move to the newly created project directory and open a code editor of your choice.

3. Authentication

  • If your Strapi API requires authentication before it can serve any requests, you should add your bearer access token in the request header. Below is a sample code block on how you can do that.
  • const res = await fetch('http://localhost:1337/api/posts', { headers: { Authorization: 'Bearer YOUR_ACCESS_TOKEN', }, });
  • Add your access token to the authorization header in this request before sending the request. If you pass the correct access token, your Strapi API will allow you to fetch posts or make any changes to them.

4. Fetch Strapi Content Using REST

  • Now, it is time to write code to fetch Strapi content in your next.js project. In your code editor, create a new file named posts.js, and add the following code to your new file.

        // pages/posts.js
        export async function getServerSideProps() {
            const res = await fetch('http://localhost:1337/api/posts');
            const { data } = await res.json();
            return {
                props: {
                    posts: data,
                },
            };
        }

        const Posts = ({ posts }) => {
            return (
            
                Posts
                
                    {posts.map((post) => (
                    
                        {post.attributes.title}
                        {post.attributes.content}
                    
                    ))}
                
            
            );
        };

        export default Posts;
    
  • The above will help to ensure code quality where every request gets the latest content from your Strapi instance.
  • At this point, you know how to fetch content using Strapi REST API, but if you want to use GraphQL AP, stick around for some more time. In the next section, we will explore how to fetch Strapi content using GraphQL API.

How To Fetch Strapi Content Using GraphQL API

1. Setup

  • When using GraphQL API for Strapi Content, you need a significant setup in the form of plugins and libraries to get it working. To get started, you need to install the Strapi GraphQL plugin and Apollo client for GraphQL.
  • Run the below command to install the Strapi GraphQL Plugin npm install @strapi/plugin-graphql
  • Run the below command to install the Apollo client for GraphQL npm install @apollo/client graphql

How To Fetch Strapi Content Using GraphQL API

2. Create New Project

  • For the GraphQL API, You should create a new Next.js project. Open a terminal and run the below commands to create a new project.
  • npx create-next-app cd
  • The first command will create a simple next.js project, and the next one will move you to the newly created project directory.

3. Fetch Strapi Content

  • Once you are in the code editor, you need to create a setup file for your Apollo client. Create a new file in the lib folder named apollo-client.js, and add the below code to it.

        import { ApolloClient, InMemoryCache } from '@apollo/client';

        const client = new ApolloClient({
            uri: 'http://localhost:1337/graphql', // Replace with your Strapi GraphQL URL
            cache: new InMemoryCache(),
        });

        export default client;
    

Now, write the code below in another file to fetch your data and even use the Apollo client.


        import { gql } from '@apollo/client';
        import client from '../lib/apollo-client';

        export async function getServerSideProps() {
            const { data } = await client.query({
                query: gql`
                query GetPosts {
                    posts {
                        data {
                            id
                            attributes {
                                title
                                content
                            }
                        }
                    }
                }
                `,
            });

            return {
                props: {
                    posts: data.posts.data,
                },
            };
        }

        const Posts = ({ posts }) => {
            return (
            
                Posts
                
                    {posts.map((post) => (
                    
                        {post.attributes.title}
                        {post.attributes.content}
                    
                    ))}
                
            
            );
        };

        export default Posts;
    
  • This code will use the Apollo client to fetch posts per incoming requests.

Performance Comparison

Knowing about both the API types, it is also important to know their performance. So, let’s do a comparison between GraphQL and REST APIs.

1. Data Retrieval

  • When you want a smooth data retrieval approach and always fetch the right things without worrying about hitting rate limits, you should consider adopting GraphQL APIs. REST endpoints are faster, but they aren't always the best choice.

2. Number of Requests

  • With graphQL, you can fetch related data in a single request, and this will reduce the number of requests hitting the backend services. On the other hand, when you use REST APIs, you will have to send a new request for each piece of data.
  • Before signing off, we should also know which of these is better for your needs.

Which Of The Two Is Better?

If you want to query multiple posts and minimize backend requests, you should adopt GraphQL APIs for your Strapi CMS. As GraphQL is a new technology, it comes with more features, and you can customize it for your changing needs.

Compared to this, if your teams are well-versed with REST endpoints and can create custom endpoints and queries to fetch different content, you should work with Strapi’s REST API endpoint.

You might also like: