npx create-strapi-app my-app --quickstart
npx create-next-app@latest
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
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 };
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>
);
}
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