This post is part 2 of many in our Epic Next.js Series. You can find the outline for upcoming posts here.
In this post, we will start by building our home page. We will focus on the Hero Component and Features Component and use Dynamic Zone to allow our Strapi admins to choose which component they want to use.
If you missed the first part of this series, you can check it out here.
Once our data is returned by our Strapi API, we will build out those same components within our Next JS app.
Our goal is to display our Hero Section and Features Sections on our Next application. So let's get started.
In Strapi, there are many ways of structuring your data; you can create single types,
collection types,
and components
that allow you to create reusable content types that you can use in multiple places.
We will build our Hero Section and Features Section as components.
Let's start by building out our Hero Section Component.
Looking at our Hero Section UI, we can break it down into the following parts.
We have the following items:
So, let's jump into our Strapi Admin and create our Hero Component.
Let's start by navigating to Content-Type Builder
under COMPONENTS
and clicking on Create new component.
We will create the following fields.
Media -> Single Media - image Text -> Short Text - heading Text -> Long Text - subHeading
Note: Change it to only allow images for media in advanced settings.
For our link, we will create a component that we can reuse.
Go ahead and create a new component called Link and save it under components.
Our Link component will have the following fields. Text -> Short Text -> url Text -> Short Text -> text Boolean -> isExternal
Note: for isExternal in the advanced setting, change the default value to be set to false.
Let's go ahead and add them now.
Finally, please return to our Hero Section component and add our newly created Link component.
The completed fields in our Hero Section component should look like the following:
Finally, let's add our newly created component to our Home Page via dynamic zones.
We can accomplish this by going to Content-Type Builder,
selecting the Home Page under SINGLE TYPES
and clicking on Add another field to this single type.
Select the Dynamic Zone
field, give it a name called blocks,
and click Add components to the zone.
Finally, select Use an existing component
and choose our Hero Section component.
Great, we now have our first component that has been added to our Home Page
Before creating our Features Section component, let's see if we can get our current component from our API.
First, let's add some data.
Now make sure that we have proper permission in the Settings
Now, let's test our API call in Postman. But before we do, we need to specify in Strapi all the items we would like to populate.
Looking at our content, we need to populate the following items: blocks,
image,
and link.
Before we construct our query, quick note, as of Strapi 5, we need to use the on
flag to populate our dynamic zones data.
You can learn more about it in the Strapi docs.
Remember, we can construct our query using the Strapi Query Builder.
We can populate our data with the following query.
1{
2 populate: {
3 blocks: {
4 on: {
5 "layout.hero-section": {
6 populate: {
7 image: {
8 fields: ["url", "alternativeText"]
9 },
10 link: {
11 populate: true
12 }
13 }
14 }
15 }
16 }
17 },
18}
Using the query builder, the following LHS syntax query will be generated.
http://localhost:1337/api/home-page?populate[blocks][on][layout.hero-section][populate][image][fields][0]=url&populate[blocks][on][layout.hero-section][populate][image][fields][1]=alternativeText&populate[blocks][on][layout.hero-section][populate][link][populate]=true
Here is the complete URL
We will get the following data after making a GET
request in Postman.
1{
2 "data": {
3 "id": 3,
4 "documentId": "fcnlk9xwoqmogfxvfim713y4",
5 "title": "Home Page",
6 "description": "This is our first single type",
7 "createdAt": "2024-10-01T18:33:35.081Z",
8 "updatedAt": "2024-10-01T23:15:19.426Z",
9 "publishedAt": "2024-10-01T23:15:19.436Z",
10 "locale": null,
11 "blocks": [
12 {
13 "__component": "layout.hero-section",
14 "id": 2,
15 "heading": "Epic Next.js Tutorial",
16 "subHeading": "It's awesome just like you.",
17 "image": {
18 "id": 1,
19 "documentId": "fzwtij74oqqf9yasu9mit953",
20 "url": "/uploads/computer_working_3aee40bab7.jpg",
21 "alternativeText": null
22 },
23 "link": {
24 "id": 2,
25 "url": "/login",
26 "text": "Login",
27 "isExternal": false
28 }
29 }
30 ]
31 },
32 "meta": {}
33}
Now that we know our Strapi API works, let's move into the frontend of our project, fetch our new data, and create our Hero Section React component.
Taking a look at our frontend code, this is what we have so far.
1async function getStrapiData(url: string) {
2 const baseUrl = "http://localhost:1337";
3 try {
4 const response = await fetch(baseUrl + url);
5 const data = await response.json();
6 return data;
7 } catch (error) {
8 console.error(error);
9 }
10}
11
12export default async function Home() {
13 const strapiData = await getStrapiData("/api/home-page");
14
15 const { title, description } = strapiData.data;
16
17 return (
18 <main className="container mx-auto py-6">
19 <h1 className="text-5xl font-bold">{title}</h1>
20 <p className="text-xl mt-4">{description}</p>
21 </main>
22 );
23}
If we console log strapiData,
we will notice that we are not yet getting all our fields.
1{
2 data: {
3 id: 2,
4 documentId: 'fcnlk9xwoqmogfxvfim713y4',
5 title: 'Home Page',
6 description: 'This is our first single type',
7 createdAt: '2024-10-01T18:33:35.081Z',
8 updatedAt: '2024-10-01T18:33:35.081Z',
9 publishedAt: '2024-10-01T18:33:35.090Z',
10 locale: null
11 },
12 meta: {}
13}
That is because we need to tell Strapi what items we would like to populate. We already know how to do this; it is what we did earlier in the section when using Strapi Query Builder.
We will use the query that we defined previously.
1{
2 populate: {
3 blocks: {
4 on: {
5 "layout.hero-section": {
6 populate: {
7 image: {
8 fields: ["url", "alternativeText"]
9 },
10 link: {
11 populate: true
12 }
13 }
14 }
15 }
16 }
17 },
18}
But to make this work, we must first install the qs
package from NPM. You can learn more about it here.
It will allow us to generate our query string by passing our object from above.
Let's run the following two commands in the front end of our project.
This will add qs
.
yarn add qs
This will add the types.
yarn add @types/qs
Now that we have installed our qs
package, we can construct our query and refactor our getStrapiData
function.
Let's add the following changes to your page.tsx
file.
First let's import the qs
library.
1import qs from "qs";
Define our query.
1const homePageQuery = qs.stringify({
2 populate: {
3 blocks: {
4 on: {
5 "layout.hero-section": {
6 populate: {
7 image: {
8 fields: ["url", "alternativeText"]
9 },
10 link: {
11 populate: true
12 }
13 }
14 }
15 }
16 }
17 },
18});
Finally, let's update our getStrapiData
function.
We will use the URL
to construct our final path; you can learn more about it in the MDN docs.
Our updated function will look like the following.
1async function getStrapiData(path: string) {
2 const baseUrl = "http://localhost:1337";
3
4 const url = new URL(path, baseUrl);
5 url.search = homePageQuery;
6
7 try {
8 const response = await fetch(url.href);
9 const data = await response.json();
10 return data;
11 } catch (error) {
12 console.error(error);
13 }
14}
The final code will look as follows:
1import qs from "qs";
2
3const homePageQuery = qs.stringify({
4 populate: {
5 blocks: {
6 on: {
7 "layout.hero-section": {
8 populate: {
9 image: {
10 fields: ["url", "alternativeText"]
11 },
12 link: {
13 populate: true
14 }
15 }
16 }
17 }
18 }
19 },
20});
21
22async function getStrapiData(path: string) {
23 const baseUrl = "http://localhost:1337";
24
25 const url = new URL(path, baseUrl);
26 url.search = homePageQuery;
27
28 try {
29 const response = await fetch(url.href);
30 const data = await response.json();
31 return data;
32 } catch (error) {
33 console.error(error);
34 }
35}
36
37export default async function Home() {
38 const strapiData = await getStrapiData("/api/home-page");
39
40 console.dir(strapiData, { depth: null });
41
42 const { title, description } = strapiData.data;
43
44 return (
45 <main className="container mx-auto py-6">
46 <h1 className="text-5xl font-bold">{title}</h1>
47 <p className="text-xl mt-4">{description}</p>
48 </main>
49 );
50}
When we look at our response in the terminal, we should see that Strapi has returned all of our requested data.
1{
2 data: {
3 id: 3,
4 documentId: 'fcnlk9xwoqmogfxvfim713y4',
5 title: 'Home Page',
6 description: 'This is our first single type',
7 createdAt: '2024-10-01T18:33:35.081Z',
8 updatedAt: '2024-10-01T23:15:19.426Z',
9 publishedAt: '2024-10-01T23:15:19.436Z',
10 locale: null,
11 blocks: [
12 {
13 __component: 'layout.hero-section',
14 id: 2,
15 heading: 'Epic Next.js Tutorial',
16 subHeading: "It's awesome just like you.",
17 image: {
18 id: 1,
19 documentId: 'fzwtij74oqqf9yasu9mit953',
20 url: '/uploads/computer_working_3aee40bab7.jpg',
21 alternativeText: null
22 },
23 link: { id: 2, url: '/login', text: 'Login', isExternal: false }
24 }
25 ]
26 },
27 meta: {}
28}
Before we can render our section data, let's create our Hero Section component.
We will start with the basics to ensure that we can display our data, and then we will style the UI with Tailwind and Shadcn.
Inside the components
let's create a new folder called custom
, this is where we will add all of our components that we will create.
Inside the custom
folder let's create a bare component called hero-section.tsx
.
We will add the following code to get started.
1export function HeroSection({ data } : { readonly data: any }) {
2 console.dir(data, { depth: null })
3 return (
4 <div>Hero Section</div>
5 )
6}
We will update the types later, but for now we will do the I don't know TS
and just use any
;
Now that we have our basic component, let's import in our home page.
1import qs from "qs";
2import { HeroSection } from "@/components/custom/hero-section";
3
4const homePageQuery = qs.stringify({
5 populate: {
6 blocks: {
7 on: {
8 "layout.hero-section": {
9 populate: {
10 image: {
11 fields: ["url", "alternativeText"]
12 },
13 link: {
14 populate: true
15 }
16 }
17 }
18 }
19 }
20 },
21});
22
23async function getStrapiData(path: string) {
24 const baseUrl = "http://localhost:1337";
25
26 const url = new URL(path, baseUrl);
27 url.search = homePageQuery;
28
29 try {
30 const response = await fetch(url.href);
31 const data = await response.json();
32 return data;
33 } catch (error) {
34 console.error(error);
35 }
36}
37
38export default async function Home() {
39 const strapiData = await getStrapiData("/api/home-page");
40
41 console.dir(strapiData, { depth: null });
42
43 const { title, description, blocks } = strapiData.data;
44
45 return (
46 <main className="container mx-auto py-6">
47 <h1 className="text-5xl font-bold">{title}</h1>
48 <p className="text-xl mt-4">{description}</p>
49 <HeroSection data={blocks} />
50 </main>
51 );
52}
We should see the following output when running our app. Notice we are able to see our HeroSection component.
Now let's build out our component. Let's add the following code to get us started.
1import Link from "next/link";
2
3export function HeroSection({ data }: { readonly data: any }) {
4 console.dir(data, { depth: null });
5 return (
6 <header className="relative h-[600px] overflow-hidden">
7 <img
8 alt="Background"
9 className="absolute inset-0 object-cover w-full h-full"
10 height={1080}
11 src="https://images.pexels.com/photos/4050314/pexels-photo-4050314.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=2"
12 style={{
13 aspectRatio: "1920/1080",
14 objectFit: "cover",
15 }}
16 width={1920}
17 />
18 <div className="relative z-10 flex flex-col items-center justify-center h-full text-center text-white bg-black bg-opacity-20">
19 <h1 className="text-4xl font-bold md:text-5xl lg:text-6xl">
20 Summarize Your Videos
21 </h1>
22 <p className="mt-4 text-lg md:text-xl lg:text-2xl">
23 Save time and get the key points from your videos
24 </p>
25 <Link
26 className="mt-8 inline-flex items-center justify-center px-6 py-3 text-base font-medium text-black bg-white rounded-md shadow hover:bg-gray-100"
27 href="/login"
28 >
29 Login
30 </Link>
31 </div>
32 </header>
33 );
34}
Everything is currently hardcoded but we will fix it in just a little bit.
And do make sure that everything looks good, let's update our code in page.tsx
to remove the original styles we added in the <main>
html tag.
1return (
2 <main>
3 <HeroSection data={blocks[0]} />
4 </main>
5);
Now our UI should look like the following.
And the final code in the page.tsx
file should reflect the following changes.
1import qs from "qs";
2import { HeroSection } from "@/components/custom/hero-section";
3
4const homePageQuery = qs.stringify({
5 populate: {
6 blocks: {
7 on: {
8 "layout.hero-section": {
9 populate: {
10 image: {
11 fields: ["url", "alternativeText"],
12 },
13 link: {
14 populate: true,
15 },
16 },
17 },
18 },
19 },
20 },
21});
22
23async function getStrapiData(path: string) {
24 const baseUrl = "http://localhost:1337";
25
26 const url = new URL(path, baseUrl);
27 url.search = homePageQuery;
28
29 try {
30 const response = await fetch(url.href);
31 const data = await response.json();
32 return data;
33 } catch (error) {
34 console.error(error);
35 }
36}
37
38export default async function Home() {
39 const strapiData = await getStrapiData("/api/home-page");
40
41 console.dir(strapiData, { depth: null });
42
43 const { blocks } = strapiData.data;
44
45 return (
46 <main>
47 <HeroSection data={blocks[0]} />
48 </main>
49 );
50}
Going back to the hero-section.tsx
file, let's go ahead and display our Strapi data.
This is what our data looks like.
1{
2 __component: 'layout.hero-section',
3 id: 2,
4 heading: 'Epic Next.js Tutorial',
5 subHeading: "It's awesome just like you.",
6 image: {
7 id: 1,
8 documentId: 'fzwtij74oqqf9yasu9mit953',
9 url: '/uploads/computer_working_3aee40bab7.jpg',
10 alternativeText: null
11 },
12 link: { id: 2, url: '/login', text: 'Login', isExternal: false }
13}
Let's use this response structure do define our interface.
Let's create the following interfaces.
1interface Image {
2 id: number;
3 documentId: string;
4 url: string;
5 alternativeText: string | null;
6}
7
8interface Link {
9 id: number;
10 url: string;
11 label: string;
12}
13
14interface HeroSectionProps {
15 id: number;
16 documentId: string;
17 __component: string;
18 heading: string;
19 subHeading: string;
20 image: Image;
21 link: Link;
22}
And update our HeroSection component use our types.
1export function HeroSection({ data }: { readonly data: HeroSectionProps }) {
2 // ...rest of the code
3}
Finally, let's add our data from Strapi instead of hard coding it by making the following changes to our HeroSection component.
1import Link from "next/link";
2
3interface Image {
4 id: number;
5 documentId: string;
6 url: string;
7 alternativeText: string | null;
8}
9
10interface Link {
11 id: number;
12 url: string;
13 text: string;
14}
15
16interface HeroSectionProps {
17 id: number;
18 documentId: string;
19 __component: string;
20 heading: string;
21 subHeading: string;
22 image: Image;
23 link: Link;
24}
25
26export function HeroSection({ data }: { readonly data: HeroSectionProps }) {
27 console.dir(data, { depth: null });
28 const { heading, subHeading, image, link } = data;
29 const imageURL = "http://localhost:1337" + image.url;
30
31 return (
32 <header className="relative h-[600px] overflow-hidden">
33 <img
34 alt={image.alternativeText ?? "no alternative text"}
35 className="absolute inset-0 object-cover w-full h-full"
36 height={1080}
37 src={imageURL}
38 style={{
39 aspectRatio: "1920/1080",
40 objectFit: "cover",
41 }}
42 width={1920}
43 />
44 <div className="relative z-10 flex flex-col items-center justify-center h-full text-center text-white bg-black bg-opacity-40">
45 <h1 className="text-4xl font-bold md:text-5xl lg:text-6xl">
46 {heading}
47 </h1>
48 <p className="mt-4 text-lg md:text-xl lg:text-2xl">
49 {subHeading}
50 </p>
51 <Link
52 className="mt-8 inline-flex items-center justify-center px-6 py-3 text-base font-medium text-black bg-white rounded-md shadow hover:bg-gray-100"
53 href={link.url}
54 >
55 {link.text}
56 </Link>
57 </div>
58 </header>
59 );
60}
We are now getting and displaying our data from Strapi but here are still more improvements that we must make in this component.
Like to use Next Image and not have to hard code "http://localhost:1337" path that we append to our image url but instead should get it from our .env
variable.
We will do this in the next post, where we will finish up our Hero Section component and start working on the Features Component
We are making some great progress. In this post, we started working on displaying our Hero Section content.
In the next post, we will create the StrapiImage component using the Next Image component to make rendering Strapi images easier.
Finish up our Hero Section and start working on our Features Section.
I hope you are enjoying this series so far. Thank you for your time, and I will see you in the next one.
This project has been updated to use Next.js 15 and Strapi 5.
If you have any questions, feel free to stop by at our Discord Community for our daily "open office hours" from 12:30 PM CST to 1:30 PM CST.
If you have a suggestion or find a mistake in the post, please open an issue on the GitHub repository.
You can also find the blog post content in the Strapi Blog.
Feel free to make PRs to fix any issues you find in the project or let me know if you have any questions.
Happy coding!