Part 52: Integrating Strapi with a Next.js Application: A Step-by-Step Guide

[App] Headless CMS

[App] Headless CMS

In modern web development, decoupling your frontend and backend is a common practice, allowing for more flexibility and scalability. In this post, we’ll explore how to integrate a Strapi CMS instance with a Next.js application, focusing on fetching and displaying data from Strapi's API. For this example, we'll assume you have a Strapi instance running with 25 pre-existing reviews.

Setting Up the Environment

Before diving into the code, ensure you have both your Strapi and Next.js servers running:

  • Strapi Server: Running on port 1337.

  • Next.js Server: Running on port 3000.

With these servers running, we can focus on modifying our Next.js application to fetch data from Strapi.

Modifying the Next.js Application

Current Setup

In our current setup, the reviews are stored in local Markdown files, and our code uses functions like getReviews, getSlugs, and getReview to load and parse these files. Our goal is to replace this setup with API requests to Strapi.

Using Fetch to Call the Strapi API

To fetch data from the Strapi API, we’ll use the fetch function, which is available globally in modern JavaScript environments, including Node.js. This function allows us to make HTTP requests and handle responses asynchronously.

Creating a Test Script

Before altering the existing code in our Next.js application, let's create a separate script to test our API requests. This way, we can verify the data retrieval process independently.

  1. Create a Scripts Folder: In your project, create a new folder named scripts.

  2. Write a Test Script: Create a file named strapi-request.mjs in the scripts folder. Use the .mjs extension to enable ES modules in Node.js, allowing the use of import statements.

import { writeFileSync } from 'node:fs';

const url = 'http://localhost:1337/api/reviews?populate=*';
const response = await fetch(url);
const body = await response.json();
console.log(JSON.stringify(body, null, 2));
const formatted = JSON.stringify(body, null, 2);
const file = 'scripts/strapi-response.json';
writeFileSync(file, formatted, 'utf8');

Running the Test Script

To execute the test script:

  1. Stop the Next.js Dev Server: Temporarily stop your Next.js server to free up the terminal.

  2. Run the Script: Execute the script using Node.js.

node scripts/strapi-request.mjs

This script fetches data from the Strapi API, writes the response to a JSON file, and allows you to inspect the data structure and attributes.

Understanding the API Response

The response from Strapi includes a data array, where each review is an object with attributes such as slug, title, and body. By default, relational fields like images are not included in the response. Using the populate=* query parameter ensures all related data, such as images, is included.

Next Steps

Now that we have successfully fetched and understood the API response, the next steps involve integrating this data retrieval process into our Next.js application:

  1. Replace Local Data Fetching: Modify functions like getReviews to call the Strapi API instead of reading local files.

  2. Optimize Data Fetching: In future iterations, consider selecting only the fields you need to minimize data transfer and improve performance.

  3. Dynamic Rendering: Use the fetched data to dynamically render the reviews page in your Next.js application, providing a seamless and updated user experience.

Conclusion

Integrating Strapi with a Next.js application offers a robust solution for managing and displaying content. By leveraging Strapi's API, you can centralize content management while maintaining the flexibility of a decoupled frontend. As you continue to develop your application, explore more advanced features like pagination and selective data fetching to optimize performance and user experience.

Last updated