Table of Contents
Strapi is an open-source headless CMS that allows you to manage your content and integrate it with any frontend framework. Next.js is a powerful React framework that provides features like server-side rendering and static site generation. Combining Strapi and Next.js allows you to build robust and dynamic web applications. In this guide, we will set up a Next.js application with Strapi as the backend.
Prerequisites
Ensure you have the following installed:
- Node.js
- npm or yarn
Steps for Building a Next.js Application with Strapi
Step 1: Setting Up Strapi
Create a new Strapi project using the following command
npx create-strapi-app my-strapi-app --quickstart
cd my-strapi-app
Step 2: Creating Content Types in Strapi
To manage content in Strapi, you’ll need to create content types using the Strapi Admin Panel. Follow these detailed steps to create a content type called “Article” and populate it with data.
Accessing the Strapi Admin Panel
- Start Strapi Development Server
Ensure your Strapi server is running. If you haven’t started it yet, navigate to your Strapi project directory (my-strapi-app) and run:
npm run develop # or yarn develop
- The development server will start, and Strapi will automatically open the Admin Panel in your default browser at http://localhost:1337/admin.
- Log in or Register: If this is your first time using Strapi, you’ll need to register an admin user. Fill out the registration form and log in to the Admin Panel.
Creating a Content Type
- Open Content-Type Builder: In the Strapi Admin Panel, navigate to the Content-Type Builder from the left sidebar.
- Create New Content Type: Click the “Create new collection type” button.
- Configure Content Type:
- Display Name: Enter “Article”.
- API ID: This will be automatically generated based on the Display Name.
- Description: (Optional) Add a description if desired.
- Click the “Continue” button.
- Add Fields to Content Type: You’ll be prompted to add fields to your new content type.
- Title:
- Click on “Text” under “Basic”.
- In the right sidebar, configure the field:
- Name: Enter “Title”.
- Type: Ensure “Short text” is selected.
- Click the “Finish” button.
- Content:
- Click on “Rich Text” under “Basic”.
- In the right sidebar, configure the field:
- Name: Enter “Content”.
- Click the “Finish” button.
- Slug:
- Click on “UID” under “Basic”.
- In the right sidebar, configure the field:
- Name: Enter “Slug”.
- Attached Field: Select “Title” (this will auto-generate the slug based on the title).
- Click the “Finish” button.
- Title:
- Save the Content Type: After adding the fields, click the “Save” button in the top right corner of the screen. Strapi will prompt you to restart the server to apply the changes. Confirm the restart.
Adding Content
- Open Content Manager: Navigate to the Content Manager from the left sidebar.
- Create New Article:
- In the Content Manager, you should see the “Articles” collection type.
- Click on “Articles”.
- Click the “Add New Article” button.
- Fill in Article Details:
- Title: Enter the title of your article.
- Content: Add the content using the rich text editor.
- Slug: This will be auto-generated based on the title, but you can customize it if needed.
- Save and Publish: Click the “Save” button to save the article as a draft or “Publish” to make it live.
Useful Links
- Strapi Documentation – Content-Type Builder
- Strapi Documentation – Content Manager
- Strapi Documentation – Quick Start Guide
By following these steps, you can create and manage content types in Strapi, which will be used to populate your Next.js application with dynamic content.
Step 3: Setting Up the Next.js Project
Create a new Next.js project
npx create-next-app my-nextjs-app # or yarn create next-app my-nextjs-app
cd my-nextjs-app
Step 4: Fetching Data from Strapi
Install Axios for making HTTP requests
npm install axios # or yarn add axios
Create a file lib/api.js to handle API requests to Strapi
// lib/api.js import axios from 'axios'; const strapiUrl = process.env.STRAPI_URL || 'http://localhost:1337'; export const fetchAPI = async (path) => { const requestUrl = `${strapiUrl}${path}`; const response = await axios.get(requestUrl); return response.data; };
Step 5: Creating Pages to Display Data
Fetch and display articles on the home page. Update pages/index.js
// pages/index.js import { fetchAPI } from '../lib/api'; const Home = ({ articles }) => { return ( <div> <h1>Articles</h1> <ul> {articles.map((article) => ( <li key={article.id}> <a href={`/articles/${article.slug}`}>{article.title}</a> </li> ))} </ul> </div> ); }; export async function getStaticProps() { const articles = await fetchAPI('/articles'); return { props: { articles }, revalidate: 1, // Revalidate at most once every second }; } export default Home;
Create a dynamic route to display individual articles. Create a file pages/articles/[slug].js
// pages/articles/[slug].js import { fetchAPI } from '../../lib/api'; const Article = ({ article }) => { return ( <div> <h1>{article.title}</h1> <div dangerouslySetInnerHTML={{ __html: article.content }} /> </div> ); }; export async function getStaticPaths() { const articles = await fetchAPI('/articles'); const paths = articles.map((article) => ({ params: { slug: article.slug }, })); return { paths, fallback: false }; } export async function getStaticProps({ params }) { const articles = await fetchAPI(`/articles?slug=${params.slug}`); return { props: { article: articles[0] }, revalidate: 1 }; } export default Article;
Step 6: Setting Environment Variables
Create a .env.local file in the root of your Next.js project:
STRAPI_URL=http://localhost:1337
Step 7: Running the Next.js Application
Start your Next.js development server:
npm run dev # or yarn dev
Navigate to http://localhost:3000 to see the list of articles and test the individual article pages.
Conclusion
In this guide, we covered how to set up a Next.js application with Strapi as the backend. We created content types in Strapi, fetched data using Axios, and displayed the data in Next.js pages. This setup allows you to build a dynamic and robust web application with a powerful CMS backend.
For more updates on programming trends and tutorials, visit blogsea.net regularly.
Building a Next.js Application with Strapi – FAQs
Strapi is an open-source headless CMS that allows you to manage content and integrate it with any frontend framework.
Use the Content-Type Builder in the Strapi Admin Panel to create a new content type.
Add fields for Title (text), Content (rich text), and Slug (UID based on Title).
A Content Type is a structured format in Strapi to define and manage different types of content, such as articles, products, or users.
Yes, install the GraphQL plugin to enable GraphQL queries and mutations in Strapi.