In this tutorial, we will learn how to build a blog using Next.js, a popular React framework for server-side rendering, and Strapi, an open-source headless CMS. By the end of this tutorial, you will have a fully functional blog with Next.js as the frontend and Strapi as the backend API.
Prerequisites
Before we begin, make sure you have the following prerequisites installed on your system:
- Node.js (v14 or higher)
- npm or yarn package manager
- Git
Setting up the Backend with Strapi
First, let’s set up the backend using Strapi. Strapi provides a simple and user-friendly way to create APIs for your projects.
Step 1: Create a new Strapi project
To create a new Strapi project, open a terminal and run the following command:
npx create-strapi-app my-blog --quickstart
This will create a new Strapi project in a directory called my-blog
using the quickstart template.
Step 2: Configure the database
By default, Strapi uses SQLite as the database for development. If you want to use a different database, you can configure it in the .env
file located in the root directory of your project.
For example, if you want to use MongoDB, open the .env
file and update the DATABASE_URL
variable:
DATABASE_URL=mongodb://localhost:27017/my-blog
Step 3: Start the Strapi server
To start the Strapi server, navigate to the project directory and run the following command:
cd my-blog
npm run develop
This will start the Strapi server on http://localhost:1337`. You can access the Strapi admin panel by visiting
http://localhost:1337/admin`.
Step 4: Create the content types
In the Strapi admin panel, go to the Content-Types Builder section and create two new content types: Article
and Category
.
For the Article
content type, add the following fields:
- Title (Text)
- Content (Rich Text)
- Category (Relation with the
Category
content type)
For the Category
content type, add a single field:
- Name (Text)
Save the changes and go back to the Plugins section. Install and enable the GraphQL plugin.
Step 5: Generate the GraphQL schema
To generate the GraphQL schema for your Strapi project, run the following command in the project directory:
npm run build
This will generate the schema at ./.tmp/graphql/schema.graphql
.
With the Strapi backend set up, we can now move on to building the frontend using Next.js.
Setting up the Frontend with Next.js
Next.js is a powerful React framework that enables server-side rendering and other advanced features to build fast and scalable applications.
Step 1: Create a new Next.js project
To create a new Next.js project, open a terminal and run the following command:
npx create-next-app my-blog
This will create a new Next.js project in a directory called my-blog
.
Step 2: Install dependencies
Navigate to the project directory and install the required dependencies:
cd my-blog
npm install axios graphql-request
We will use the axios
library to make HTTP requests to the Strapi API and the graphql-request
library to query our GraphQL API.
Step 3: Configure environment variables
Create a new .env.local
file in the root directory of your project and add the following variables:
NEXT_PUBLIC_STRAPI_API_URL=http://localhost:1337/graphql
This file will contain environment-specific variables, such as the URL to your Strapi API.
Step 4: Create API functions
In the lib
directory of your project, create a new file called api.js
and add the following code:
import { GraphQLClient } from 'graphql-request';
export async function request(query, variables = {}) {
const endpoint = process.env.NEXT_PUBLIC_STRAPI_API_URL;
const client = new GraphQLClient(endpoint);
return client.request(query, variables);
}
This code sets up a GraphQL client using the graphql-request
library and exports a function to make requests to the Strapi API.
Step 5: Fetch articles from the API
In the pages
directory of your project, create a new file called index.js
and add the following code:
import { request } from '../lib/api';
export default function Home({ articles }) {
return (
<div>
<h1>My Blog</h1>
<ul>
{articles.map((article) => (
<li key={article.id}>
<h2>{article.title}</h2>
{article.content}
</li>
))}
</ul>
</div>
);
}
export async function getStaticProps() {
const query = `
query Articles {
articles {
id
title
content
}
}
`;
const { articles } = await request(query);
return {
props: {
articles,
},
};
}
This code fetches the articles from the Strapi API using the request
function we defined earlier and displays them on the page.
Step 6: Start the Next.js development server
To start the Next.js development server, run the following command in the project directory:
npm run dev
This will start the Next.js server on `http://localhost:3000`. If you visit this URL in your browser, you should see the list of articles fetched from the Strapi API.
Adding Dynamic Routes
Next.js allows you to create dynamic routes by using square brackets []
in the filename. Let’s add dynamic routes to display individual articles.
Step 1: Create a new file for the dynamic route
In the pages
directory of your project, create a new directory called articles
. Inside the articles
directory, create a file called [slug].js
and add the following code:
import { request } from '../../lib/api';
export default function Article({ article }) {
return (
<div>
<h1>{article.title}</h1>
{article.content}
</div>
);
}
export async function getStaticPaths() {
const query = `
query Articles {
articles {
slug
}
}
`;
const { articles } = await request(query);
const paths = articles.map((article) => ({
params: { slug: article.slug },
}));
return {
paths,
fallback: false,
};
}
export async function getStaticProps({ params }) {
const query = `
query Article($slug: String!) {
article(where: { slug: $slug }) {
title
content
}
}
`;
const { article } = await request(query, { slug: params.slug });
return {
props: {
article,
},
};
}
This code fetches the individual article based on the slug
parameter from the Strapi API and displays it on the page.
Step 2: Link to the dynamic route
In the index.js
file, replace the li
element with the following code:
import Link from 'next/link';
// ...
<ul>
{articles.map((article) => (
<li key={article.id}>
<Link href={`/articles/${article.slug}`}>
<a>
<h2>{article.title}</h2>
</a>
</Link>
{article.content}
</li>
))}
</ul>
This code uses Next.js’s Link
component to create a link to the dynamic route for each article.
Restart the Next.js server and visit `http://localhost:3000` to see the updated list of articles. Clicking on an article should take you to the individual article page.
Conclusion
Congratulations! You have successfully built a blog with Next.js as the frontend and Strapi as the backend API. You have learned how to set up the backend with Strapi, create content types, and generate a GraphQL schema. You have also learned how to set up the frontend with Next.js, fetch data from the Strapi API, and create dynamic routes.
This is just the beginning of what you can accomplish with Next.js and Strapi. Feel free to explore the Next.js and Strapi documentation to discover more features and possibilities for your projects. Happy coding!