In part 3 of our series, let's finish building out our home page. We will finish up our Hero Section, then move to our Features Section, and finally add our Top Navigation and Footer.
Let's refactor our Hero Section to use the Next Image component.
Instead of using it directly, we will create a new component called StrapiImage to add a few additional quality live improvements.
Inside src/app/components
, create a new file called strapi-image.tsx
and paste it into the following code.
1import Image from "next/image";
2import { getStrapiMedia } from "@/lib/utils";
3
4interface StrapiImageProps {
5 src: string;
6 alt: string;
7 height: number;
8 width: number;
9 className?: string;
10}
11
12export function StrapiImage({
13 src,
14 alt,
15 height,
16 width,
17 className,
18}: Readonly<StrapiImageProps>) {
19 const imageUrl = getStrapiMedia(src);
20 if (!imageUrl) return null;
21
22 return (
23 <Image
24 src={imageUrl}
25 alt={alt}
26 height={height}
27 width={width}
28 className={className}
29 />
30 );
31}
You will notice that we have a helper function called getStrapiMedia
; first, let's add it to our src/lib/utils.ts
file and then review what it does.
1export function getStrapiURL() {
2 return process.env.NEXT_PUBLIC_STRAPI_URL ?? "http://localhost:1337";
3}
4
5export function getStrapiMedia(url: string | null) {
6 if (url == null) return null;
7 if (url.startsWith("data:")) return url;
8 if (url.startsWith("http") || url.startsWith("//")) return url;
9 return `${getStrapiURL()}${url}`;
10}
getStrapiURL():
This function returns the URL of the Strapi API. We are setting our environment name to NEXT_PUBLIC_
, which will be available in both the server and client components.
Note: only set public for none private items when using NEXT_PUBLIC_
, they will be seen by all. You can learn more in Next.js docs.
getStrapiMedia(): This function is designed to process media URLs from the Strapi CMS. It accepts a URL as a string or null.
If the input url is null, the function returns null, which could be used in cases where an image or media file is optional.
If the input URL starts with "data:", it is returned as-is. This condition checks for data URLs, which are URLs that contain actual data (e.g., base64-encoded images) instead of linking to an external resource.
This is often used to embed small images directly in HTML or CSS to reduce the number of HTTP requests.
If the input URL starts with "http" or "//", it is also returned as-is. This covers absolute URLs, meaning the media is hosted outside the Strapi backend (possibly on another domain or CDN).
If none of the above conditions are met, the function assumes the url is a relative path to a resource on the Strapi backend.
In essence, these functions help manage and resolve media URLs in a Next.js application that uses Strapi as a headless CMS, ensuring that the application can handle local and external media resources effectively.
Now that we have our StrapiImage component let's use it in our Hero Section.
Navigate to src/app/components/custom/hero-section.tsx
and make the following changes.
First, import our newly created component.
1import { StrapiImage } from "@/components/custom/strapi-image";
Second, replace the img
tag with the following.
1<StrapiImage
2 alt={image.alternativeText ?? "no alternative text"}
3 className="absolute inset-0 object-cover w-full h-full aspect/16:9"
4 src={image.url}
5 height={1080}
6 width={1920}
7/>
And remove the following reference we had before.
1const imageURL = "http://localhost:1337" + image.url;
This is now handled inside of our StrapiImage component.
Restart the application, and... you will see the following error.
Clicking on the link in the error will take you here, which explains the steps to fix this.
Inside the root of your project, locate the next.config.mjs
file and make the following change.
1import type { NextConfig } from "next";
2
3const nextConfig: NextConfig = {
4 /* config options here */
5 images: {
6 remotePatterns: [
7 {
8 protocol: "http",
9 hostname: "localhost",
10 port: "1337",
11 pathname: "/uploads/**/*",
12 },
13 ],
14 },
15};
16
17export default nextConfig;
Now, when you restart your application, you should see the following with your image.
Nice, now let's work on our Features Section
Looking at our Features Section UI, we can break it down into the following parts.
We have a section that has repeatable components with the following items.
So, let's jump into our Strapi Admin and create our Features Section Component.
Let's start by navigating to Content-Type Builder
under COMPONENTS
, clicking on Create new component
, and let's call it Features Section and save it under the layout
category.
We will create the following fields.
Text -> Short Text - title Text -> Long Text - description
Finally, let's create a repeatable component called Feature and save it under components
Now, add the following fields.
Text -> Short Text - heading Text -> Long Text - subHeading Enum -> with the following options
Let's add our newly created Feature Section component to our home page.
Now, let's add some features data and save.
Navigate to Content Manager, select the Home Page, add the new Features Section block, and fill in your features.
We are already getting our page data; let's navigate to src/app/page.tsx
and update our query to populate our feature
repeatable component.
Let's update the homePageQuery
query with the following changes. Remember in Strapi 5 we have to user the on
flag to populate our dynamic zone components.
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 "layout.features-section": {
16 populate: {
17 feature: {
18 populate: true,
19 },
20 },
21 },
22 },
23 },
24 },
25});
Also, let's update our getStrapiData
function to use our new helper method, getStrapiURL.
So it will look like the following.
So don't forget to import it.
1import { getStrapiURL } from "@/lib/utils";
1async function getStrapiData(path: string) {
2 const baseUrl = getStrapiURL();
3
4 const url = new URL(path, baseUrl);
5 url.search = homePageQuery;
6
7 console.log(url.href);
8
9 try {
10 const response = await fetch(url.href);
11 const data = await response.json();
12 return data;
13 } catch (error) {
14 console.error(error);
15 }
16}
Now, let's console log our block
and see what the response looks like.
1console.dir(blocks, { depth: null });
We should see the following data.
1[
2 {
3 __component: "layout.hero-section",
4 id: 3,
5 heading: "Epic Next.js Tutorial",
6 subHeading: "It's awesome just like you.",
7 image: {
8 id: 1,
9 documentId: "fzwtij74oqqf9yasu9mit953",
10 url: "/uploads/computer_working_3aee40bab7.jpg",
11 alternativeText: null,
12 },
13 link: { id: 3, url: "/login", text: "Login", isExternal: false },
14 },
15 {
16 __component: "layout.features-section",
17 id: 2,
18 title: "Features",
19 description: "Checkout our cool features.",
20 feature: [
21 {
22 id: 4,
23 heading: "Save Time",
24 subHeading:
25 "No need to watch the entire video. Get the summary and save time.",
26 icon: "CLOCK_ICON",
27 },
28 {
29 id: 5,
30 heading: "Accurate Summaries",
31 subHeading:
32 "Our AI-powered tool provides accurate summaries of your videos.",
33 icon: "CHECK_ICON",
34 },
35 {
36 id: 6,
37 heading: "Cloud Based",
38 subHeading: "Access your video. summaries from anywhere at any time.",
39 icon: "CLOUD_ICON",
40 },
41 ],
42 },
43];
Notice that we are getting both our Hero Section and Features Section
Now, let's create a component to display our feature data.
Let's navigate to src/app/components/custom
, create a file called features-section.tsx,
and paste it into the following code.
1function getIcon(name: string) {
2 switch (name) {
3 case "CLOCK_ICON":
4 return ClockIcon;
5 case "CHECK_ICON":
6 return CheckIcon;
7 case "CLOUD_ICON":
8 return CloudIcon;
9 default:
10 return null;
11 }
12}
13
14export function FeatureSection() {
15 return (
16 <div className="">
17 <div className="flex-1">
18 <section className="container px-4 py-6 mx-auto md:px-6 lg:py-24">
19 <div className="grid gap-8 md:grid-cols-3">
20 <div className="flex flex-col items-center text-center">
21 <ClockIcon className="w-12 h-12 mb-4 text-gray-900" />
22 <h2 className="mb-4 text-2xl font-bold">Save Time</h2>
23 <p className="text-gray-500">
24 No need to watch the entire video. Get the summary and save
25 time.
26 </p>
27 </div>
28 <div className="flex flex-col items-center text-center">
29 <CheckIcon className="w-12 h-12 mb-4 text-gray-900" />
30 <h2 className="mb-4 text-2xl font-bold">Accurate Summaries</h2>
31 <p className="text-gray-500">
32 Our AI-powered tool provides accurate summaries of your videos.
33 </p>
34 </div>
35 <div className="flex flex-col items-center text-center">
36 <CloudIcon className="w-12 h-12 mb-4 text-gray-900" />
37 <h2 className="mb-4 text-2xl font-bold">Cloud Based</h2>
38 <p className="text-gray-500">
39 Access your video summaries from anywhere at any time.
40 </p>
41 </div>
42 </div>
43 </section>
44 </div>
45 </div>
46 );
47}
48
49function CheckIcon(props: any) {
50 return (
51 <svg
52 {...props}
53 xmlns="http://www.w3.org/2000/svg"
54 width="24"
55 height="24"
56 viewBox="0 0 24 24"
57 fill="none"
58 stroke="currentColor"
59 strokeWidth="2"
60 strokeLinecap="round"
61 strokeLinejoin="round"
62 >
63 <polyline points="20 6 9 17 4 12" />
64 </svg>
65 );
66}
67
68function ClockIcon(props: any) {
69 return (
70 <svg
71 {...props}
72 xmlns="http://www.w3.org/2000/svg"
73 width="24"
74 height="24"
75 viewBox="0 0 24 24"
76 fill="none"
77 stroke="currentColor"
78 strokeWidth="2"
79 strokeLinecap="round"
80 strokeLinejoin="round"
81 >
82 <circle cx="12" cy="12" r="10" />
83 <polyline points="12 6 12 12 16 14" />
84 </svg>
85 );
86}
87
88function CloudIcon(props: any) {
89 return (
90 <svg
91 {...props}
92 xmlns="http://www.w3.org/2000/svg"
93 width="24"
94 height="24"
95 viewBox="0 0 24 24"
96 fill="none"
97 stroke="currentColor"
98 strokeWidth="2"
99 strokeLinecap="round"
100 strokeLinejoin="round"
101 >
102 <path d="M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z" />
103 </svg>
104 );
105}
We are currently hard-coding our data, which we will update in a moment. But let's navigate to src/app/page.tsx
, import our newly created component, and see what we get.
1import { FeatureSection } from "@/components/custom/features-section";
And update the return
statement with the following code.
1return (
2 <main>
3 <HeroSection data={blocks[0]} />
4 <FeatureSection />
5 </main>
6);
When we restart our application and refresh the page with command + r
, we should see the following.
Now, let's pass our data to our component and refactor our Features Section component to consume our data from Strapi.
1return (
2 <main>
3 <HeroSection data={blocks[0]} />
4 <FeatureSection data={blocks[1]} />
5 </main>
6);
And update our Features Component code with the following.
1function getIcon(name: string) {
2 switch (name) {
3 case "CLOCK_ICON":
4 return <ClockIcon className="w-12 h-12 mb-4 text-gray-900" />;
5 case "CHECK_ICON":
6 return <CheckIcon className="w-12 h-12 mb-4 text-gray-900" />;
7 case "CLOUD_ICON":
8 return <CloudIcon className="w-12 h-12 mb-4 text-gray-900" />;
9 default:
10 return null;
11 }
12}
13
14interface FeatureProps {
15 id: number;
16 heading: string;
17 subHeading: string;
18 icon: string;
19}
20
21interface FeatureSectionProps {
22 id: number;
23 __component: string;
24 title: string;
25 description: string;
26 feature: FeatureProps[];
27}
28
29export function FeatureSection({
30 data,
31}: {
32 readonly data: FeatureSectionProps;
33}) {
34 const { feature } = data;
35 console.dir(feature, { depth: null });
36 return (
37 <div className="">
38 <div className="flex-1">
39 <section className="container px-4 py-6 mx-auto md:px-6 lg:py-24">
40 <div className="grid gap-8 md:grid-cols-3">
41 {feature.map((feature) => (
42 <div
43 key={feature.id}
44 className="flex flex-col items-center text-center"
45 >
46 {getIcon(feature.icon)}
47 <h2 className="mb-4 text-2xl font-bold">{feature.heading}</h2>
48 <p className="text-gray-500">
49 {feature.subHeading}
50 </p>
51 </div>
52 ))}
53 </div>
54 </section>
55 </div>
56 </div>
57 );
58}
59
60function CheckIcon(props: any) {
61 return (
62 <svg
63 {...props}
64 xmlns="http://www.w3.org/2000/svg"
65 width="24"
66 height="24"
67 viewBox="0 0 24 24"
68 fill="none"
69 stroke="currentColor"
70 strokeWidth="2"
71 strokeLinecap="round"
72 strokeLinejoin="round"
73 >
74 <polyline points="20 6 9 17 4 12" />
75 </svg>
76 );
77}
78
79function ClockIcon(props: any) {
80 return (
81 <svg
82 {...props}
83 xmlns="http://www.w3.org/2000/svg"
84 width="24"
85 height="24"
86 viewBox="0 0 24 24"
87 fill="none"
88 stroke="currentColor"
89 strokeWidth="2"
90 strokeLinecap="round"
91 strokeLinejoin="round"
92 >
93 <circle cx="12" cy="12" r="10" />
94 <polyline points="12 6 12 12 16 14" />
95 </svg>
96 );
97}
98
99function CloudIcon(props: any) {
100 return (
101 <svg
102 {...props}
103 xmlns="http://www.w3.org/2000/svg"
104 width="24"
105 height="24"
106 viewBox="0 0 24 24"
107 fill="none"
108 stroke="currentColor"
109 strokeWidth="2"
110 strokeLinecap="round"
111 strokeLinejoin="round"
112 >
113 <path d="M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z" />
114 </svg>
115 );
116}
Our features component should now be utilizing our Strapi data.
We do have to make one more change in the page.tsx
file to make our code dynamically display our blocks based on what we get from our response.
To accomplish this, we will create a new function called blockRenderer
and define it in the page.tsx
file.
It will look like the following:
1 const blockComponents = {
2 "layout.hero-section": HeroSection,
3 "layout.features-section": FeatureSection,
4 };
5
6 function blockRenderer(block: any) {
7 const Component = blockComponents[block.__component as keyof typeof blockComponents];
8 return Component ? <Component key={block.id} data={block} /> : null;
9 }
We can refactor the code in our page.tsx
component with the following code.
1export default async function Home() {
2 const strapiData = await getStrapiData("/api/home-page");
3
4 console.dir(strapiData, { depth: null });
5
6 const { blocks } = strapiData?.data || [];
7 return <main>{blocks.map(blockRenderer)}</main>;
8}
The completed code in the page.tsx
file should look like the following.
1import qs from "qs";
2import { getStrapiURL } from "@/lib/utils";
3
4import { HeroSection } from "@/components/custom/hero-section";
5import { FeatureSection } from "@/components/custom/features-section";
6
7const homePageQuery = qs.stringify({
8 populate: {
9 blocks: {
10 on: {
11 "layout.hero-section": {
12 populate: {
13 image: {
14 fields: ["url", "alternativeText"],
15 },
16 link: {
17 populate: true,
18 },
19 },
20 },
21 "layout.features-section": {
22 populate: {
23 feature: {
24 populate: true,
25 },
26 },
27 },
28 },
29 },
30 },
31});
32
33async function getStrapiData(path: string) {
34 const baseUrl = getStrapiURL();
35
36 const url = new URL(path, baseUrl);
37 url.search = homePageQuery;
38
39 console.log(url.href);
40
41 try {
42 const response = await fetch(url.href);
43 const data = await response.json();
44 return data;
45 } catch (error) {
46 console.error(error);
47 }
48}
49
50const blockComponents = {
51 "layout.hero-section": HeroSection,
52 "layout.features-section": FeatureSection,
53};
54
55function blockRenderer(block: any) {
56 const Component = blockComponents[block.__component as keyof typeof blockComponents];
57 return Component ? <Component key={block.id} data={block} /> : null;
58}
59
60export default async function Home() {
61 const strapiData = await getStrapiData("/api/home-page");
62 console.dir(strapiData, { depth: null });
63 const { blocks } = strapiData?.data || [];
64
65 return (
66 <main>
67 {blocks.map(blockRenderer)}
68 </main>
69 );
70}
Let's do one more quick refactor. In src
, create a new folder named data
with a file called loaders.ts
.
And add the following code.
1import qs from "qs";
2import { getStrapiURL } from "@/lib/utils";
3
4const baseUrl = getStrapiURL();
5
6async function fetchData(url: string) {
7 const authToken = null; // we will implement this later getAuthToken() later
8 const headers = {
9 method: "GET",
10 headers: {
11 "Content-Type": "application/json",
12 Authorization: `Bearer ${authToken}`,
13 },
14 };
15
16 try {
17 const response = await fetch(url, authToken ? headers : {});
18 const data = await response.json();
19 return data;
20 } catch (error) {
21 console.error("Error fetching data:", error);
22 throw error; // or return null;
23 }
24}
This will be our reusable function that will help us construct additional methods to load data.
And finally, let's create a new function, getHomePageData,
to load our home page data.
1export async function getHomePageData() {
2 const url = new URL("/api/home-page", baseUrl);
3
4 url.search = 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 "layout.features-section": {
19 populate: {
20 feature: {
21 populate: true,
22 },
23 },
24 },
25 },
26 },
27 },
28 });
29
30 return await fetchData(url.href);
31}
And finally, in the pate.tsx
file, let's import this new function and delete the previous one.
Our final code should look like the following.
1import { getHomePageData } from "@/data/loaders";
2
3import { HeroSection } from "@/components/custom/hero-section";
4import { FeatureSection } from "@/components/custom/features-section";
5
6export default async function Home() {
7 const strapiData = await getHomePageData();
8 const { blocks } = strapiData?.data || [];
9 return <main>{blocks.map(blockRenderer)}</main>;
10}
11
12const blockComponents = {
13 "layout.hero-section": HeroSection,
14 "layout.features-section": FeatureSection,
15};
16
17function blockRenderer(block: any) {
18 const Component = blockComponents[block.__component as keyof typeof blockComponents];
19 return Component ? <Component key={block.id} data={block} /> : null;
20}
Nice. Let's move on and start working on our Header and Footer
Taking a quick look at our Header and Footer, we see that they are simple enough. In the header, we have two items, logo text
and button.
In the footer, we have logo text,
text,
and social icons.
Let's first start by taking a look at how we have represented this data in Strapi.
We are going to store the data for our' Header' and' Footer' using a single type.'
Navigating to Content-Type Builder
under SINGLE TYPE
and clicking on Create new single type.
We are going to call it Global
. Go ahead and add the following fields.
Text -> Short Text - title Text -> Long Text - description
Now, let's create the Header component. To start with, it will have two links: logo text and a call to action
button.
In Strapi, inside the global page, let's add the following component.
add another field to this single type.
Component
field typeDisplay Name
will be HeaderCategory
will be Layout
Configure the component
buttonName
field, we will enter headerAdd the first field to component
buttonNow let's create two additional components called logoText
and ctaButton
to store our logo text and call to action button data.
Since both will be links, we can reuse a previously created Link component.
Component
field typeUse an existing component
Select component
buttonSelect a component
field, select Link componentName
field, we will enter logoTextSelect Single component
and click the Finish
button
Select Add another field to this component
Component
field typeUse an existing component
Select a component
buttonName
field, we will enter ctaButtonSelect a component
field, select Link componentSingle component
and click the Finish
buttonThe final Header component should look like the following.
Now that we are getting the hang of modeling content think about how we can represent our footer.
We can create the Footer the same way we made our Header.
Can you do it on your own?
Our Footer will have the following fields.
Our footer has the following three items.
If you get stuck at any point, you can always ask in the comments or join us at Strapi Open Office hours on Discord 12:30 pm CST Monday - Friday.
Let's add some data to our Global single type.
Now, let's give the proper permissions so we can access the data from our Strapi API.
Navigate to Setting
-> USERS AND PERMISSION PLUGIN
-> Roles
-> Public
-> Global
and check the find
checkbox. We now should be able to make a GET
request to /api/global
and see our data.
Since we have already learned about Strapi's Populate, we can jump straight into our frontend code and implement the function to fetch our Global data.
Let's navigate to src/data/loaders.ts
and create a new function called getGlobalData
; it should look like the following.
1export async function getGlobalData() {
2 const url = new URL("/api/global", baseUrl);
3
4 url.search = qs.stringify({
5 populate: [
6 "header.logoText",
7 "header.ctaButton",
8 "footer.logoText",
9 "footer.socialLink",
10 ],
11 });
12
13 return await fetchData(url.href);
14}
One thing to notice here is that we are using array
notation in populate, which is a great way to populate items that don't have many nested items.
If you need more help with Populate and Filtering in Strapi, check out this post.
Now that we have our getGlobalData
function let's use it.
Since our Header and Footer will live int the layout.tsx
file, let's call our function there.
Since we can load data within our React Server Component, we can call the function there directly.
First, let's import our function.
1import { getGlobalData } from "@/data/loaders";
Then, update the RootLayout with the following code.
1export default async function RootLayout({
2 children,
3}: Readonly<{
4 children: React.ReactNode,
5}>) {
6 const globalData = await getGlobalData();
7 console.dir(globalData, { depth: null });
8 return (
9 <html lang="en">
10 <body
11 className={`${geistSans.variable} ${geistMono.variable} antialiased`}
12 >
13 {children}
14 </body>
15 </html>
16 );
17}
The complete code should look like the following.
1import type { Metadata } from "next";
2import localFont from "next/font/local";
3import "./globals.css";
4
5import { getGlobalData } from "@/data/loaders";
6
7const geistSans = localFont({
8 src: "./fonts/GeistVF.woff",
9 variable: "--font-geist-sans",
10 weight: "100 900",
11});
12const geistMono = localFont({
13 src: "./fonts/GeistMonoVF.woff",
14 variable: "--font-geist-mono",
15 weight: "100 900",
16});
17
18export const metadata: Metadata = {
19 title: "Create Next App",
20 description: "Generated by create next app",
21};
22
23export default async function RootLayout({
24 children,
25}: Readonly<{
26 children: React.ReactNode,
27}>) {
28 const globalData = await getGlobalData();
29 console.dir(globalData, { depth: null });
30 return (
31 <html lang="en">
32 <body
33 className={`${geistSans.variable} ${geistMono.variable} antialiased`}
34 >
35 {children}
36 </body>
37 </html>
38 );
39}
Nice. Now restart your Next.js application, and we should see the following output in the terminal console.
1{
2 data: {
3 id: 2,
4 documentId: 'fyj7ijjnkxy75h1cbusrafj2',
5 title: 'Global Page',
6 description: 'Responsible for our header and footer.',
7 createdAt: '2024-10-02T18:44:37.585Z',
8 updatedAt: '2024-10-02T18:44:37.585Z',
9 publishedAt: '2024-10-02T18:44:37.594Z',
10 locale: null,
11 header: {
12 id: 2,
13 ctaButton: { id: 11, url: '/', text: 'Login', isExternal: false },
14 logoText: { id: 10, url: '/', text: 'Summarize AI', isExternal: false }
15 },
16 footer: {
17 id: 2,
18 text: 'Made with love by Paul',
19 socialLink: [
20 {
21 id: 13,
22 url: 'www.youtube.com',
23 text: 'YouTube',
24 isExternal: true
25 },
26 {
27 id: 14,
28 url: 'www.twitter.com',
29 text: 'Twitter',
30 isExternal: true
31 },
32 {
33 id: 15,
34 url: 'www.linkedin.com',
35 text: 'LinkedIn',
36 isExternal: true
37 }
38 ],
39 logoText: { id: 12, url: '/', text: 'Summarize AI', isExternal: false }
40 }
41 },
42 meta: {}
43}
That is amazing.
Alright, let's build out our Header component for our top navigation.
Just as a reminder, our logo has two items. A logo and button , so let's first create our Logo
component.
Navigate to src/app/components/custom
, create a file called logo.tsx,
and add the following code.
1import Link from "next/link";
2
3function MountainIcon(props: any) {
4 return (
5 <svg
6 {...props}
7 xmlns="http://www.w3.org/2000/svg"
8 width="24"
9 height="24"
10 viewBox="0 0 24 24"
11 fill="none"
12 stroke="currentColor"
13 strokeWidth="2"
14 strokeLinecap="round"
15 strokeLinejoin="round"
16 >
17 <path d="m8 3 4 8 5-5 5 15H2L8 3z" />
18 </svg>
19 );
20}
21
22interface LogoProps {
23 text?: string;
24 dark?: boolean;
25}
26
27export function Logo({
28 text = "Logo Text",
29 dark = false,
30}: Readonly<LogoProps>) {
31 return (
32 <Link className="flex items-center gap-2" href="/">
33 <MountainIcon className={"h-6 w-6 text-pink-500"} />
34 <span
35 className={`text-lg font-semibold ${
36 dark ? "text-white" : "text-slate-900"
37 }`}
38 >
39 {text}
40 </span>
41 </Link>
42 );
43}
It is a simple component that expects text
as a prop to display the name of our site and a dark
prop to allow us to make the text white on dark backgrounds.
Next, let's create our actual Header component. Navigate to src/app/components/custom
, create a file called header.tsx,
and add the following code.
1import Link from "next/link";
2import { Logo } from "@/components/custom/logo";
3import { Button } from "@/components/ui/button";
4
5interface HeaderProps {
6 data: {
7 logoText: {
8 id: number;
9 text: string;
10 url: string;
11 }
12 ctaButton: {
13 id: number;
14 text: string;
15 url: string;
16 };
17 }
18}
19
20export async function Header({ data }: Readonly<HeaderProps>) {
21 const { logoText, ctaButton } = data;
22 return (
23 <div className="flex items-center justify-between px-4 py-3 bg-white shadow-md dark:bg-gray-800">
24 <Logo text={logoText.text}/>
25 <div className="flex items-center gap-4">
26 <Link href={ctaButton.url}><Button>{ctaButton.text}</Button></Link>
27 </div>
28 </div>
29 );
30}
The component expects our header
props, which we already get from our getGlobalData
function found in the layout.tsx
file.
So let's navigate to src/app/layout.tsx
file and make the following updates.
First, let's import our Header component.
1import { Header } from "@/components/custom/header";
Next, make the following change in the return
statement.
1return (
2 <html lang="en">
3 <body className={`${geistSans.variable} ${geistMono.variable} antialiased`}>
4 <Header data={globalData.data.header} />
5 <div>{children}</div>
6 </body>
7 </html>
8);
Restart your project, and you should now see our awesome top navigation.
Now, let's go ahead and build out our footer.
Our footer will display the following items.
Navigate to src/app/components/custom,
create a file called footer.tsx,
and add the following code.
1import Link from "next/link";
2import { Logo } from "@/components/custom/logo";
3
4interface SocialLink {
5 id: number;
6 text: string;
7 url: string;
8}
9
10interface FooterProps {
11 data: {
12 logoText: {
13 id: number,
14 text: string,
15 url: string,
16 },
17 text: string,
18 socialLink: SocialLink[],
19 };
20}
21
22function selectSocialIcon(url: string) {
23 if (url.includes("youtube")) return <YoutubeIcon className="h-6 w-6" />;
24 if (url.includes("twitter")) return <TwitterIcon className="h-6 w-6" />;
25 if (url.includes("github")) return <GithubIcon className="h-6 w-6" />;
26 return null;
27}
28
29export function Footer({ data }: Readonly<FooterProps>) {
30 const { logoText, socialLink, text } = data;
31 return (
32 <div className="dark bg-gray-900 text-white py-8">
33 <div className="container mx-auto px-4 md:px-6 flex flex-col md:flex-row items-center justify-between">
34 <Logo dark text={logoText.text} />
35 <p className="mt-4 md:mt-0 text-sm text-gray-300">{text}</p>
36 <div className="flex items-center space-x-4">
37 {socialLink.map((link) => {
38 return (
39 <Link
40 className="text-white hover:text-gray-300"
41 href={link.url}
42 key={link.id}
43 >
44 {selectSocialIcon(link.url)}
45 <span className="sr-only">Visit us at {link.text}</span>
46 </Link>
47 );
48 })}
49 </div>
50 </div>
51 </div>
52 );
53}
54
55function GithubIcon(props: any) {
56 return (
57 <svg
58 {...props}
59 xmlns="http://www.w3.org/2000/svg"
60 width="24"
61 height="24"
62 viewBox="0 0 24 24"
63 fill="none"
64 stroke="currentColor"
65 strokeWidth="2"
66 strokeLinecap="round"
67 strokeLinejoin="round"
68 >
69 <path d="M15 22v-4a4.8 4.8 0 0 0-1-3.5c3 0 6-2 6-5.5.08-1.25-.27-2.48-1-3.5.28-1.15.28-2.35 0-3.5 0 0-1 0-3 1.5-2.64-.5-5.36-.5-8 0C6 2 5 2 5 2c-.3 1.15-.3 2.35 0 3.5A5.403 5.403 0 0 0 4 9c0 3.5 3 5.5 6 5.5-.39.49-.68 1.05-.85 1.65-.17.6-.22 1.23-.15 1.85v4" />
70 <path d="M9 18c-4.51 2-5-2-7-2" />
71 </svg>
72 );
73}
74
75function TwitterIcon(props: any) {
76 return (
77 <svg
78 {...props}
79 xmlns="http://www.w3.org/2000/svg"
80 width="24"
81 height="24"
82 viewBox="0 0 24 24"
83 fill="none"
84 stroke="currentColor"
85 strokeWidth="2"
86 strokeLinecap="round"
87 strokeLinejoin="round"
88 >
89 <path d="M22 4s-.7 2.1-2 3.4c1.6 10-9.4 17.3-18 11.6 2.2.1 4.4-.6 6-2C3 15.5.5 9.6 3 5c2.2 2.6 5.6 4.1 9 4-.9-4.2 4-6.6 7-3.8 1.1 0 3-1.2 3-1.2z" />
90 </svg>
91 );
92}
93
94function YoutubeIcon(props: any) {
95 return (
96 <svg
97 {...props}
98 xmlns="http://www.w3.org/2000/svg"
99 width="24"
100 height="24"
101 viewBox="0 0 24 24"
102 fill="none"
103 stroke="currentColor"
104 strokeWidth="2"
105 strokeLinecap="round"
106 strokeLinejoin="round"
107 >
108 <path d="M2.5 17a24.12 24.12 0 0 1 0-10 2 2 0 0 1 1.4-1.4 49.56 49.56 0 0 1 16.2 0A2 2 0 0 1 21.5 7a24.12 24.12 0 0 1 0 10 2 2 0 0 1-1.4 1.4 49.55 49.55 0 0 1-16.2 0A2 2 0 0 1 2.5 17" />
109 <path d="m10 15 5-3-5-3z" />
110 </svg>
111 );
112}
The code is responsible for rendering our Footer data.
selectSocialIcon(url: string): A function that determines which social media icon to display based on the URL provided. It supports YouTube, Twitter, and GitHub, returning the corresponding icon component or null if the URL does not match these platforms.
note: When adding social links, I only included Twitter, Github, and YouTube. If you have additional links, you will need to add more icons to represent them.
Here is what my response looks like with my social links.
1[
2 {
3 id: 25,
4 url: "www.youtube.com",
5 text: "YouTube",
6 isExternal: true,
7 },
8 {
9 id: 26,
10 url: "www.twitter.com",
11 text: "Twitter",
12 isExternal: true,
13 },
14 {
15 id: 27,
16 url: "www.github.com",
17 text: "GitHub",
18 isExternal: true,
19 },
20];
Now that we have completed our footer, let's add it to the layout.tsx file in the root of our app folder.
First, let's import our Footer component.
1import { Footer } from "@/components/custom/footer";
Next, make the following change in the return
statement.
1return (
2 <html lang="en">
3 <body className={`${geistSans.variable} ${geistMono.variable} antialiased`}>
4 <Header data={globalData.data.header} />
5 {children}
6 <Footer data={globalData.data.footer} />
7 </body>
8 </html>
9);
Now, if you restart the Next.js application, you should see the following changes.
Yay, we are now getting our data from our Strapi API.
We have a title
and description
on our Global page in Strapi.
Let's use it as our metadata
information in our app.
Let's look at the src/app/layout.tsx
file. We will see the following.
1export const metadata: Metadata = {
2 title: "Create Next App",
3 description: "Generated by create next app",
4};
This is one way to set metadata in Next.js, but as you notice, it is hardcoded. Let's look at how we can add metadata dynamically.
To dynamically populate our metadata, we must fetch it using our metadata
function.
We already have our getGlobalData
, but that function returns not just the title
and description
but also the rest of our data to populate our Header and Footer.
Let's create a new function called getGlobalPageMetadata,
which only returns the title
and description
fields.
Let's navigate to src/data/loaders.ts
and add the following code.
1export async function getGlobalPageMetadata() {
2 const url = new URL("/api/global", baseUrl);
3
4 url.search = qs.stringify({
5 fields: ["title", "description"],
6 });
7
8 return await fetchData(url.href);
9}
In the function above, we ask Strapi to return only the title
and description,
which are the only data we need for our metadata.
The response will look like the following.
1data: {
2 id: 4,
3 documentId: 'fyj7ijjnkxy75h1cbusrafj2',
4 title: 'Global Page',
5 description: 'Responsible for our header and footer.'
6},
Let's implement dynamic metadata inside our layout.tsx
file.
Let's update our current metadata
function with the following.
First, let's import the following.
1import { getGlobalData, getGlobalPageMetadata } from "@/data/loaders";
Now, replace the previous export const metadata: Metadata
with the following code.
1export async function generateMetadata(): Promise<Metadata> {
2 const metadata = await getGlobalPageMetadata();
3
4 return {
5 title: metadata?.data?.title ?? "Epic Next Course",
6 description: metadata?.data?.description ?? "Epic Next Course",
7 };
8}
Now, our metadata is dynamically set from our Strapi Api.
The completed code should look like the following:
1import type { Metadata } from "next";
2import localFont from "next/font/local";
3import "./globals.css";
4
5import { getGlobalData, getGlobalPageMetadata } from "@/data/loaders";
6
7import { Header } from "@/components/custom/header";
8import { Footer } from "@/components/custom/footer";
9
10const geistSans = localFont({
11 src: "./fonts/GeistVF.woff",
12 variable: "--font-geist-sans",
13 weight: "100 900",
14});
15const geistMono = localFont({
16 src: "./fonts/GeistMonoVF.woff",
17 variable: "--font-geist-mono",
18 weight: "100 900",
19});
20
21export async function generateMetadata(): Promise<Metadata> {
22 const metadata = await getGlobalPageMetadata();
23
24 return {
25 title: metadata?.data?.title ?? "Epic Next Course",
26 description: metadata?.data?.description ?? "Epic Next Course",
27 };
28}
29
30export default async function RootLayout({
31 children,
32}: Readonly<{
33 children: React.ReactNode;
34}>) {
35 const globalData = await getGlobalData();
36 console.dir(globalData, { depth: null });
37 return (
38 <html lang="en">
39 <body
40 className={`${geistSans.variable} ${geistMono.variable} antialiased`}
41 >
42 <Header data={globalData.data.header} />
43 {children}
44 <Footer data={globalData.data.footer} />
45 </body>
46 </html>
47 );
48}
Nice job.
Our landing page looks great, but we have a small problem. We have not yet implemented the login
page, so when we click our link, we get the default not found page.
But why, if we wanted to make it prettier, how can we accomplish this?
Well, we can create the not-found.js
page. You can learn more about it here in the Next.js docs.
Navigate to src/app,
create a file called not-found.tsx,
and add the following code.
1import Link from "next/link";
2
3export default function NotFoundRoot() {
4 return (
5 <div className="flex flex-col items-center justify-center min-h-screen bg-gray-100 dark:bg-gray-900">
6 <div className="space-y-4">
7 <BugIcon className="h-24 w-24 text-pink-500 dark:text-pink-400" />
8 <h1 className="text-4xl font-bold text-gray-900 dark:text-gray-100">
9 Oops!
10 </h1>
11 <p className="text-lg text-gray-700 dark:text-gray-300">
12 This page has left the building.
13 </p>
14 <Link
15 href="/"
16 className="inline-flex h-10 items-center justify-center rounded-md bg-gray-900 px-8 text-sm font-medium text-gray-50 shadow transition-colors hover:bg-gray-900/90 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-gray-950 disabled:pointer-events-none disabled:opacity-50 dark:bg-gray-50 dark:text-gray-900 dark:hover:bg-gray-50/90 dark:focus-visible:ring-gray-300"
17 >
18 Go back home
19 </Link>
20 </div>
21 </div>
22 );
23}
24
25function BugIcon({ className }: { className?: string }) {
26 return (
27 <svg
28 xmlns="http://www.w3.org/2000/svg"
29 width="24"
30 height="24"
31 viewBox="0 0 24 24"
32 fill="none"
33 stroke="currentColor"
34 strokeWidth="2"
35 strokeLinecap="round"
36 strokeLinejoin="round"
37 className={className}
38 >
39 <path d="m8 2 1.88 1.88" />
40 <path d="M14.12 3.88 16 2" />
41 <path d="M9 7.13v-1a3.003 3.003 0 1 1 6 0v1" />
42 <path d="M12 20c-3.3 0-6-2.7-6-6v-3a4 4 0 0 1 4-4h4a4 4 0 0 1 4 4v3c0 3.3-2.7 6-6 6" />
43 <path d="M12 20v-9" />
44 <path d="M6.53 9C4.6 8.8 3 7.1 3 5" />
45 <path d="M6 13H2" />
46 <path d="M3 21c0-2.1 1.7-3.9 3.8-4" />
47 <path d="M20.97 5c0 2.1-1.6 3.8-3.5 4" />
48 <path d="M22 13h-4" />
49 <path d="M17.2 17c2.1.1 3.8 1.9 3.8 4" />
50 </svg>
51 );
52}
Now restart your app and navigate to our login
page. You will be treated to this nicer page. It can be better, but you get the point.
Wouldn't it be nice to show a loaded spinner when navigation pages are displayed? Yes, it would. Let's see how we can do that.
There are many ways to handle the loading state in Next.js; we will start with the simplest one.
This creates a file called loading.tsx
. You can read about other ways here.
Navigate to src/app
, create a file called loading.tsx
, and add the following code.
1export default function Loading() {
2 return (
3 <div className="fixed inset-0 flex items-center justify-center bg-gray-200 bg-opacity-50">
4 <div className="animate-spin h-12 w-12 border-t-4 border-pink-600 rounded-full" />
5 </div>
6 );
7}
That is all we need to do. Now, let's restart our application and see the amazing loader in action. If you find my loader too boring, feel free to add your own design flair to your application.
Finally, let's take a look at how we can handle errors in our application.
Now, let's examine how to handle errors in Next.js to prevent our app from crashing completely.
Right now, if I go to the src/data/loaders.ts
and add the following, I can throw an error inside the getHomePageData
function.
1throw new Error("Test error");
The complete function will look like the following.
1export async function getHomePageData() {
2 throw new Error("Test error");
3
4 const url = new URL("/api/home-page", baseUrl);
5
6 url.search = qs.stringify({
7 populate: {
8 blocks: {
9 populate: {
10 image: {
11 fields: ["url", "alternativeText"],
12 },
13 link: {
14 populate: true,
15 },
16 feature: {
17 populate: true,
18 },
19 },
20 },
21 },
22 });
23
24 return await fetchData(url.href);
25}
Our app will break with an ugly error.
We can fix this by creating an error.ts
file to break our app gracefully. You can read more about Next.js errors here
Let's create a file called error.tsx
inside our app folder and paste it into the following code.
1"use client";
2import { useEffect } from "react";
3import { cn } from "@/lib/utils";
4
5export default function Error({
6 error,
7}: {
8 error: Error & { digest?: string },
9}) {
10 useEffect(() => {
11 console.error(error);
12 }, [error]);
13
14 return (
15 <div className="flex flex-col items-center justify-center min-h-screen bg-gray-100 dark:bg-gray-900">
16 <div className="space-y-4">
17 <BugIcon className="h-24 w-24 text-pink-500 dark:text-pink-400" />
18 <h1 className="text-4xl font-bold text-gray-900 dark:text-gray-100">
19 Oops! Something went wrong.
20 </h1>
21 <p className="text-lg text-gray-700 dark:text-gray-300">
22 This is an error page. Please try again later.
23 </p>
24 <p className="text-pink-800 italic">{error.message}</p>
25 </div>
26 </div>
27 );
28}
29
30function BugIcon({ className }: { className?: string }) {
31 return (
32 <svg
33 xmlns="http://www.w3.org/2000/svg"
34 width="24"
35 height="24"
36 viewBox="0 0 24 24"
37 fill="none"
38 stroke="currentColor"
39 strokeWidth="2"
40 strokeLinecap="round"
41 strokeLinejoin="round"
42 className={cn(className)}
43 >
44 <path d="m8 2 1.88 1.88" />
45 <path d="M14.12 3.88 16 2" />
46 <path d="M9 7.13v-1a3.003 3.003 0 1 1 6 0v1" />
47 <path d="M12 20c-3.3 0-6-2.7-6-6v-3a4 4 0 0 1 4-4h4a4 4 0 0 1 4 4v3c0 3.3-2.7 6-6 6" />
48 <path d="M12 20v-9" />
49 <path d="M6.53 9C4.6 8.8 3 7.1 3 5" />
50 <path d="M6 13H2" />
51 <path d="M3 21c0-2.1 1.7-3.9 3.8-4" />
52 <path d="M20.97 5c0 2.1-1.6 3.8-3.5 4" />
53 <path d="M22 13h-4" />
54 <path d="M17.2 17c2.1.1 3.8 1.9 3.8 4" />
55 </svg>
56 );
57}
Now, when our app crashes, it does not look as scary.
Let's see if we can fix this.
Excellent, we covered a lot in this post. Let's do a quick recap of what we covered.
In Part 3 of the Epic Next.js 14 Tutorial series, we focused on completing the home page design of a real-life project. The tutorial covered several key areas:
Refactoring the Hero Section: we refactored the Hero Section to use the Next.js Image component for optimized image handling. This included creating a custom StrapiImage component for additional quality-of-life improvements.
Building the Features Section: This Section involved modeling the Features Section data in Strapi, creating corresponding components in Next.js, and implementing functionality to display features dynamically from the Strapi CMS.
Displaying Dynamic Meta Data: We examined how to get our metadata from Strapi and display it on our layout.tsx
page.
Top Header and Footer: We created our Header and Footer, leveraging Strapi to manage and fetch global data like logo texts and social links.
We finished by covering how to handle loading, not found, and errors pages.
I can't wait to see the next post, where we cover how to create our Sign In and Sign Up pages. This will include form validation with Zod
, handling form submission with server actions
, creating and storing http only
cookies, and protecting our routes with Next.js middleware
.
I am so excited. Thanks for checking out this post. I look forward to seeing 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!