In this beginner-friendly tutorial, we will build a dynamic website using Next.js 14 and Strapi 5, a headless content management system (CMS). This blog post is based on Brad Schiff's video tutorial, which can be found here.
Don't let the simplicity fool you. In this tutorial, we will cover the following topics.
If you prefer to read instead of watch the video, I will walk you through the steps I took following the tutorial.
But I would recommend doing both. In my tutorial, I used TypesScript and took a different approach when rendering Strapi's dynamic zone.
As a bonus, we used Strapi's Block Editor, and I showed you how to render the text blocks and the image.
Let's get started!
First, choose a directory to set up your project. I will name my project directory brad
.
mkdir brad
cd brad
After changing into the directory, we will create a new Next.js app by running the following command.
npx create-next-app@latest
You can learn more about getting started with Next.js here
We will be prompted with the following options: here is what I chose.
➜ brad git:(main) ✗ npx create-next-app@latest
✔ What is your project named? … client
✔ Would you like to use TypeScript? … Yes
✔ Would you like to use ESLint? … No
✔ Would you like to use Tailwind CSS? … Yes
✔ Would you like to use `src/` directory? … Yes
✔ Would you like to use App Router? (recommended) … Yes
✔ Would you like to customize the default import alias (@/*)? … No
Creating a new Next.js app in /Users/paulbratslavsky/Desktop/work/tutorials-and-posts/brad/client.
Now that we have our project set up, we can start running the development server.
cd client
yarn dev
You can navigate to the following URL to view the app: http://localhost:3000. You should see the following screen:
Nice! We have a basic Next.js app setup and running.
In this section, we will set up our Next.js UI and Layout. Once we are done, we should have something that looks like this:
To get started, we will create a new folder in the src/app
directory and name it components.
Inside this folder, we will create a new file and name it header.tsx
. This file will contain our header component.
Inside the header.tsx
file, let's start by adding the following code:
1import Link from "next/link";
2import NavLink from "./nav-link";
3
4const links = [
5 { href: "/", label: "Home" },
6 { href: "/our-team", label: "Our Team" },
7 { href: "/about-us", label: "About Us" },
8];
9
10export default function Header() {
11 return (
12 <header className="bg-white/50">
13 <nav className="container mx-auto flex justify-between items-center py-4">
14 <Link href="/">Our Cool Project</Link>
15
16 <ul className="flex gap-4">
17 {links.map((link) => (
18 <NavLink key={link.href} href={link.href}>
19 {link.label}
20 </NavLink>
21 ))}
22 </ul>
23 </nav>
24 </header>
25 );
26}
The above code renders our Header component. It creates a header
element with a nav
element. The nav
element contains a Link
component for the logo and a ul
element with NavLink
components for the navigation links.
We are iterating over the links
array to create a NavLink
component for each link. The NavLink
component is a custom component that we will make in the next section. It is responsible for rendering an active link when the current path matches the href of the link.
NavLink
ComponentInside the components
folder, we will create a new file and name it nav-link.tsx
. This file will contain our NavLink component.
Let's start by adding the following code:
1"use client";
2
3import { usePathname } from "next/navigation";
4import Link from "next/link";
5import path from "path";
6
7function cn(...inputs: (string | undefined | null | false)[]) {
8 return inputs.filter(Boolean).join(" ");
9}
10
11interface NavLinkProps {
12 href: string;
13 children: React.ReactNode;
14}
15
16export default function NavLink({ href, children }: Readonly<NavLinkProps>) {
17 const pathname = usePathname();
18 const isActive = href === "/" ? pathname === "/" : pathname.startsWith(href);
19
20 return (
21 <li>
22 <Link
23 href={href}
24 className={cn(
25 isActive ? "opacity-100" : "opacity-50 hover:opacity-100"
26 )}
27 >
28 {children}
29 </Link>
30 </li>
31 );
32}
Nice! We have a NavLink component that renders a link active when the current path matches the link's href.
We will create a new file in the components
folder and name it footer.tsx
. This file will contain our Footer component.
Let's start by adding the following code:
1export default function Footer() {
2 return (
3 <footer className="bg-white/50">
4 <div className="container mx-auto flex justify-center items-center py-4">
5 <div>© {new Date().getFullYear()} Our Company Name</div>
6 </div>
7 </footer>
8 );
9}
Now, we have a Footer component that renders a footer with a copyright notice.
Let's update our layout.tsx
file to include our Header and Footer components. The layout.tsx
file is responsible for rendering the layout of our app. It is the root component that wraps around our entire app.
Let's start by updating the layout.tsx
file with the following code:
1import type { Metadata } from "next";
2import localFont from "next/font/local";
3import "./globals.css";
4
5import Footer from "@/app/components/footer";
6import Header from "@/app/components/header";
7
8const geistSans = localFont({
9 src: "./fonts/GeistVF.woff",
10 variable: "--font-geist-sans",
11 weight: "100 900",
12});
13const geistMono = localFont({
14 src: "./fonts/GeistMonoVF.woff",
15 variable: "--font-geist-mono",
16 weight: "100 900",
17});
18
19export const metadata: Metadata = {
20 title: "Create Next App",
21 description: "Generated by create next app",
22};
23
24export default function RootLayout({
25 children,
26}: Readonly<{
27 children: React.ReactNode;
28}>) {
29 return (
30 <html lang="en">
31 <body
32 className={`${geistSans.variable} ${geistMono.variable} antialiased`}
33 >
34 <div className="bg-gray-200 min-h-screen grid grid-rows-[auto_1fr_auto]">
35 <Header />
36 <main className="container mx-auto bg-white/50 rounded-xl py-7 px-8 m-6 overflow-hidden">
37 {children}
38 </main>
39 <Footer />
40 </div>
41 </body>
42 </html>
43 );
44}
We now have a Layout component responsible for rendering our app's layout. It includes our Header
and Footer
components.
In our project, we will have the following pages:
Let's start by creating routes for the pages above.
Create Home Page
We already have a page.tsx
file in the app
folder. This file is our Home page.
Let's update the page.tsx
file with the following code:
1export default function Home() {
2 return (
3 <div>
4 <h1>Home Page</h1>
5 </div>
6 );
7}
Nice! We have a Home page.
Create Our Team Page
Now, let's create our Our Team page. We will create a new folder in the app
folder and name it our-team
. We will create a new file and name it page.tsx
inside this folder. This file will contain the Our Team page.
Let's start by adding the following code:
1export default function OurTeam() {
2 return (
3 <div>
4 <h1>Our Team</h1>
5 </div>
6 );
7}
Create About Us Page
Finally, let's create our About Us page. We will create a new folder in the app
folder and name it about-us
. We will create a new file and name it page.tsx
inside this folder. This file will contain our About Us
page.
Let's start by adding the following code:
1export default function AboutUs() {
2 return (
3 <div>
4 <h1>About Us</h1>
5 </div>
6 );
7}
Nice, now we have all of our basic pages set up.
In the next section, we will start to set up our Strapi backend.
Strapi is an open-source headless content management system (CMS) that allows you to create, manage, and serve content through a flexible API.
We are going to use Strapi to power the backend of our application, enabling non-developers or non-programmers to easily contribute and manage website content, such as team member profiles.
By integrating Strapi with Next.js, we can dynamically fetch and display this content on the frontend, allowing for a seamless and interactive user experience. Strapi simplifies data handling and offers a user-friendly admin interface for content management.
We can get started by running the following command at the root of our project:
npx create-strapi-app@latest server
We will be prompted with the following options: here is what I chose.
Strapi v5.0.2 🚀 Let's create your new project
We can't find any auth credentials in your Strapi config.
Create a free account on Strapi Cloud and benefit from:
- ✦ Blazing-fast ✦ deployment for your projects
- ✦ Exclusive ✦ access to resources to make your project successful
- An ✦ Awesome ✦ community and full enjoyment of Strapi's ecosystem
Start your 14-day free trial now!
? Please log in or sign up.
Login/Sign up
❯ Skip
For this tutorial, we will choose to skip the login step.
After we hit enter, we will see the following options: here is what I chose.
? Please log in or sign up. Skip
? Do you want to use the default database (sqlite) ? Yes
? Start with an example structure & data? No
? Start with Typescript? Yes
? Install dependencies with npm? Yes
? Initialize a git repository? Yes
Strapi Creating a new application at /Users/paulbratslavsky/Desktop/work/tutorials-and-posts/brad/server
Once everything is set up, we can start the Strapi server by running the following command:
cd server
yarn develop
We should be greeted with the following screen: create your first Strapi Admin User.
After successfully creating the user, you should be redirected to the Strapi Welcome screen.
In this tutorial, we are primarily focusing on collection types, which are essential for structuring our data in a way that is easily accessible and manageable.
Collection types in Strapi define a group of similar data entries. For instance, in our case, we will create a collection type called Team Members. This collection will allow us to manage individual profiles for each team member, including fields such as their name, description, photograph, and URL-friendly slug.
The use of collection types is beneficial because it provides a structured format for data, making it straightforward to add, edit, or remove entries as needed. Each team member's data can be easily retrieved via API endpoints, enabling our frontend to dynamically display the information without hardcoding it.
We will create a new collection type called Team Member.
Once you click on "Continue," you will be redirected to the following screen:
Now, let's start by adding the following fields to our collection type:
Field Name | Field Type | Additional Info |
---|---|---|
name | Text | Short text input |
description | Text | Long text input |
photo | Media | Single media |
slug | UID | Reference name |
Once you have added all the fields, click "Save" to save the collection type.
Now that we have our collection type, we can start adding data. Go ahead and add your first team member.
Nice! We have added our first team member.
Now that we have our team member data in place let's see how we can access it via the Strapi API.
But first, let's give our API appropriate permission to access our team member data.
We can do this in the Settings section of Strapi.
We will navigate to the Users & Permissions plugin. Once in the Users & Permissions plugin, we will navigate to the Roles section, select the Public role, and click on the Team Members permission.
We will check find
and findOne
. This will give our API the necessary permissions to fetch and display our team member data.
We should be able to request the following URL to fetch our team member data:
http://localhost:1337/api/team-members
See the following response:
1{
2 "data": [
3 {
4 "id": 2,
5 "documentId": "ybk38754pitymo4wxcn3mjct",
6 "name": "Sarah",
7 "description": "Hello I am Sarah.",
8 "slug": "sarah",
9 "createdAt": "2024-10-03T17:50:37.403Z",
10 "updatedAt": "2024-10-03T17:50:37.403Z",
11 "publishedAt": "2024-10-03T17:50:37.411Z",
12 "locale": null
13 }
14 ],
15 "meta": {
16 "pagination": {
17 "page": 1,
18 "pageSize": 25,
19 "pageCount": 1,
20 "total": 1
21 }
22 }
23}
You will notice that we are not yet seeing the photo
data in the response. This is because we need to tell Strapi to include the photo
field in the response using our populate
and filtering
flags.
This is something we will do as we start to build our frontend.
Now that we have our Strapi backend, let's start building our frontend. In this section, we will fetch our team member data in Next.js.
With Next.js Server Components, we can fetch data directly from our components.
Let's see how we can accomplish this within our Our Team
page.
Let's start by updating our our-team/page.tsx
file with the following code:
1async function getTeamMembers() {
2 const baseUrl = process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:1337";
3 const path = "/api/team-members";
4
5 const url = new URL(path, baseUrl);
6
7 const res = await fetch(url);
8
9 if (!res.ok) throw new Error("Failed to fetch team members");
10
11 const data = await res.json();
12 console.log(data);
13
14 return data;
15}
16
17export default async function OurTeam() {
18 const teamMembers = await getTeamMembers();
19 console.log(teamMembers);
20
21 return (
22 <div>
23 <h1>Our Team</h1>
24 <pre>{JSON.stringify(teamMembers, null, 2)} </pre>
25 </div>
26 );
27}
This will fetch our team member data from our Strapi backend and display it in the browser.
photo
FieldNow, let's update this to populate our photo
field.
You can learn more about Strapi's Populate and Filtering here, but I will walk you through the steps here.
We will start by constructing the query
object using Strapi's Query Builder that you can find here.
Here is the basic our query will look like:
Go ahead and copy the Query String URL and make a request to the following URL in your browser:
You should see the following response:
1{
2 "data": [
3 {
4 "id": 2,
5 "documentId": "ybk38754pitymo4wxcn3mjct",
6 "name": "Sarah",
7 "description": "Hello I am Sarah.",
8 "slug": "sarah",
9 "createdAt": "2024-10-03T17:50:37.403Z",
10 "updatedAt": "2024-10-03T17:50:37.403Z",
11 "publishedAt": "2024-10-03T17:50:37.411Z",
12 "locale": null,
13 "photo": {
14 "id": 1,
15 "documentId": "e2zyo9559mmgj3tu3f4olngz",
16 "alternativeText": null,
17 "name": "computer-working.jpg",
18 "url": "/uploads/computer_working_3ec59d6554.jpg"
19 }
20 }
21 ],
22 "meta": {
23 "pagination": {
24 "page": 1,
25 "pageSize": 25,
26 "pageCount": 1,
27 "total": 1
28 }
29 }
30}
Notice how we now see the photo
data in the response.
To recap, in our collection type, we added the following fields:
name
description
slug
photo
The fields name
, description
, and slug
are all that I would call top-level fields. That is because they do not have any relationships with other entities.
Since photo
relates to another entity or image, we must populate it.
As we did above, use Strapi's Query Builder. Where we passed the following to the query:
1{
2 populate: {
3 photo: {
4 fields: ['alternativeText', 'name', 'url']
5 }
6 },
7}
Now, let's update our Our Team page.tsx
file to display and utilize the populate logic that we learned about above.
To accomplish this, we will install a new package called qs, which will help us construct our query string.
You can install the package by running the following command:
yarn add qs
yarn add @types/qs
You can learn more about the qs
package here.
Let's start by updating our getTeamMembers
function to utilize the qs
package.
First, we will import the qs
package at the top of the file.
1import qs from "qs";
Then, we will update our getTeamMembers
function to utilize the qs
package.
1async function getTeamMembers() {
2 const baseUrl = process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:1337";
3 const path = "/api/team-members";
4
5 const url = new URL(path, baseUrl);
6
7 url.search = qs.stringify({
8 populate: {
9 photo: {
10 fields: ["alternativeText", "name", "url"],
11 },
12 },
13 });
14
15 const res = await fetch(url);
16
17 if (!res.ok) throw new Error("Failed to fetch team members");
18
19 const data = await res.json();
20 console.log(data);
21
22 return data;
23}
The complete code for our Our Team page should now look like this:
1import qs from "qs";
2
3async function getTeamMembers() {
4 const baseUrl = process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:1337";
5 const path = "/api/team-members";
6
7 const url = new URL(path, baseUrl);
8
9 url.search = qs.stringify({
10 populate: {
11 photo: {
12 fields: ["alternativeText", "name", "url"],
13 },
14 },
15 });
16
17 const res = await fetch(url);
18
19 if (!res.ok) throw new Error("Failed to fetch team members");
20
21 const data = await res.json();
22 console.log(data);
23
24 return data;
25}
26
27export default async function OurTeam() {
28 const teamMembers = await getTeamMembers();
29 console.log(teamMembers);
30
31 return (
32 <div>
33 <h1>Our Team</h1>
34 <pre>{JSON.stringify(teamMembers, null, 2)} </pre>
35 </div>
36 );
37}
In the next section, we will build our frontend to display our team members.
In this section, we will start building the Team Member Card component, which will display a single team member's profile.
Inside our Our Team page.tsx
file, we will create a new component named TeamMemberCard. This component will display a single team member profile.
Let's start by adding the following code:
1interface TeamMemberProps {
2 id: number;
3 documentId: string;
4 name: string;
5 description: string;
6 slug: string;
7 createdAt: string;
8 updatedAt: string;
9 publishedAt: string;
10 locale: string;
11 photo: {
12 id: number;
13 documentId: string;
14 alternativeText: string;
15 name: string;
16 url: string;
17 };
18}
19
20function TeamMemberCard({
21 name,
22 description,
23 photo,
24 slug,
25}: Readonly<TeamMemberProps>) {
26 const imageUrl = `${
27 process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:1337"
28 }${photo.url}`;
29 return (
30 <Link
31 href={`/our-team/${slug}`}
32 className="bg-white rounded-lg shadow-md overflow-hidden"
33 >
34 <Image
35 src={imageUrl}
36 alt={photo.alternativeText || name}
37 width={500}
38 height={500}
39 />
40 <div className="p-6">
41 <h3 className="text-xl font-semibold mb-2">{name}</h3>
42 <p className="text-gray-600">{description}</p>
43 </div>
44 </Link>
45 );
46}
This component will be responsible for displaying a single team member profile.
And update our Our Team component to utilize our TeamMemberCard component.
1export default async function OurTeam() {
2 const teamMembers = await getTeamMembers();
3
4 return (
5 <div>
6 <h1 className="text-3xl font-bold mb-8">Our Team</h1>
7 <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
8 {teamMembers.data.map((member: TeamMemberProps) => (
9 <TeamMemberCard key={member.documentId} {...member} />
10 ))}
11 </div>
12 </div>
13 );
14}
The complete code for our Our Team page should now look like this:
1import qs from "qs";
2import Image from "next/image";
3
4async function getTeamMembers() {
5 const baseUrl = process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:1337";
6 const path = "/api/team-members";
7
8 const url = new URL(path, baseUrl);
9
10 url.search = qs.stringify({
11 populate: {
12 photo: {
13 fields: ["alternativeText", "name", "url"],
14 },
15 },
16 });
17
18 const res = await fetch(url);
19
20 if (!res.ok) throw new Error("Failed to fetch team members");
21
22 const data = await res.json();
23 console.log(data);
24
25 return data;
26}
27
28interface TeamMemberProps {
29 id: number;
30 documentId: string;
31 name: string;
32 description: string;
33 slug: string;
34 createdAt: string;
35 updatedAt: string;
36 publishedAt: string;
37 locale: string;
38 photo: {
39 id: number;
40 documentId: string;
41 alternativeText: string;
42 name: string;
43 url: string;
44 };
45}
46
47function TeamMemberCard({
48 name,
49 description,
50 photo,
51 slug,
52}: Readonly<TeamMemberProps>) {
53 const imageUrl = `${
54 process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:1337"
55 }${photo.url}`;
56 return (
57 <Link
58 href={`/our-team/${slug}`}
59 className="bg-white rounded-lg shadow-md overflow-hidden"
60 >
61 <Image
62 src={imageUrl}
63 alt={photo.alternativeText || name}
64 width={500}
65 height={500}
66 />
67 <div className="p-6">
68 <h3 className="text-xl font-semibold mb-2">{name}</h3>
69 <p className="text-gray-600">{description}</p>
70 </div>
71 </Link>
72 );
73}
74
75export default async function OurTeam() {
76 const teamMembers = await getTeamMembers();
77
78 return (
79 <div>
80 <h1 className="text-3xl font-bold mb-8">Our Team</h1>
81 <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
82 {teamMembers.data.map((member: TeamMemberProps) => (
83 <TeamMemberCard key={member.documentId} {...member} />
84 ))}
85 </div>
86 </div>
87 );
88}
If we navigate to our Our Team page, we will see the following error:
To fix this error, we need to update our next.config. JMS
file to include our Strapi server as a remote pattern.
1/** @type {import('next').NextConfig} */
2
3const nextConfig = {
4 images: {
5 remotePatterns: [
6 {
7 protocol: "http",
8 hostname: "localhost",
9 port: "1337",
10 pathname: "/uploads/**/*",
11 },
12 ],
13 },
14};
15
16export default nextConfig;
Now restart your development server and navigate to our Our Team page, and we should see the following:
Nice. Now that we can display our team members, let's build our Team Member Detail page. But before that, let's learn about Strapi's Components and Dynamic Zones.
This section will start by learning about Strapi's Components and Dynamic Zones.
Components are reusable building blocks that can be used to build pages, and dynamic zones are special components that can be used to build pages.
We will start by creating a new Testimonial component.
I will name it testimonial
and create a blocks
category.
Now, click the "Continue" button and add our first fields.
I am going to add the following fields:
Field Name | Field Type | Additional Info |
---|---|---|
authorName | Text | Short text input |
quote | Text | Long text input |
photo | Media | Single media |
Here is what the final fields should look like:
Now let's create another component; we will name it spoiler
.
I am going to add the following fields:
Field Name | Field Type | Additional Info |
---|---|---|
title | Text | Short text input |
content | Text | Long text input |
Here is what the final fields should look like:
And finally, let's create one more component; we will name it richText
.
I am going to add the following field:
Field Name | Field Type | Additional Info |
---|---|---|
content | Rich Text | Rich text input |
Here is what the final fields should look like:
Nice! Now that our components are created let's start building our dynamic zones.
Let's navigate to our Team Member collection type and click "Add another field to this type".
We will scroll down and find Dynamic Zone and add it to our collection type.
Let's name it blocks
and click on Add the component to the zone.
I will add our Testimonial, Spoiler, and Rich Text components that we created earlier and click on Finish. You should see the following screen:
Don't forget to click on Save to save the dynamic zone.
Now, let's go ahead and add some data to our Team Member collection type.
Excellent; let's see how we can fetch this data in our Next.js application.
But first, let's revisit our populate
logic. We already did some of this when we built our Our Team page.
However, now that we use dynamic zones, we need to update our populate logic to include our blocks
field. For this, we will use the on
flag.
You can learn more about Strapi's on
flag here.
Here is the example query we would use to populate the above dynamic zone example:
1{
2 populate: {
3 blocks: { // asking to populate the blocks dynamic zone
4 on: { // using a detailed population strategy to explicitly define what you want
5 'blocks.related-articles': {
6 populate: {
7 'articles': {
8 populate: ['image']
9 }
10 }
11 },
12 'blocks.cta-command-line': {
13 populate: '*'
14 }
15 },
16 },
17 },
18}
We will use similar populate logic as the example above to populate our blocks
dynamic zone.
Populating Our Dynamic Zone
Looking at our Team Member collection, we see that we have our blocks
dynamic zone field.
Using the on
flag, we can target the blocks
field. We can also see that our Testimonial component has a photo
field related to our Media content type. So, we will populate the fields we need using the fields
flag.
Here is what the populate logic will look like:
1{
2 populate: {
3 photo: {
4 fields: ['alternativeText', 'name', 'url']
5 },
6 blocks: {
7 on: {
8 'blocks.testimonial': {
9 populate: {
10 photo: {
11 fields: ['alternativeText', 'name', 'url']
12 }
13 }
14 }
15 }
16 }
17 },
18}
We can request the following URL with the above populate logic included in the query string, and we should see the following response:
1{
2 "data": [
3 {
4 "id": 4,
5 "documentId": "ybk38754pitymo4wxcn3mjct",
6 "name": "Sarah",
7 "description": "Hello I am Sarah.",
8 "slug": "sarah",
9 "createdAt": "2024-10-03T17:50:37.403Z",
10 "updatedAt": "2024-10-03T21:17:22.740Z",
11 "publishedAt": "2024-10-03T21:17:22.751Z",
12 "locale": null,
13 "photo": {
14 "id": 1,
15 "documentId": "e2zyo9559mmgj3tu3f4olngz",
16 "alternativeText": null,
17 "name": "computer-working.jpg",
18 "url": "/uploads/computer_working_3ec59d6554.jpg"
19 },
20 "blocks": [
21 {
22 "__component": "blocks.testimonial",
23 "id": 3,
24 "authorName": "Sarah",
25 "quote": "Strapi 5 is awesome.",
26 "photo": {
27 "id": 1,
28 "documentId": "e2zyo9559mmgj3tu3f4olngz",
29 "alternativeText": null,
30 "name": "computer-working.jpg",
31 "url": "/uploads/computer_working_3ec59d6554.jpg"
32 }
33 }
34 ]
35 }
36 ],
37 "meta": {
38 "pagination": {
39 "page": 1,
40 "pageSize": 25,
41 "pageCount": 1,
42 "total": 1
43 }
44 }
45}
Nice! Notice we can see our Testimonial component data in the response.
The last item we need to solve before implementing our Team Member Detail page is to ensure we know how to fetch a single team member via the slug
field.
Let's update our query
from above to include the filters
flag. Here is what the updated query should look like:
1{
2 populate: {
3 photo: {
4 fields: ['alternativeText', 'name', 'url']
5 },
6 blocks: {
7 on: {
8 'blocks.testimonial': {
9 populate: {
10 photo: {
11 fields: ['alternativeText', 'name', 'url']
12 }
13 }
14 },
15 }
16 }
17 },
18 filters: {
19 slug: {
20 $eq: "sarah" // This is the slug for our team member
21 }
22 }
23}
This will allow us to fetch the data for the team member we want.
And finally, let's update our query to populate the rest of our blocks
in our dynamic zone.
Here is the final query we will use:
1{
2 populate: {
3 photo: {
4 fields: ['alternativeText', 'name', 'url']
5 },
6 blocks: {
7 on: {
8 'blocks.testimonial': {
9 populate: {
10 photo: {
11 fields: ['alternativeText', 'name', 'url']
12 }
13 }
14 },
15 'blocks.spoiler': {
16 populate: true
17 },
18 'blocks.rich-text': {
19 populate: true
20 }
21 }
22 }
23 },
24 filters: {
25 slug: {
26 $eq: "sarah" // This is the slug for our team member
27 }
28 }
29}
And here is the response we should see:
Notice how we now see our testimonial,
spoiler
, and rich-text
components in the response.
Finally, let's start working out the Team Member Detail
page.
In our Next.js project, we will start by creating a new file in our app/team-member
folder and naming it [slug].
Inside, let's add page.tsx
.
By naming our folder [slug]
it will turn our normal route into a dynamic route; you can learn more about dynamic routes here.
Let's add the following code to our [slug]/page.tsx
file:
1export default function TeamMemberDetail() {
2 return (
3 <div>
4 <h1>Team Member Detail</h1>
5 </div>
6 );
7}
Now, when we click on any of the team members in our Our Team
page, we should see our Team Member Detail
page.
Now, let's look at how we can access our parameters to get our slug,
which we can use to fetch our team member data.
In our [slug]/page.tsx
component, we can access our slug
by accessing the params
object.
We will start by adding the following code to our component:
1export default function TeamMemberDetail({
2 params,
3}: {
4 params: { slug: string };
5}) {
6 const { slug } = params;
7
8 if (!slug) <p>No member found</p>;
9
10 return (
11 <div>
12 <h1>Team Member Detail</h1>
13 <p>{slug}</p>
14 </div>
15 );
16}
When we navigate to our Team Member Detail page, we should see our team member's name.
Before styling our page, let's start by fetching data from our team members.
Let's create a new function to fetch our team member data. We will name it getTeamMember
and add it to our [slug]/page.tsx
file.
Here is what the code should look like:
1import qs from "qs";
2
3async function getTeamMember(slug: string) {
4 const baseUrl = process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:1337";
5 const path = "/api/team-members";
6
7 const url = new URL(path, baseUrl);
8
9 url.search = qs.stringify({
10 populate: {
11 photo: {
12 fields: ["alternativeText", "name", "url"],
13 },
14 blocks: {
15 on: {
16 "blocks.testimonial": {
17 populate: {
18 photo: {
19 fields: ["alternativeText", "name", "url"],
20 },
21 },
22 },
23 "blocks.spoiler": {
24 populate: true,
25 },
26 "blocks.rich-text": {
27 populate: true,
28 },
29 },
30 },
31 },
32 filters: {
33 slug: {
34 $eq: slug, // This is the slug for our team member
35 },
36 },
37 });
38
39 const res = await fetch(url);
40
41 if (!res.ok) throw new Error("Failed to fetch team members");
42
43 const data = await res.json();
44 const teamMember = data?.data[0];
45 console.dir(teamMember, { depth: null });
46 return teamMember;
47}
48
49export default async function TeamMemberDetail({
50 params,
51}: {
52 params: { slug: string };
53}) {
54 const { slug } = params;
55
56 if (!slug) <p>No member found</p>;
57
58 const teamMember = await getTeamMember(slug);
59
60 return (
61 <div>
62 <h1>Team Member Detail</h1>
63 <p>{slug}</p>
64 <pre>{JSON.stringify(teamMember, null, 2)}</pre>
65 </div>
66 );
67}
In the code above, we use the getTeamMember
function to fetch data for our team members. We pass in our slug
as an argument to the function, and then return the team member data to our component.
Notice how we pass our search query to url.search
based on the populate logic we created earlier.
We also use the pre
tag to display our team member data in a readable format.
Let's add basic styling to our Team Member Detail
page.
We will add the following code to our [slug]/page.tsx
file:
1import qs from "qs";
2
3import { BlockRenderer, TeamPageBlock } from "@/app/components/blocks";
4
5async function getTeamMember(slug: string) {
6 const baseUrl = process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:1337";
7 const path = "/api/team-members";
8
9 const url = new URL(path, baseUrl);
10
11 url.search = qs.stringify({
12 populate: {
13 photo: {
14 fields: ["alternativeText", "name", "url"],
15 },
16 blocks: {
17 on: {
18 "blocks.testimonial": {
19 populate: {
20 photo: {
21 fields: ["alternativeText", "name", "url"],
22 },
23 },
24 },
25 "blocks.spoiler": {
26 populate: true,
27 },
28 "blocks.rich-text": {
29 populate: true,
30 },
31 },
32 },
33 },
34 filters: {
35 slug: {
36 $eq: slug, // This is the slug for our team member
37 },
38 },
39 });
40
41 const res = await fetch(url);
42
43 if (!res.ok) throw new Error("Failed to fetch team members");
44
45 const data = await res.json();
46 const teamMember = data?.data[0];
47 console.dir(teamMember, { depth: null });
48 return teamMember;
49}
50
51interface UserProfile {
52 id: number;
53 documentId: string;
54 name: string;
55 description: string;
56 slug: string;
57 createdAt: string;
58 updatedAt: string;
59 publishedAt: string;
60 locale: string | null;
61 photo: {
62 id: number;
63 alternativeText: string;
64 name: string;
65 url: string;
66 };
67 blocks: TeamPageBlock[];
68}
69
70export default async function TeamMemberDetail({
71 params,
72}: {
73 params: { slug: string };
74}) {
75 const { slug } = params;
76
77 if (!slug) return <p>No member found</p>;
78
79 const teamMember = (await getTeamMember(slug)) as UserProfile;
80
81 return (
82 <div>
83 {teamMember.blocks.map((block: TeamPageBlock) => (
84 <BlockRenderer key={block.id} block={block} />
85 ))}
86 </div>
87 );
88}
For the above code to work, we must create our new BlockRenderer component and all the other components we use on our Team Member Detail page.
Let's do that now.
Let's create a new folder in our app/components
folder and name it blocks
; let's create a new file and name it index.tsx
.
Now, let's create the following components in our blocks
folder:
spoiler-block.tsx
testimonial-block.tsx
rich-text-block.tsx
Here is what the spoiler-block.tsx
file should look like:
1"use client";
2
3import { useState } from "react";
4
5export interface SpoilerBlock {
6 __component: "blocks.spoiler";
7 id: number;
8 title: string;
9 content: string;
10}
11
12export function SpoilerBlock({ block }: { block: SpoilerBlock }) {
13 const [isExpanded, setIsExpanded] = useState(false);
14
15 return (
16 <div className="w-full mb-4 rounded-lg overflow-hidden shadow-md transition-all duration-300 ease-in-out">
17 <button
18 className={`w-full flex justify-between items-center p-4 bg-gray-100 hover:bg-gray-200 transition-colors duration-300 ease-in-out ${
19 isExpanded ? "bg-gray-200" : ""
20 }`}
21 onClick={() => setIsExpanded(!isExpanded)}
22 aria-expanded={isExpanded}
23 >
24 <span className="text-lg font-semibold text-gray-800">
25 {block.title}
26 </span>
27 <span
28 className={`text-2xl text-gray-600 transition-transform duration-300 ease-in-out ${
29 isExpanded ? "transform rotate-180" : ""
30 }`}
31 >
32 {isExpanded ? "−" : "+"}
33 </span>
34 </button>
35 <div
36 className={`overflow-hidden transition-all duration-300 ease-in-out ${
37 isExpanded ? "max-h-[1000px]" : "max-h-0"
38 }`}
39 aria-hidden={!isExpanded}
40 >
41 <div className="p-4 bg-white text-gray-700 leading-relaxed">
42 {block.content}
43 </div>
44 </div>
45 </div>
46 );
47}
Here is what the testimonial-block.tsx
file should look like:
1import Image from "next/image";
2
3export interface TestimonialBlock {
4 __component: "blocks.testimonial";
5 id: number;
6 authorName: string;
7 quote: string;
8 photo: {
9 id: number;
10 documentId: string;
11 alternativeText: string | null;
12 name: string;
13 url: string;
14 };
15}
16
17export function TestimonialBlock({ block }: { block: TestimonialBlock }) {
18 const imageUrl = `${
19 process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:1337"
20 }${block?.photo?.url}`;
21
22 return (
23 <figure className="relative bg-gray-100 rounded-lg border border-gray-200 overflow-hidden my-6">
24 <div className="grid grid-cols-1 md:grid-cols-3">
25 <div className="relative h-64 md:h-full col-span-1">
26 <Image
27 src={imageUrl}
28 alt={block.photo.alternativeText || block.authorName}
29 layout="fill"
30 objectFit="cover"
31 className="w-full h-full object-center"
32 />
33 </div>
34 <div className="p-8 col-span-2 flex flex-col justify-center">
35 <blockquote className="relative">
36 <svg
37 className="absolute top-0 left-0 transform -translate-x-6 -translate-y-8 h-16 w-16 text-gray-300 opacity-50"
38 fill="currentColor"
39 viewBox="0 0 32 32"
40 aria-hidden="true"
41 >
42 <path d="M9.352 4C4.456 7.456 1 13.12 1 19.36c0 5.088 3.072 8.064 6.624 8.064 3.36 0 5.856-2.688 5.856-5.856 0-3.168-2.208-5.472-5.088-5.472-.576 0-1.344.096-1.536.192.48-3.264 3.552-7.104 6.624-9.024L9.352 4zm16.512 0c-4.8 3.456-8.256 9.12-8.256 15.36 0 5.088 3.072 8.064 6.624 8.064 3.264 0 5.856-2.688 5.856-5.856 0-3.168-2.304-5.472-5.184-5.472-.576 0-1.248.096-1.44.192.48-3.264 3.456-7.104 6.528-9.024L25.864 4z" />
43 </svg>
44 <p className="relative text-xl font-medium text-gray-900 mb-4">
45 {block.quote}
46 </p>
47 </blockquote>
48 <figcaption className="font-semibold text-indigo-600 mt-2">
49 {block.authorName}
50 </figcaption>
51 </div>
52 </div>
53 </figure>
54 );
55}
Here is what the rich-text-block.tsx
file should look like:
1"use client";
2import {
3 BlocksRenderer,
4 type BlocksContent,
5} from "@strapi/blocks-react-renderer";
6import Image from "next/image";
7
8export interface RichTextBlock {
9 __component: "blocks.rich-text";
10 id: number;
11 content: BlocksContent;
12}
13
14// This renderer is using Strapi's Rich Text renderer.
15// https://github.com/strapi/blocks-react-renderer
16
17export function RichTextBlock({ block }: { block: RichTextBlock }) {
18 return (
19 <div className="richtext">
20 <BlocksRenderer
21 content={block.content}
22 blocks={{
23 image: ({ image }) => {
24 console.log("image", image);
25 if (!image) return null;
26 return (
27 <div className="my-4 flex justify-center">
28 <Image
29 src={image.url}
30 width={image.width || 800}
31 height={image.height || 600}
32 alt={image.alternativeText || ""}
33 className="rounded-lg shadow-md h-[300px] w-full object-cover"
34 />
35 </div>
36 );
37 },
38 }}
39 />
40 </div>
41 );
42}
This component is using Strapi's Rich Text renderer. You can learn more about it here;
To style our Rich Text component, we use Tailwind CSS. Here is what I added in the global.css
file:
1/* Rich Text Block Start */
2
3.richtext h1,
4.richtext h2,
5.richtext h3,
6.richtext h4,
7.richtext h5,
8.richtext h6 {
9 @apply font-bold leading-tight;
10}
11
12.richtext h1 {
13 @apply text-4xl mb-6 text-gray-900 dark:text-gray-100;
14}
15
16.richtext h2 {
17 @apply text-3xl mb-4 text-gray-800 dark:text-gray-200;
18}
19
20.richtext h3 {
21 @apply text-2xl mb-3 text-gray-700 dark:text-gray-300;
22}
23
24.richtext h4 {
25 @apply text-xl mb-2 text-gray-600 dark:text-gray-400;
26}
27
28.richtext h5 {
29 @apply text-lg mb-2 text-gray-600 dark:text-gray-400;
30}
31
32.richtext h6 {
33 @apply text-base mb-2 text-gray-600 dark:text-gray-400;
34}
35
36.richtext p {
37 @apply mb-4 text-gray-700 dark:text-gray-300 leading-relaxed;
38}
39
40.richtext blockquote {
41 @apply border-l-4 border-blue-500 bg-blue-50 dark:bg-blue-900 dark:bg-opacity-20 italic my-8 p-4 rounded-r-lg;
42}
43
44.richtext a {
45 @apply text-blue-600 dark:text-blue-400 hover:underline;
46}
47
48.richtext ul,
49.richtext ol {
50 @apply mb-4 pl-8;
51}
52
53.richtext ul {
54 @apply list-disc;
55}
56
57.richtext ol {
58 @apply list-decimal;
59}
60
61/* Rich Text Block End */
Nice, now that we have all of our components, let's add the following code in our components/blocks/index.tsx
file:
1import { RichTextBlock } from "./rich-text-block";
2import { TestimonialBlock } from "./testimonial-block";
3import { SpoilerBlock } from "./spoiler-block";
4
5type TeamPageBlock = SpoilerBlock | TestimonialBlock | RichTextBlock;
6
7const blocks: Record<
8 TeamPageBlock["__component"],
9 React.ComponentType<{ block: TeamPageBlock }>
10> = {
11 "blocks.spoiler": ({ block }: { block: TeamPageBlock }) => (
12 <SpoilerBlock block={block as SpoilerBlock} />
13 ),
14 "blocks.testimonial": ({ block }: { block: TeamPageBlock }) => (
15 <TestimonialBlock block={block as TestimonialBlock} />
16 ),
17 "blocks.rich-text": ({ block }: { block: TeamPageBlock }) => (
18 <RichTextBlock block={block as RichTextBlock} />
19 ),
20};
21
22function BlockRenderer({ block }: { block: TeamPageBlock }) {
23 const BlockComponent = blocks[block.__component];
24 return BlockComponent ? <BlockComponent block={block} /> : null;
25}
26
27export { BlockRenderer };
28export type { TeamPageBlock };
The TeamPageBlock
type is a union of three block types: SpoilerBlock
, TestimonialBlock
, and RichTextBlock
. Each block represents a distinct type of content that can be displayed.
Each block component is imported and can be rendered based on the block data type.
The blocks object maps a block's __component
field (which is a string identifier like blocks.spoiler
, blocks.testimonial
, or blocks.rich-text
) to the corresponding React component that should handle that block type.
For example:
When the block's __component
is blocks.spoiler
, it renders the SpoilerBlock
component.
Each block type is cast to the correct type using TypeScript's as
keyword (block as SpoilerBlock
) to ensure the correct component is used with the correct block data.
The BlockRenderer component takes a TeamPageBlock
object as a prop and renders the appropriate component based on the block's __component
field.
Inside this function, blocks[block.__component]
retrieves the correct component for the given block. If a matching component is found, it is rendered; otherwise, null is returned (indicating no content is rendered for unrecognized block types).
How the BlockRenderer Works
When BlockRenderer is called with a block, it looks up the block.__component
in the blocks object to find the corresponding React component.
It then renders the component, passing the block data to it.
The specific component (e.g., SpoilerBlock, TestimonialBlock, or RichTextBlock) knows how to handle and render that particular block's data.
Example Flow:
A TeamPageBlock
(e.g., a TestimonialBlock) is passed to BlockRenderer.
BlockRenderer checks the block's __component
field (e.g., blocks.testimonial
).
It finds the corresponding component (TestimonialBlock) in the blocks object.
It renders the TestimonialBlock
component, passing the block as a prop and displaying the block content.
This pattern is useful for rendering dynamic content in which blocks are of different types and each type has its own specific rendering logic.
Nice. Now that we have all our components, let's add some data for our team members in Strapi's admin panel. Then, check out our locally running Next.js app to see our new team member page.
This tutorial covered building a dynamic website using Next.js 14 and Strapi 5, and we explored the frontend and backend aspects, making it accessible for beginners.
Topics included:
Key concepts covered were:
I hope you enjoyed this tutorial. A huge thank you to Brad from LearnWebCode for creating the video tutorial I used to write this blog post. Make sure to check out his video.
You can find the code for this tutorial here.
If you have any questions or feedback, please leave a comment below. Or join us on Strapi's Discord here for our "Strapi Open Office Hours" Monday - Friday.
Morning Session: 4 AM CST (9:00 AM GMT)
Afternoon Session: 12:30 PM CST (6:30 PM GMT)