website-logomedCode

How to fetch data from Strapi API in server side Next.js 14

Uncover the secrets of efficiently fetching data from Strapi API in Server-Side Next.js 14. Elevate your development skills with expert guidance!...
MOHAMMED DAKIR| April 7, 2024
tools
How to fetch data from Strapi API in server side Next.js 14

#Next.js #Strapi #Server-side

Introduction to Next.js and Strapi

Next.js and Strapi are two powerful tools in the modern web development ecosystem. Next.js is a React framework that enables the creation of server-side rendered (SSR) and statically generated React applications, while Strapi is a flexible headless CMS (Content Management System) that allows developers to build APIs quickly and efficiently. In this article, we'll explore how to fetch data from a Strapi API on the server-side in a Next.js application.

Server-side Data Fetching in Next.js

In Next.js, server-side data fetching is typically performed using the getServerSideProps function. This function runs on the server side and fetches data before rendering the page, ensuring that the data is available when the page is rendered. By fetching data on the server side, you can improve performance and ensure that your content is SEO-friendly.

Fetching Data from Strapi API

To fetch data from a Strapi API in Next.js, you can use the fetch API or a library like Axios. Simply make an HTTP request to the desired Strapi endpoint, and parse the JSON response. You can then pass the fetched data to your Next.js components for rendering.

step 1:

create a Strapi project :

npx create-strapi-app my-app --quickstart

documentation strapi

step2 :

create Next.js app :

npx create-next-app@latest

step 3:

Preparing the environment variables:

Next.js has support for loading environment variables into your project. Simply create a .env.development file at the root of the frontend folder and paste in this snippet:

NEXT_PUBLIC_BASE_URL=http://localhost:1337
NEXT_PUBLIC_REST_API_KEY=bc8700420ab5627c5cd5c7710fda91af350246d231b3e4d7a637f90f16744d19935db928b5611032667b70246a30c5975f393c817259d9f33ab6554337ebb6d8b65d92986cd1feaa96baa830922734ef64cc2c2100a44bcfacb42e31fd1f32829b9698fe009cfcf372efa9587e690021f8bd21d3a9e205d7f77b5b0577a7d387

this a example API_KEY you can get one from your project by adding new API token and get your private key

step 4 :

create a app/utils folder in inside the folder create a file AxiosFetching.js

const { default: axios } = require("axios");

const apiKey = process.env.NEXT_PUBLIC_REST_API_KEY;
const apiUrl = "http://localhost:1337/api";

// api tokens options
const axiosClient = axios.create({
  baseURL: apiUrl,
  headers: {
    Authorization: `Bearer ${apiKey}`,
  },
});
// fetch All product
const getProducts = async () => {
  const headers = {
    Authorization: `Bearer ${apiKey}`,
  };
  const response = await axios.get(`${apiUrl}/products?populate=*`, {
    headers,
  });
  const data = response.data.data;
  return data;
};
export default { getProducts  };

step 5 :

create a products folder app/products inside products page create page.js:

import React from "react";
import AxiosClient from "@/app/utils/AxiosClient";
export default async function page() {
  const product = await AxiosClient.getProducts();
  return (
    <div className="font-[sans-serif] bg-light">
      <h1>Single page</h1>
       <div className="grid grid-cols-3 gap-10 items-center p-6">
         {product.map((item)=>{
          //fetch data here
            })}
      </div>
    </div>
  );
}

Conclusion:

Fetching data from the Strapi API in a Next.js application allows you to build dynamic and interactive web applications with ease. By leveraging the server-side rendering capabilities of Next.js, you can improve performance and SEO while maintaining a great user experience. Experiment with fetching data from various endpoints of the Strapi API and see how you can enhance your Next.js application.


This website uses cookies to enhance your browsing experience, analyze site traffic, and serve better user experiences. By continuing to use this site, you consent to our use of cookies. Learn more in our cookie policy

Explore the latest insights, articles,free components, and expert advice on programming and software development

© Copyright 2024 MED DAKIR. All rights reserved./privacy policy