Strapi is the leading open-source composable Content Management System (CMS). It is 100% JavaScript, based on Node.js, and used to build RESTful APIs and GraphQL APIs. It also has a cloud SAAS, Strapi Cloud - a fully managed, composable, and collaborative platform to boost your content velocity!
Strapi enables developers to build projects faster with a flexible and customizable platform for managing content. Its even suitable for managing multilingual websites and their content. Check out the Strapi Quickstart guide for a brief intro.
The Strapi Team made a New Strapi Starter using Next.js 13, Tailwind, and TypeScript. In this tutorial, you will learn to create a blog website based on the new Strapi Starter. The blog will use Strapi for the backend and Next.js 13 for the frontend.
Here's the final result of the blog website you will build if you want to see it. Check out the project repo here.
v4.10.x
v16.x.x
or v18.x.x
. You can download Node.js here.v1.22.x
. You can download yarn here.Open up your terminal and create a blog-strapi
folder to store your project files.
mkdir blog-strapi
Navigate into blog-strapi
.
cd blog-strapi
Create your Strapi app in a folder named backend
.
npx create-strapi-app@4.10.4 backend --quickstart
NOTE: At the time of making this tutorial, there was a bug in the file import in versions after 4.10.4, so please use this version for a smooth experience.
The --quickstart
flag sets up your Strapi app with an SQLite database and automatically starts your server on port 1337
.
TIP If the server is not already running in your terminal,
cd
into thebackend
folder and runyarn develop
to launch it.
Visit http://localhost:1337/admin
in your browser and register your details in the Strapi Admin Registration Form.
After registering your admin user, you should see the Strapi Dashboard
in your browser.
Next, you will seed your Strapi app database with data to use for the blog post. This includes articles, authors, images, categories, and so on. The Data import feature is quite handy in that regard.
Go back to your terminal and stop your Strapi backend server by pressing CTRL
plus C
on your keyboard.
Update the schema for your Strapi app so that the data won't be lost when you perform a data import. Make sure you are executing the command in the root of your project folder blog-strapi
.
NOTE: You may need to install wget via brew install on your Mac.
wget https://raw.githubusercontent.com/Marktawa/blog-strapi-archives/main/seed-schema.tar
tar xvf seed-schema.tar -C backend
Next, import data into your backend's database.
wget https://raw.githubusercontent.com/strapi/nextjs-corporate-starter/main/seed-data.tar.gz
cd backend
yarn strapi import -f ../seed-data.tar.gz
Answer y
to The import will delete all assets and data in your database. Are you sure you want to proceed? (y/N)
NOTE: The data used to seed the database is from the Strapi Nextjs Starter.
After a successful import, rerun your Strapi backend server.
yarn develop
In your browser, log in to your admin panel. You should see the newly imported content
and collection types
.
In a new terminal session, change the directory to blog-strapi
and run the following command:
yarn create next-app
On installation, you'll see some prompts. Name your project frontend
and refer to the image below for the other responses.
Add the following dependencies to your frontend
Next app: @types/negotiator
, negotiator
, @types/qs
, qs
, classnames
, react-icons
, react-markdown
, react-slideshow-image
, remark-gfm
, @formatjs/intl-localematcher
for use later.
cd frontend
yarn add @types/negotiator negotiator @types/qs qs classnames react-icons react-markdown react-slideshow-image remark-gfm @formatjs/intl-localematcher
Move the following dependencies to devdependencies in your frontend
Next app: autoprefixer
, postcss
, tailwindcss
.
yarn remove autoprefixer postcss tailwindcss
yarn add autoprefixer postcss tailwindcss --dev
Delete the following auto-generated files in your frontend
directory, as we will not need them:
src/app/favicon.ico
src/app/layout.tsx
src/app/page.tsx
src/app/globals.css
Create a .env
file in the root of your frontend
directory and paste the following environment variables:
NEXT_PUBLIC_STRAPI_API_TOKEN=your-api-token
NEXT_PUBLIC_PAGE_LIMIT=6
NEXT_PUBLIC_STRAPI_API_URL=http://localhost:1337
Go back to your Strapi Admin panel to create the API token to be used for displaying content.
Inside your Strapi Admin Panel, click on Settings
, select API Tokens
and click on the + Create new API Token
button.
Configure your API Token with the following details:
Public API Token Content
Access to public content
Unlimited
Custom
Configure your API Token with the following permissions:
Content | Permissions |
---|---|
Article | find and findOne |
Author | find and findOne |
Category | find and findOne |
Global | find |
Page | find and findOne |
Product-feature | find and findOne |
Click on Save
then copy the generated API token and paste it next to the NEXT_PUBLIC_STRAPI_API_TOKEN
in your .env
file.
NOTE: The generated API token is only visible once, so make sure to copy it right after you generate one.
Your updated .env
file should have environment variables similar to this:
NEXT_PUBLIC_STRAPI_API_TOKEN=ab2bfc3f905e61b58cbb76c1d459609ac29351249f5ffb98db9dd6d109ab60d651de15e0d31e3e367a754e622fe3c918fef89f0c28ae7b9c6e788d3db4d2ea7abd7b282b37b8448886c865607965ea82c57648e11de6bb278c7bbac811051287dbf6657cac0604716fd4d4501771db43b36b531b8418ca5c8a4bc248eb85b266
NEXT_PUBLIC_PAGE_LIMIT=6
NEXT_PUBLIC_STRAPI_API_URL=http://localhost:1337
Of course, the NEXT_PUBLIC_STRAPI_API_TOKEN
for your Strapi server app will be different from the one shown above.
Create a i18n-config.ts
file in the root of your frontend
folder to set up the internationalization configuration.
touch frontend/i18n-config.ts
Add the following code to i18n-config.ts
:
export const i18n = {
defaultLocale: 'en',
locales: ['en', 'de', 'cs'],
} as const;
export type Locale = typeof i18n\['locales'\][number];
Before the data request from the Strapi backend is completed, middleware is required to handle certain tasks in a Next.js frontend app.
Create a new file named middleware.ts
in the frontend/src
directory.
touch frontend/src/middleware.ts
The middleware.ts
file serves the purpose of adding internationalization (i18n) support to the application. It ensures that the URL contains a locale segment and redirects the user to the appropriate URL if a locale is missing. Additionally, it determines the best-matched locale based on the request headers using language negotiation and the available locales.
Find out more about Next.js middleware on the Routing: Middleware | Next.js page.
Open up middleware.ts
and add the following code:
1 // ./frontend/src/middleware.ts
2
3 import type { NextRequest } from 'next/server';
4 import { NextResponse } from 'next/server';
5
6 import { i18n } from '../i18n-config';
7
8 import { match as matchLocale } from '@formatjs/intl-localematcher';
9 import Negotiator from 'negotiator';
10
11 function getLocale(request: NextRequest): string | undefined {
12 // Negotiator expects plain object so we need to transform headers
13 const negotiatorHeaders: Record<string, string> = {};
14 request.headers.forEach((value, key) => (negotiatorHeaders[key] = value));
15
16 // Use negotiator and intl-localematcher to get best locale
17 let languages = new Negotiator({ headers: negotiatorHeaders }).languages();
18 // @ts-ignore locales are readonly
19 const locales: string[] = i18n.locales;
20 return matchLocale(languages, locales, i18n.defaultLocale);
21 }
22
23 export function middleware(request: NextRequest) {
24 const pathname = request.nextUrl.pathname;
25
26 // // `/_next/` and `/api/` are ignored by the watcher, but we need to ignore files in `public` manually.
27 // // If you have one
28 if (
29 [
30 '/manifest.json',
31 '/favicon.ico',
32 // Your other files in `public`
33 ].includes(pathname)
34 )
35 return;
36
37 // Check if there is any supported locale in the pathname
38 const pathnameIsMissingLocale = i18n.locales.every(
39 (locale) => !pathname.startsWith(`/${locale}/`) && pathname !== `/${locale}`
40 );
41
42 // Redirect if there is no locale
43 if (pathnameIsMissingLocale) {
44 const locale = getLocale(request);
45
46 // e.g. incoming request is /products
47 // The new URL is now /en-US/products
48 return NextResponse.redirect(new URL(`/${locale}/${pathname}`, request.url));
49 }
50 }
51
52 export const config = {
53 // Matcher ignoring `/_next/` and `/api/`
54 matcher: ['/((?!_next).*)'],
55 };
The middleware.ts
file imports NextRequest
and NextResponse
types to handle incoming requests and generate responses in Next.js. It imports the i18n
object from the i18n-config
module we created earlier to access the available locales. The matchLocale
function is used for matching and determining the best locale based on the request headers and available locales.
In this step, we will create two files, api-helpers.ts
and fetch-api.tsx
to fetch data from the Strapi API backend.
In your frontend/src/app
directory, create a new directory named [lang]
for handling the locales we defined in i18n-config.ts
. This is handled through Next.js' dynamic routes feature.
mkdir frontend/src/app/[lang]
In your frontend/src/app/[lang]
directory, create a new directory and name it utils
. Execute these commands in the root of your frontend
folder.
cd frontend
mkdir src/app/[lang]/utils
In the utils
folder, create api-helpers.ts
and fetch-api.tsx
.
touch src/app/[lang]/utils/api-helpers.ts src/app/[lang]/utils/fetch-api.tsx
Add the following code to api-helpers.ts
:
1 // ./frontend/src/app/[lang]/utils/api-helpers.ts
2
3 export function getStrapiURL(path = '') {
4 return `${process.env.NEXT_PUBLIC_STRAPI_API_URL || 'http://localhost:1337'}${path}`;
5 }
6
7 export function getStrapiMedia(url: string | null) {
8 if (url == null) {
9 return null;
10 }
11
12 // Return the full URL if the media is hosted on an external provider
13 if (url.startsWith('http') || url.startsWith('//')) {
14 return url;
15 }
16
17 // Otherwise prepend the URL path with the Strapi URL
18 return `${getStrapiURL()}${url}`;
19 }
20
21 export function formatDate(dateString: string) {
22 const date = new Date(dateString);
23 const options: Intl.DateTimeFormatOptions = { year: 'numeric', month: 'long', day: 'numeric' };
24 return date.toLocaleDateString('en-US', options);
25 }
api-helpers.ts
defines two helper functions: getStrapiURL
and getStrapiMedia
.
getStrapiURL
: This function returns the Strapi API URL. If the NEXT_PUBLIC_STRAPI_API_URL
environment variable is set it will use the value as a base URL otherwise it defaults to http://localhost:1337
. It takes an optional path
parameter that represents a path to a specific endpoint. It concatenates the base URL with the provided path
and returns the complete URL.getStrapiMedia
: This function returns the correct URL for media regardless of whether the media is hosted externally or within the Strapi API.These helper functions provide a convenient way to handle the Strapi API URL and media URLs for our frontend app.
Add the following code to fetch-api.tsx
:
1 // ./frontend/stc/app/[lang]/utils/fetch-api.tsx
2 import qs from "qs";
3 import { getStrapiURL } from "./api-helpers";
4
5 export async function fetchAPI(
6 path: string,
7 urlParamsObject = {},
8 options = {}
9 ) {
10 try {
11 // Merge default and user options
12 const mergedOptions = {
13 next: { revalidate: 60 },
14 headers: {
15 "Content-Type": "application/json",
16 },
17 ...options,
18 };
19
20 // Build request URL
21 const queryString = qs.stringify(urlParamsObject);
22 const requestUrl = `${getStrapiURL(
23 `/api${path}${queryString ? `?${queryString}` : ""}`
24 )}`;
25
26 // Trigger API call
27 const response = await fetch(requestUrl, mergedOptions);
28 const data = await response.json();
29 return data;
30
31 } catch (error) {
32 console.error(error);
33 throw new Error(`Please check if your server is running and you set all the required tokens.`);
34 }
35 }
The provided code defines a helper function named fetchAPI
that performs an API call using the JavaScript Fetch API.
The code imports the qs
library which provides query string parsing and formatting functionality. It also imports the getStrapiURL
helper function from the api-helpers.ts
module we created previously.
The fetchAPI
functions takes three parameters: path
, urlParamsObject
, and options
. path
is the API endpoint path, urlParamsObject
is an object containing URL parameters, and options
is an object containing additional options for the API call.
The requestUrl
is constructed by combining the Strapi API URL obtained from the getStrapiURL
function with the provided path
and any query string parameters present in the urlParamsObject
. The qs.stringify
function converts the urlParamsObject
into a query string.
The API call is triggered using the fetch
function passing in the requestUrl
and mergedOptions
. What is returned is data
in JSON format.
Add the following code to next.config.js
in the frontend
directory to access both local and remote media sources but still use the built-in Next.js Image Optimization API.
1 // ./frontend/next.config.js
2
3 /** @type {import('next').NextConfig} */
4
5 const nextConfig = {
6 experimental: {
7 appDir: true,
8 },
9 images: {
10 remotePatterns: [
11 {
12 protocol: 'http',
13 hostname: 'localhost',
14 port: '1337',
15 pathname: '/uploads/**',
16 },
17 {
18 protocol: 'https',
19 hostname: 'images.pexels.com',
20 }
21 ],
22 },
23 }
24
25 module.exports = nextConfig
You will create a home page for your blog frontend in this step. In this case, the home page will display a list of all the articles.
Add page.tsx
file
Create a new file named page.tsx
in the src/app/[lang]
directory.
touch src/app/[lang]/page.tsx
Add the following code to page.tsx
:
1 "use client";
2 import { useState, useEffect, useCallback } from "react";
3 import { fetchAPI } from "./utils/fetch-api";
4
5 import Loader from "./components/Loader";
6 import PostList from "./components/PostList";
7 import PageHeader from "./components/PageHeader";
8
9 interface Meta {
10 pagination: {
11 start: number;
12 limit: number;
13 total: number;
14 };
15 }
16
17 export default function Profile() {
18 const [meta, setMeta] = useState<Meta | undefined>();
19 const [data, setData] = useState<any>([]);
20 const [isLoading, setLoading] = useState(true);
21
22 const fetchData = useCallback(async (start: number, limit: number) => {
23 setLoading(true);
24 try {
25 const token = process.env.NEXT_PUBLIC_STRAPI_API_TOKEN;
26 const path = `/articles`;
27 const urlParamsObject = {
28 sort: { createdAt: "desc" },
29 populate: {
30 cover: { fields: ["url"] },
31 category: { populate: "*" },
32 authorsBio: {
33 populate: "*",
34 },
35 },
36 pagination: {
37 start: start,
38 limit: limit,
39 },
40 };
41 const options = { headers: { Authorization: `Bearer ${token}` } };
42 const responseData = await fetchAPI(path, urlParamsObject, options);
43
44 if (start === 0) {
45 setData(responseData.data);
46 } else {
47 setData((prevData: any[] ) => [...prevData, ...responseData.data]);
48 }
49
50 setMeta(responseData.meta);
51 } catch (error) {
52 console.error(error);
53 } finally {
54 setLoading(false);
55 }
56 }, []);
57
58 function loadMorePosts(): void {
59 const nextPosts = meta!.pagination.start + meta!.pagination.limit;
60 fetchData(nextPosts, Number(process.env.NEXT_PUBLIC_PAGE_LIMIT));
61 }
62
63 useEffect(() => {
64 fetchData(0, Number(process.env.NEXT_PUBLIC_PAGE_LIMIT));
65 }, [fetchData]);
66
67 if (isLoading) return <Loader />;
68
69 return (
70 <div>
71 <PageHeader heading="Our Blog" text="Checkout Something Cool" />
72 <PostList data={data}>
73 {meta!.pagination.start + meta!.pagination.limit <
74 meta!.pagination.total && (
75 <div className="flex justify-center">
76 <button
77 type="button"
78 className="px-6 py-3 text-sm rounded-lg hover:underline dark:bg-gray-900 dark:text-gray-400"
79 onClick={loadMorePosts}
80 >
81 Load more posts...
82 </button>
83 </div>
84 )}
85 </PostList>
86 </div>
87 );
88 }
This code sets up a Next.js page that will fetch a list of all the articles from the Strapi API /articles
endpoint and renders them in a neat blog-like format. It includes pagination for loading more posts when the Load more posts
button is clicked.
The fetchData
function uses the fetchAPI
function to make the API request. It retrieves the NEXT_PUBLIC_STRAPI_API_TOKEN
from the environment variables to construct the request path and URL parameters.
Notice that the page.tsx
file imports a Loader
, a PostList
, and a PageHeader
components, but these are yet to be created. Let's create the files.
Create a components
folder in the src/app/[lang]/
folder to store all your components:
mkdir src/app/[lang]/components
Add Loader Component Add a Loader component to provide visual feedback to the user that data is still being fetched from the API.
Create a new file named Loader.tsx
in the components
folder and add the following code to Loader.tsx
1 // ./frontend/src/app/[lang]/components/Loader.tsx
2 export default function Loader() {
3 return (
4 <div className="absolute inset-0 flex items-center justify-center z-50 bg-opacity-40 bg-gray-500">
5 <div role="status">
6 <svg
7 aria-hidden="true"
8 className="inline w-8 h-8 mr-2 text-gray-200 animate-spin dark:text-gray-600 fill-purple-400"
9 viewBox="0 0 100 101"
10 fill="none"
11 xmlns="http://www.w3.org/2000/svg"
12 >
13 <path
14 d="M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z"
15 fill="currentColor"
16 />
17 <path
18 d="M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z"
19 fill="currentFill"
20 />
21 </svg>
22 <span className="sr-only">Loading...</span>
23 </div>
24 </div>
25 )
26 }
Add PostList Component
The PostList
component will render a grid of articles and retrieve the necessary attributes like the title
, description
, slug
, cover
, and author
for each article.
Create a new file named PostList.tsx
in the components
folder and add the following code to PostList.tsx
1 // ./frontend/src/app/[lang]/components/PostList.tsx
2
3 import Image from "next/image";
4 import Link from "next/link";
5 import { getStrapiMedia, formatDate } from "../utils/api-helpers";
6
7 interface Article {
8 id: 4;
9 attributes: {
10 title: string;
11 description: string;
12 slug: string;
13 createdAt: string;
14 updatedAt: string;
15 publishedAt: string;
16 cover: {
17 data: {
18 attributes: {
19 url: string;
20 };
21 };
22 };
23 category: {
24 data: {
25 attributes: {
26 name: string;
27 slug: string;
28 };
29 };
30 };
31 authorsBio: {
32 data: {
33 attributes: {
34 name: string;
35 avatar: {
36 data: {
37 attributes: {
38 url: string;
39 };
40 };
41 };
42 };
43 };
44 };
45 };
46 }
47
48 export default function PostList({
49 data: articles,
50 children,
51 }: {
52 data: Article[];
53 children?: React.ReactNode;
54 }) {
55 return (
56 <section className="container p-6 mx-auto space-y-6 sm:space-y-12">
57 <div className="grid justify-center grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3">
58 {articles.map((article) => {
59 const imageUrl = getStrapiMedia(
60 article.attributes.cover.data?.attributes.url
61 );
62
63 const category = article.attributes.category.data?.attributes;
64 const authorsBio = article.attributes.authorsBio.data?.attributes;
65
66 const avatarUrl = getStrapiMedia(
67 authorsBio?.avatar.data.attributes.url
68 );
69
70 return (
71 <Link
72 href={`${category?.slug}/${article.attributes.slug}`}
73 key={article.id}
74 className="max-w-sm mx-auto group hover:no-underline focus:no-underline dark:bg-gray-900 lg:w-[300px] xl:min-w-[375px] rounded-2xl overflow-hidden shadow-lg"
75 >
76 {imageUrl && (
77 <Image
78 alt="presentation"
79 width="240"
80 height="240"
81 className="object-cover w-full h-44 "
82 src={imageUrl}
83 />
84 )}
85 <div className="p-6 space-y-2 relative">
86 {avatarUrl && (
87 <Image
88 alt="avatar"
89 width="80"
90 height="80"
91 src={avatarUrl}
92 className="rounded-full h-16 w-16 object-cover absolute -top-8 right-4"
93 />
94 )}
95
96 <h3 className="text-2xl font-semibold group-hover:underline group-focus:underline">
97 {article.attributes.title}
98 </h3>
99
100 <div className="flex justify-between items-center">
101 <span className="text-xs dark:text-gray-400">
102 {formatDate(article.attributes.publishedAt)}
103 </span>
104 {authorsBio && (
105 <span className="text-xs dark:text-gray-400">
106 {authorsBio.name}
107 </span>
108 )}
109 </div>
110 <p className="py-4">{article.attributes.description}</p>
111 </div>
112 </Link>
113 );
114 })}
115 </div>
116 {children && children}
117 </section>
118 );
119 }
The PostList
component provides a reusable way to display a list of blog posts with consistent styling and structure.
Add PageHeader Component
The PageHeader
component will add a reusable header to your frontend.
Create a new file named PageHeader.tsx
in the components
folder and add the following code to PageHeader.tsx
.
1 // ./frontend/src/app/[lang]/components/PageHeader.tsx
2
3 import React from "react";
4
5 interface PageHeaderProps {
6 heading: string,
7 text?: string,
8 }
9
10 export default function PageHeader({ heading, text } : PageHeaderProps) {
11 return (
12 <div className="my-16 w-full text-center">
13 { text && <span className="text-violet-400 font-bold">{text}</span> }
14 <h2 className="text-4xl my-4 lg:text-5xl font-bold font-heading">{heading}</h2>
15 </div>
16 );
17 }
Create Layout
Let's create a layout that provides code for the UI. This will be shared between routes.
Create a new file named layout.tsx
in the src/app/[lang]
directory.
touch src/app/[lang]/layout.tsx
Add the following code to layout.tsx
:
1 // ./frontend/src/app/[lang]/layout.tsx
2
3 import type { Metadata } from "next";
4 import "./globals.css";
5 import { getStrapiMedia, getStrapiURL } from "./utils/api-helpers";
6 import { fetchAPI } from "./utils/fetch-api";
7
8 import { i18n } from "../../../i18n-config";
9 import Footer from "./components/Footer";
10 import Navbar from "./components/Navbar";
11
12 const FALLBACK_SEO = {
13 title: "Strapi Starter Next Blog",
14 description: "Strapi Starter Next Blog",
15 }
16
17
18 async function getGlobal(): Promise<any> {
19 const token = process.env.NEXT_PUBLIC_STRAPI_API_TOKEN;
20
21 if (!token) throw new Error("The Strapi API Token environment variable is not set.");
22
23 const path = `/global`;
24 const options = { headers: { Authorization: `Bearer ${token}` } };
25
26 const urlParamsObject = {
27 populate: [
28 "metadata.shareImage",
29 "favicon",
30 "navbar.links",
31 "navbar.navbarLogo.logoImg",
32 "footer.footerLogo.logoImg",
33 "footer.menuLinks",
34 "footer.legalLinks",
35 "footer.socialLinks",
36 "footer.categories",
37 ],
38 };
39
40 const response = await fetchAPI(path, urlParamsObject, options);
41 return response;
42 }
43
44 export async function generateMetadata(): Promise<Metadata> {
45 const meta = await getGlobal();
46
47 if (!meta.data) return FALLBACK_SEO;
48
49 const { metadata, favicon } = meta.data.attributes;
50 const { url } = favicon.data.attributes;
51
52 return {
53 title: metadata.metaTitle,
54 description: metadata.metaDescription,
55 icons: {
56 icon: [new URL(url, getStrapiURL())],
57 },
58 };
59 }
60
61 export default async function RootLayout({
62 children,
63 params,
64 }: {
65 children: React.ReactNode;
66 params: { lang: string };
67 }) {
68 const global = await getGlobal();
69 // TODO: CREATE A CUSTOM ERROR PAGE
70 if (!global.data) return null;
71
72 const { navbar, footer } = global.data.attributes;
73
74 const navbarLogoUrl = getStrapiMedia(
75 navbar.navbarLogo.logoImg.data.attributes.url
76 );
77
78 const footerLogoUrl = getStrapiMedia(
79 footer.footerLogo.logoImg.data.attributes.url
80 );
81
82 return (
83 <html lang={params.lang}>
84 <body>
85 <Navbar
86 links={navbar.links}
87 logoUrl={navbarLogoUrl}
88 logoText={navbar.navbarLogo.logoText}
89 />
90
91 <main className="dark:bg-black dark:text-gray-100 min-h-screen">
92 {children}
93 </main>
94
95 <Footer
96 logoUrl={footerLogoUrl}
97 logoText={footer.footerLogo.logoText}
98 menuLinks={footer.menuLinks}
99 categoryLinks={footer.categories.data}
100 legalLinks={footer.legalLinks}
101 socialLinks={footer.socialLinks}
102 />
103 </body>
104 </html>
105 );
106 }
107
108 export async function generateStaticParams() {
109 return i18n.locales.map((locale) => ({ lang: locale }));
110 }
The layout.tsx
provides a consistent layout structure for the blog frontend. It fetches global data from the Strapi API, retrieves metadata, and renders the necessary components, such as the Navbar
and the Footer
. It also handles internationalization by generating static parameters based on the available locales.
Notice that the code imports a globals.css
file, a Footer
component, and a Navbar
component, but they are yet to be created. In addition, a Logo
component for the blog logo will be needed. This will be used by the Navbar
and Footer
components. Let's create the files.
Add Logo component
Create a new file named Logo.tsx
in the components
folder and add the following code to Logo.tsx
:
1 // ./frontend/src/app/[lang]/components/Logo.tsx
2
3 import React from "react";
4 import Link from "next/link";
5 import Image from "next/image";
6
7 export default function Logo({
8 src,
9 children,
10 }: {
11 src: string | null;
12 children?: React.ReactNode;
13 }) {
14 return (
15 <Link
16 href="/"
17 aria-label="Back to homepage"
18 className="flex items-center p-2"
19 >
20 {src && <Image src={src} alt="logo" width={45} height={45} />}
21 <div className="ml-2">{children}</div>
22 </Link>
23 );
24 }
Add Navbar component
Create a new file named Navbar.tsx
in the components
folder and add the following code to Navbar.tsx
:
1 // ./frontend/src/app/[lang]/components/Navbar.tsx
2
3 "use client";
4 import Logo from "./Logo";
5 import Link from "next/link";
6 import { usePathname } from "next/navigation";
7
8 interface NavLink {
9 id: number;
10 url: string;
11 newTab: boolean;
12 text: string;
13 }
14
15 function NavLink({ url, text }: NavLink) {
16 const path = usePathname();
17
18 return (
19 <li className="flex">
20 <Link
21 href={url}
22 className={`flex items-center mx-4 -mb-1 border-b-2 dark:border-transparent ${
23 path === url && "dark:text-violet-400 dark:border-violet-400"
24 }}`}
25 >
26 {text}
27 </Link>
28 </li>
29 );
30 }
31
32 export default function Navbar({
33 links,
34 logoUrl,
35 logoText,
36 }: {
37 links: Array<NavLink>;
38 logoUrl: string | null;
39 logoText: string | null;
40 }) {
41 return (
42 <div className="p-4 dark:bg-black dark:text-gray-100">
43 <div className="container flex justify-between h-16 mx-auto px-0 sm:px-6">
44 <Logo src={logoUrl}>
45 {logoText && <h2 className="text-2xl font-bold">{logoText}</h2>}
46 </Logo>
47
48 <div className="items-center flex-shrink-0 hidden lg:flex">
49 <ul className="items-stretch hidden space-x-3 lg:flex">
50 {links.map((item: NavLink) => (
51 <NavLink key={item.id} {...item} />
52 ))}
53 </ul>
54 </div>
55
56 <button className="p-4 lg:hidden">
57 <svg
58 xmlns="http://www.w3.org/2000/svg"
59 fill="none"
60 viewBox="0 0 24 24"
61 stroke="currentColor"
62 className="w-6 h-6 dark:text-gray-100"
63 >
64 <path
65 strokeLinecap="round"
66 strokeLinejoin="round"
67 strokeWidth="2"
68 d="M4 6h16M4 12h16M4 18h16"
69 ></path>
70 </svg>
71 </button>
72 </div>
73 </div>
74 );
75 }
Add Footer component
Create a new file named Footer.tsx
in the components
folder and add the following code to Footer.tsx
:
1 "use client";
2 import { usePathname } from "next/navigation";
3 import Link from "next/link";
4 import Logo from "./Logo";
5 import { CgWebsite } from "react-icons/cg";
6 import { FaDiscord } from "react-icons/fa";
7 import { AiFillTwitterCircle, AiFillYoutube } from "react-icons/ai";
8
9 interface FooterLink {
10 id: number;
11 url: string;
12 newTab: boolean;
13 text: string;
14 social?: string;
15 }
16
17 interface CategoryLink {
18 id: string;
19 attributes: {
20 name: string;
21 slug: string;
22 };
23 }
24
25 function FooterLink({ url, text }: FooterLink) {
26 const path = usePathname();
27 return (
28 <li className="flex">
29 <Link
30 href={url}
31 className={`hover:dark:text-violet-400 ${
32 path === url && "dark:text-violet-400 dark:border-violet-400"
33 }}`}
34 >
35 {text}
36 </Link>
37 </li>
38 );
39 }
40
41 function CategoryLink({ attributes }: CategoryLink) {
42 return (
43 <li className="flex">
44 <Link
45 href={`/${attributes.slug}`}
46 className="hover:dark:text-violet-400"
47 >
48 {attributes.name}
49 </Link>
50 </li>
51 );
52 }
53
54 function RenderSocialIcon({ social }: { social: string | undefined }) {
55 switch (social) {
56 case "WEBSITE":
57 return <CgWebsite />;
58 case "TWITTER":
59 return <AiFillTwitterCircle />;
60 case "YOUTUBE":
61 return <AiFillYoutube />;
62 case "DISCORD":
63 return <FaDiscord />;
64 default:
65 return null;
66 }
67 }
68
69 export default function Footer({
70 logoUrl,
71 logoText,
72 menuLinks,
73 categoryLinks,
74 legalLinks,
75 socialLinks,
76 }: {
77 logoUrl: string | null;
78 logoText: string | null;
79 menuLinks: Array<FooterLink>;
80 categoryLinks: Array<CategoryLink>;
81 legalLinks: Array<FooterLink>;
82 socialLinks: Array<FooterLink>;
83 }) {
84
85 return (
86 <footer className="py-6 dark:bg-black dark:text-gray-50">
87 <div className="container px-6 mx-auto space-y-6 divide-y divide-gray-400 md:space-y-12 divide-opacity-50">
88 <div className="grid grid-cols-12">
89 <div className="pb-6 col-span-full md:pb-0 md:col-span-6">
90 <Logo src={logoUrl}>
91 {logoText && <h2 className="text-2xl font-bold">{logoText}</h2>}
92 </Logo>
93 </div>
94
95 <div className="col-span-6 text-center md:text-left md:col-span-3">
96 <p className="pb-1 text-lg font-medium">Categories</p>
97 <ul>
98 {categoryLinks.map((link: CategoryLink) => (
99 <CategoryLink key={link.id} {...link} />
100 ))}
101 </ul>
102 </div>
103
104 <div className="col-span-6 text-center md:text-left md:col-span-3">
105 <p className="pb-1 text-lg font-medium">Menu</p>
106 <ul>
107 {menuLinks.map((link: FooterLink) => (
108 <FooterLink key={link.id} {...link} />
109 ))}
110 </ul>
111 </div>
112 </div>
113 <div className="grid justify-center pt-6 lg:justify-between">
114 <div className="flex">
115 <span className="mr-2">
116 ©{new Date().getFullYear()} All rights reserved
117 </span>
118 <ul className="flex">
119 {legalLinks.map((link: FooterLink) => (
120 <Link
121 href={link.url}
122 className="text-gray-400 hover:text-gray-300 mr-2"
123 key={link.id}
124 >
125 {link.text}
126 </Link>
127 ))}
128 </ul>
129 </div>
130 <div className="flex justify-center pt-4 space-x-4 lg:pt-0 lg:col-end-13">
131 {socialLinks.map((link: FooterLink) => {
132 return (
133 <a
134 key={link.id}
135 rel="noopener noreferrer"
136 href={link.url}
137 title={link.text}
138 target={link.newTab ? "_blank" : "_self"}
139 className="flex items-center justify-center w-10 h-10 rounded-full dark:bg-violet-400 dark:text-gray-900"
140 >
141 <RenderSocialIcon social={link.social} />
142 </a>
143 );
144 })}
145 </div>
146 </div>
147 </div>
148 </footer>
149 );
150 }
Add globals.css
Create a new file called globals.css
in the [lang]
folder and add the following code to globals.css
:
1 /* ./frontend/src/app/[lang]/globals.css */
2
3 @tailwind base;
4 @tailwind components;
5 @tailwind utilities;
6 @import "react-slideshow-image/dist/styles.css";
7
8 body {
9 @apply dark:bg-black
10 }
11
12
13 /*******************************************
14 Rich Text Styles
15 *******************************************/
16
17 /* Headers */
18 .rich-text h1 {
19 @apply text-4xl font-bold mb-4 text-violet-400;
20 }
21
22 .rich-text h2 {
23 @apply text-3xl font-bold mb-4 text-violet-400;
24 }
25
26 .rich-text h3 {
27 @apply text-2xl font-bold mb-4 text-violet-400;
28 }
29
30 .rich-text h4 {
31 @apply text-xl font-bold mb-4 text-violet-400;
32 }
33
34 .rich-text h5 {
35 @apply text-lg font-bold mb-4 text-violet-400;
36 }
37
38 .rich-text h6 {
39 @apply text-base font-bold mb-4 text-violet-200;
40 }
41
42 /* Horizontal rules */
43 .rich-text hr {
44 @apply border-gray-300 my-8;
45 }
46
47 .rich-text a {
48 @apply text-violet-400 underline;
49 }
50
51 /* Typographic replacements */
52 .rich-text p {
53 @apply mb-4;
54 }
55
56 /* Emphasis */
57 .rich-text strong {
58 @apply font-bold;
59 }
60
61 .rich-text em {
62 @apply italic;
63 }
64
65 .rich-text del {
66 @apply line-through;
67 }
68
69 /* Blockquotes */
70 .rich-text blockquote {
71 @apply border-l-4 border-gray-400 pl-4 py-2 mb-4;
72 }
73
74 /* Lists */
75 .rich-text ul {
76 @apply list-disc pl-4 mb-4;
77 }
78
79 .rich-text ol {
80 @apply list-decimal pl-4 mb-4;
81 }
82
83 .rich-text li {
84 @apply mb-2;
85 }
86
87 .rich-text li > ul {
88 @apply list-disc pl-4 mb-2;
89 }
90
91 .rich-text li > ol {
92 @apply list-decimal pl-4 mb-2;
93 }
94
95 /* Code blocks */
96 .rich-text pre {
97 @apply font-mono bg-gray-900 text-gray-100 rounded p-4 my-6;
98 }
99
100 .rich-text code {
101 @apply font-mono bg-gray-900 text-gray-100 rounded px-2 py-1;
102 }
103
104 /* Tables */
105 .rich-text table {
106 @apply w-full border-collapse border-gray-300 my-6;
107 }
108
109 .rich-text th {
110 @apply bg-gray-900 text-left py-2 px-4 font-semibold border-b border-gray-300;
111 }
112
113 .rich-text td {
114 @apply py-2 px-4 border-b border-gray-300;
115 }
116
117 /* Images */
118 .rich-text img {
119 @apply w-full object-cover rounded-xl my-6;
120 }
121
122 /* Custom containers */
123 .rich-text .warning {
124 @apply bg-yellow-100 border-yellow-500 text-yellow-700 px-4 py-2 rounded-lg mb-4;
125 }
126
127
128 /*******************************************
129 React Slideshow Styles
130 *******************************************/
131
132 .react-slideshow-container [aria-label="Previous Slide"] {
133 margin-left: 1rem;
134 }
135
136 .react-slideshow-container [aria-label="Next Slide"] {
137 margin-right: 1rem;
138 }
Test Home Page Make sure your Strapi backend server is running, then start your Next.js frontend development server.
Run the following command in the frontend
directory:
yarn dev
Visit http://localhost:3000
in your browser and you should see your blog’s home page.
Great! The home page is working and is displaying a grid of all posts as expected.
The next step is to create a page for each category.
Create [category]
folder
Create a folder named [category]
inside the [lang]
folder. Since we have multiple categories, we will use Dynamic Segments for handling the routes for each category. Therefore the URL for each category will be based on its name.
mkdir src/app/[lang]/[category]
Add page.tsx
file
Create a file called page.tsx
in the [category]
folder.
touch src/app/[lang]/[category]/page.tsx
Add the following code to page.tsx
:
1 import PageHeader from '@/app/[lang]/components/PageHeader';
2 import { fetchAPI } from '@/app/[lang]/utils/fetch-api';
3 import PostList from '@/app/[lang]/components/PostList';
4
5 async function fetchPostsByCategory(filter: string) {
6 try {
7 const token = process.env.NEXT_PUBLIC_STRAPI_API_TOKEN;
8 const path = `/articles`;
9 const urlParamsObject = {
10 sort: { createdAt: 'desc' },
11 filters: {
12 category: {
13 slug: filter,
14 },
15 },
16 populate: {
17 cover: { fields: ['url'] },
18 category: {
19 populate: '*',
20 },
21 authorsBio: {
22 populate: '*',
23 },
24 },
25 };
26 const options = { headers: { Authorization: `Bearer ${token}` } };
27 const responseData = await fetchAPI(path, urlParamsObject, options);
28 return responseData;
29 } catch (error) {
30 console.error(error);
31 }
32 }
33
34 export default async function CategoryRoute({ params }: { params: { category: string } }) {
35 const filter = params.category;
36 const { data } = await fetchPostsByCategory(filter);
37
38 if (data.length === 0) return <div>Not Posts In this category</div>;
39
40 const { name, description } = data[0]?.attributes.category.data.attributes;
41
42 return (
43 <div>
44 <PageHeader heading={name} text={description} />
45 <PostList data={data} />
46 </div>
47 );
48 }
49
50 export async function generateStaticParams() {
51 return [];
52 }
The provided code fetches and renders posts for a specific category. It exports two asynchronous functions: CategoryRoute
and generateStaticParams
.
The CategoryRoute
function handles rendering content for a specific category. It retrieves the category from the provided parameters, calls the fetchPostsByCategory
function to fetch posts data for that category, and then renders a page header with the category name and description, followed by a list of posts.
The fetchPostsByCategory
function fetches posts by a given category. It constructs an API request with sorting, filtering, and population options, and retrieves the response data.
The generateStaticParams
function is used for generating static paths based on dynamic routes. In this case, it returns an empty array.
Overall, the code retrieves and displays posts data for a specific category, utilizing asynchronous functions for API requests and rendering.
Test Category Page Make sure your Strapi backend server is running, then start your Next.js frontend development server.
Run the following command in the frontend
directory:
yarn dev
Visit http://localhost:3000/strapi
in your browser and you should see the strapi
category page of your blog.
You can test the other categories by clicking on the category
links in the footer of your blog.
The category page should work and display a grid of posts related to the specific category.
The next step is to create a page for each article that displays the full post.
Create [slug]
folder
Create a folder called [slug]
in the [category]
folder. This implies that each article will have a route based on its slug
as defined in the Strapi Admin Panel. The slug
is generated from the post title
.
mkdir src/app/[lang]/[category]/[slug]
Inside the [slug]
folder, create two new files:
page.tsx
for fetching and rendering the article.layout.tsx
for the layout of the Article page. touch src/app/[lang]/[category]/[slug]/page.tsx src/app/[lang]/[category]/[slug]/layout.tsx
Add page.tsx
file
Add the following code to src/app/[lang]/[category]/[slug]/page.tsx
:
1 import { fetchAPI } from '@/app/[lang]/utils/fetch-api';
2 import Post from '@/app/[lang]/components/Post';
3 import type { Metadata } from 'next';
4
5 async function getPostBySlug(slug: string) {
6 const token = process.env.NEXT_PUBLIC_STRAPI_API_TOKEN;
7 const path = `/articles`;
8 const urlParamsObject = {
9 filters: { slug },
10 populate: {
11 cover: { fields: ['url'] },
12 authorsBio: { populate: '*' },
13 category: { fields: ['name'] },
14 blocks: { populate: '*' },
15 },
16 };
17 const options = { headers: { Authorization: `Bearer ${token}` } };
18 const response = await fetchAPI(path, urlParamsObject, options);
19 return response;
20 }
21
22 async function getMetaData(slug: string) {
23 const token = process.env.NEXT_PUBLIC_STRAPI_API_TOKEN;
24 const path = `/articles`;
25 const urlParamsObject = {
26 filters: { slug },
27 populate: { seo: { populate: '*' } },
28 };
29 const options = { headers: { Authorization: `Bearer ${token}` } };
30 const response = await fetchAPI(path, urlParamsObject, options);
31 return response.data;
32 }
33
34 export async function generateMetadata({ params }: { params: { slug: string } }): Promise<Metadata> {
35 const meta = await getMetaData(params.slug);
36 const metadata = meta[0].attributes.seo;
37
38 return {
39 title: metadata.metaTitle,
40 description: metadata.metaDescription,
41 };
42 }
43
44 export default async function PostRoute({ params }: { params: { slug: string } }) {
45 const { slug } = params;
46 const data = await getPostBySlug(slug);
47 if (data.data.length === 0) return <h2>no post found</h2>;
48 return <Post data={data.data[0]} />;
49 }
50
51 export async function generateStaticParams() {
52 const token = process.env.NEXT_PUBLIC_STRAPI_API_TOKEN;
53 const path = `/articles`;
54 const options = { headers: { Authorization: `Bearer ${token}` } };
55 const articleResponse = await fetchAPI(
56 path,
57 {
58 populate: ['category'],
59 },
60 options
61 );
62
63 return articleResponse.data.map(
64 (article: {
65 attributes: {
66 slug: string;
67 category: {
68 slug: string;
69 };
70 };
71 }) => ({ slug: article.attributes.slug, category: article.attributes.slug })
72 );
73 }
The page.tsx
file for individual posts displays an article by fetching post data using the fetchAPI
helper function and uses the Post
component to render the page.
page.tsx
includes the following functions:
getPostBySlug
: Fetches post data based on a given slug, including cover
, authorsBio
, and category
.getMetaData
: Fetches metadata for a post based on a given slug.generateMetadata
: Generates metadata for a post using the getMetadata
function and returns the title
and description
of a post.PostRoute
: Renders the post page based on a given slug
. The function retrieves post data using the getPostBySlug
function and renders the post using the Post
component.generateStaticParams
: Generates static parameters for articles by fetching the articles' data and mapping it to an array with the slug
and category
attributes as strings.Add Post
component
page.tsx
imports a Post
component for rendering posts. Create a Post.tsx
file in the components
folder.
touch src/app/[lang]/components/Post.tsx
Add the following code to Post.tsx
:
1 import { formatDate, getStrapiMedia } from '@/app/[lang]/utils/api-helpers';
2 import { postRenderer } from '@/app/[lang]/utils/post-renderer';
3 import Image from 'next/image';
4
5 interface Article {
6 id: number;
7 attributes: {
8 title: string;
9 description: string;
10 slug: string;
11 cover: {
12 data: {
13 attributes: {
14 url: string;
15 };
16 };
17 };
18 authorsBio: {
19 data: {
20 attributes: {
21 name: string;
22 avatar: {
23 data: {
24 attributes: {
25 url: string;
26 };
27 };
28 };
29 };
30 };
31 };
32 blocks: any[];
33 publishedAt: string;
34 };
35 }
36
37 export default function Post({ data }: { data: Article }) {
38 const { title, description, publishedAt, cover, authorsBio } = data.attributes;
39 const author = authorsBio.data?.attributes;
40 const imageUrl = getStrapiMedia(cover.data?.attributes.url);
41 const authorImgUrl = getStrapiMedia(authorsBio.data?.attributes.avatar.data.attributes.url);
42
43 return (
44 <article className="space-y-8 dark:bg-black dark:text-gray-50">
45 {imageUrl && (
46 <Image
47 src={imageUrl}
48 alt="article cover image"
49 width={400}
50 height={400}
51 className="w-full h-96 object-cover rounded-lg"
52 />
53 )}
54 <div className="space-y-6">
55 <h1 className="leading-tight text-5xl font-bold ">{title}</h1>
56 <div className="flex flex-col items-start justify-between w-full md:flex-row md:items-center dark:text-gray-400">
57 <div className="flex items-center md:space-x-2">
58 {authorImgUrl && (
59 <Image
60 src={authorImgUrl}
61 alt="article cover image"
62 width={400}
63 height={400}
64 className="w-14 h-14 border rounded-full dark:bg-gray-500 dark:border-gray-700"
65 />
66 )}
67 <p className="text-md dark:text-violet-400">
68 {author && author.name} • {formatDate(publishedAt)}
69 </p>
70 </div>
71 </div>
72 </div>
73
74 <div className="dark:text-gray-100">
75 <p>{description}</p>
76
77 {data.attributes.blocks.map((section: any, index: number) => postRenderer(section, index))}
78 </div>
79 </article>
80 );
81 }
The Post
component renders details of an article. It expects a data
prop with specific attributes, which include a title
, description
, slug
, cover
, authorsBio
, blocks
, and publishedAt
. It renders an article based on these attributes.
It maps over the data.attributes.blocks
array and uses a postFenderer
utility function to render each article section.
Create postRenderer
utility
Let's create the postRenderer
utility function to be used by the Post
component. Create a new file named post-renderer.tsx
inside the utils
folder.
touch src/app/[lang]/utils/post-renderer.tsx
Add the following code to post-renderer.tsx
:
1 import RichText from "../components/RichText";
2 import ImageSlider from "../components/ImageSlider";
3 import Quote from "../components/Quote";
4 import Media from "../components/Media";
5 import VideoEmbed from "../components/VideoEmbed";
6
7 export function postRenderer(section: any, index: number) {
8 switch (section.__component) {
9 case "shared.rich-text":
10 return <RichText key={index} data={section} />;
11 case "shared.slider":
12 return <ImageSlider key={index} data={section} />;
13 case "shared.quote":
14 return <Quote key={index} data={section} />;
15 case "shared.media":
16 return <Media key={index} data={section} />;
17 case "shared.video-embed":
18 return <VideoEmbed key={index} data={section} />;
19 default:
20 return null;
21 }
22 }
The postRenderer
utility function is used to dynamically render different types of sections within a post based on the __component
value of each section. This could be a RichText
, ImageSlider
, Quote
, Media
, or VideoEmbed
component.
Next, we will create the respective components required by the postRenderer
utility.
Create the RichText
, ImageSlider
, Quote
, Media
, and VideoEmbed
components:
touch src/app/[lang]/components/{RichText,ImageSlider,Quote,Media,VideoEmbed}.tsx
Add RichText
Component
Add the following code to RichText.tsx
:
1 import Markdown from "react-markdown";
2 import remarkGfm from "remark-gfm";
3
4 interface RichTextProps {
5 data: {
6 body: string;
7 };
8 }
9
10 export default function RichText({ data }: RichTextProps) {
11 return (
12 <section className="rich-text py-6 dark:bg-black dark:text-gray-50 ">
13 <Markdown children={data.body} remarkPlugins={[remarkGfm]} />
14 </section>
15 );
16 }
The RichText
component converts markdown-formatted text into HTML and renders it as a section of rich text content. It relies on the Markdown
component from the react-markdown
library and the remark-gfm
plugin for rendering Markdown syntax with additional features like tables.
Add ImageSlider
component
Add the following code to ImageSlider.tsx
:
1 "use client";
2 import { Fade } from "react-slideshow-image";
3 import { getStrapiMedia } from "../utils/api-helpers";
4 import Image from "next/image";
5
6 interface Image {
7 id: number;
8 attributes: {
9 alternativeText: string | null;
10 caption: string | null;
11 url: string;
12 };
13 }
14
15 interface SlidShowProps {
16 files: {
17 data: Image[];
18 };
19 }
20
21 export default function Slideshow({ data }: { data: SlidShowProps }) {
22 return (
23 <div className="slide-container">
24 <Fade>
25 {data.files.data.map((fadeImage: Image, index) => {
26 const imageUrl = getStrapiMedia(fadeImage.attributes.url);
27 return (
28 <div key={index}>
29 {imageUrl && <Image className="w-full h-96 object-cover rounded-lg" height={400} width={600} alt="alt text" src={imageUrl} />}
30 </div>
31 );
32 })}
33 </Fade>
34 </div>
35 );
36 }
The Slideshow
component creates an image slider by rendering a series of images based on the provided data. The Fade
component from the react-slideshow-image
library provides the sliding effect, and the Image
component from Next.js handles the rendering of each image.
Add Quote
component
Add the following code to Quote.tsx
:
1 interface QuoteProps {
2 data: {
3 title: string;
4 body: string;
5 author: string;
6 };
7 }
8
9 export default function Quote({ data }: QuoteProps) {
10 const { title, body, author } = data;
11
12 return (
13 <div className="flex flex-col items-center mx-12 lg:mx-0 py-44">
14 {title && <h2 className="my-4">{title}</h2>}
15 <div className="relative text-center">
16 <svg
17 xmlns="http://www.w3.org/2000/svg"
18 viewBox="0 0 512 512"
19 fill="currentColor"
20 className="absolute top-0 -left-4 w-4 h-4 dark:text-gray-700"
21 >
22 <path d="M232,246.857V16H16V416H54.4ZM48,48H200V233.143L48,377.905Z"></path>
23 <path d="M280,416h38.4L496,246.857V16H280ZM312,48H464V233.143L312,377.905Z"></path>
24 </svg>
25 <p className="px-6 py-1 text-lg italic">{body}</p>
26 <svg
27 xmlns="http://www.w3.org/2000/svg"
28 viewBox="0 0 512 512"
29 fill="currentColor"
30 className="absolute bottom-0 -right-4 w-4 h-4 dark:text-gray-700"
31 >
32 <path d="M280,185.143V416H496V16H457.6ZM464,384H312V198.857L464,54.1Z"></path>
33 <path d="M232,16H193.6L16,185.143V416H232ZM200,384H48V198.857L200,54.1Z"></path>
34 </svg>
35 </div>
36 <span className="w-12 h-1 my-2 rounded-lg dark:bg-violet-400"></span>
37 {author ? <p>{author}</p> : "unknown"}
38 </div>
39 );
40 }
The Quote
component renders a blockquote with a title
, body
, and an optional author
. The quote symbols are displayed using SVG icons, and appropriate styling classes are applied for visual presentation.
Add Media
component
Add the following code to Media.tsx
:
1 import { getStrapiMedia } from "../utils/api-helpers";
2 import Image from "next/image";
3
4 interface MediaProps {
5 file: {
6 data: {
7 id: string;
8 attributes: {
9 url: string;
10 name: string;
11 alternativeText: string;
12 };
13 };
14 };
15 }
16
17 export default function Media({ data }: { data: MediaProps }) {
18 const imgUrl = getStrapiMedia(data.file.data.attributes.url);
19 return (
20 <div className="flex items-center justify-center mt-8 lg:mt-0 h-72 sm:h-80 lg:h-96 xl:h-112 2xl:h-128">
21 <Image
22 src={imgUrl || ""}
23 alt={data.file.data.attributes.alternativeText || "none provided"}
24 className="object-cover w-full h-full rounded-lg overflow-hidden"
25 width={400}
26 height={400}
27 />
28 </div>
29 );
30 }
The Media
component renders an image or media file using the Next.js Image
component. The image is displayed with rounded corners and is set to a specific width and height. The getStrapiMedia
function is used to retrieve the media URL.
Add VideoEmbed
component
Add the following code to VideoEmbed.tsx
:
1 import React from "react";
2
3 interface VideoEmbedProps {
4 id: number;
5 url: string;
6 width?: string;
7 height?: string;
8 }
9
10 const getEmbedUrl = (videoUrl: string): string | null => {
11 const youtubeRegex =
12 /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|watch\?v%3D)([\w-]{11}).*/;
13 const youtubeMatch = videoUrl.match(youtubeRegex);
14
15 if (youtubeMatch && youtubeMatch[2].length === 11) {
16 return `https://www.youtube.com/embed/${youtubeMatch[2]}`;
17 }
18
19 // Add support for other video platforms here
20
21 return null;
22 };
23
24 export default function VideoEmbed({ data }: { data: VideoEmbedProps }) {
25 const embedUrl = getEmbedUrl(data.url);
26
27 if (!embedUrl) return <div>Invalid video URL</div>;
28
29 return (
30 <div className="video-embed relative pb-56.25 h-72 lg:h-[450px] overflow-hidden my-8">
31 <iframe
32 title="video"
33 src={embedUrl || ""}
34 width={data.width || "100%"}
35 height={data.height || "100%"}
36 allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
37 allowFullScreen
38 className="absolute top-0 left-0 w-full h-full"
39 />
40 </div>
41 );
42 }
The VideoEmbed
component renders an embedded video based on the provided URL. It supports YouTube videos by extracting the video ID and creating an embed URL. If the URL is invalid, it displays an error message. The embedded video is displayed within a container with specified dimensions, and the iframe allows for various video playback features.
Add Layout
Add the following code to src/app/[lang]/[category]/[slug]/layout.tsx
:
1 import React from "react";
2
3 import ArticleSelect from "@/app/[lang]/components/ArticleSelect";
4 import { fetchAPI } from "@/app/[lang]/utils/fetch-api";
5
6 async function fetchSideMenuData(filter: string) {
7 try {
8 const token = process.env.NEXT_PUBLIC_STRAPI_API_TOKEN;
9 const options = { headers: { Authorization: `Bearer ${token}` } };
10
11 const categoriesResponse = await fetchAPI(
12 "/categories",
13 { populate: "*" },
14 options
15 );
16
17 const articlesResponse = await fetchAPI(
18 "/articles",
19 filter
20 ? {
21 filters: {
22 category: {
23 name: filter,
24 },
25 },
26 }
27 : {},
28 options
29 );
30
31 return {
32 articles: articlesResponse.data,
33 categories: categoriesResponse.data,
34 };
35 } catch (error) {
36 console.error(error);
37 }
38 }
39
40 interface Category {
41 id: number;
42 attributes: {
43 name: string;
44 slug: string;
45 articles: {
46 data: Array<{}>;
47 };
48 };
49 }
50
51 interface Article {
52 id: number;
53 attributes: {
54 title: string;
55 slug: string;
56 };
57 }
58
59 interface Data {
60 articles: Article[];
61 categories: Category[];
62 }
63
64 export default async function LayoutRoute({
65 params,
66 children,
67 }: {
68 children: React.ReactNode;
69 params: {
70 slug: string;
71 category: string;
72 };
73 }) {
74 const { category } = params;
75 const { categories, articles } = (await fetchSideMenuData(category)) as Data;
76
77 return (
78 <section className="container p-8 mx-auto space-y-6 sm:space-y-12">
79 <div className="grid grid-cols-1 md:grid-cols-3 gap-2 lg:gap-4">
80 <div className="col-span-2">{children}</div>
81 <aside>
82 <ArticleSelect
83 categories={categories}
84 articles={articles}
85 params={params}
86 />
87 </aside>
88 </div>
89 </section>
90 );
91 }
92
93 export async function generateStaticParams() {
94 const token = process.env.NEXT_PUBLIC_STRAPI_API_TOKEN;
95 const path = `/articles`;
96 const options = { headers: { Authorization: `Bearer ${token}` } };
97 const articleResponse = await fetchAPI(
98 path,
99 {
100 populate: ["category"],
101 },
102 options
103 );
104
105 return articleResponse.data.map(
106 (article: {
107 attributes: {
108 slug: string;
109 category: {
110 slug: string;
111 };
112 };
113 }) => ({ slug: article.attributes.slug, category: article.attributes.slug })
114 );
115 }
layout.tsx
serves as a wrapper for the content rendered on the article page by its child components. It has the following functions:
fetchSideMenuData
: Fetches data (articles
and categories
) for the side menu using the fetchAPI
.LayoutRoute
: Makes use of the fetchSideMenuData
function to fetch the necessary data based on the category
received from the params
. It then renders the content within a section container with padding and spacing. The layout is divided into two columns using CSS grid: the first column contains the children
components, and the second column contains the ArticleSelect
component, which receives the fetched categories
, articles
, and params
as props.generateStaticParams
: Retrieves article data from the backend, including the article's slug
and its associated category
. It returns an array of objects containing the slug
and category
for each article.Add ArticleSelect
component
Create a file named ArticleSelect.tsx
inside the components
folder:
touch src/app/[lang]/components/ArticleSelect.tsx
Add the following code to ArticleSelect.tsx
:
1 import React from "react";
2 import Link from "next/link";
3
4 interface Category {
5 id: number;
6 attributes: {
7 name: string;
8 slug: string;
9 articles: {
10 data: Array<{}>;
11 };
12 };
13 }
14
15 interface Article {
16 id: number;
17 attributes: {
18 title: string;
19 slug: string;
20 };
21 }
22
23 function selectedFilter(current: string, selected: string) {
24 return current === selected
25 ? "px-3 py-1 rounded-lg hover:underline dark:bg-violet-700 dark:text-gray-100"
26 : "px-3 py-1 rounded-lg hover:underline dark:bg-violet-400 dark:text-gray-900";
27 }
28
29 export default function ArticleSelect({
30 categories,
31 articles,
32 params,
33 }: {
34 categories: Category[];
35 articles: Article[];
36 params: {
37 slug: string;
38 category: string;
39 };
40 }) {
41
42 return (
43 <div className="p-4 rounded-lg dark:bg-gray-900 min-h-[365px] relative">
44 <h4 className="text-xl font-semibold">Browse By Category</h4>
45
46 <div>
47 <div className="flex flex-wrap py-6 space-x-2 dark:border-gray-400">
48 {categories.map((category: Category) => {
49 if (category.attributes.articles.data.length === 0) return null;
50 return (
51 <Link
52 href={`/${category.attributes.slug}`}
53 className={selectedFilter(
54 category.attributes.slug,
55 params.category
56 )}
57 >
58 #{category.attributes.name}
59 </Link>
60 );
61 })}
62 <Link href={"/"} className={selectedFilter("", "filter")}>
63 #all
64 </Link>
65 </div>
66
67 <div className="space-y-2">
68 <h4 className="text-lg font-semibold">Other Posts You May Like</h4>
69 <ul className="ml-4 space-y-1 list-disc">
70 {articles.map((article: Article) => {
71 return (
72 <li>
73 <Link
74 rel="noopener noreferrer"
75 href={`/${params.category}/${article.attributes.slug}`}
76 className={`${
77 params.slug === article.attributes.slug &&
78 "text-violet-400"
79 } hover:underline hover:text-violet-400 transition-colors duration-200`}
80 >
81 {article.attributes.title}
82 </Link>
83 </li>
84 );
85 })}
86 </ul>
87 </div>
88 </div>
89 </div>
90 );
91 }
This component is responsible for rendering a side menu that allows users to browse articles by category and displays a list of related articles. It displays category links and a list of related articles.
There is a helper function called selectedFilter
that determines the CSS class based on the currently selected category
.
A side menu section is rendered with "Browse By Category". It then iterates over the categories
array and renders links for each category
. If a category
has no associated articles, it will be skipped. The link's appearance is determined by the selectedFilter
function.
At the end of the side menu, there is a section titled "Other Posts You May Like". It renders a list of related articles based on the articles
array. Each article is rendered as a list item with a link to the corresponding article's URL.
Test Article Page Make sure your Strapi backend server is running, then start your Next.js frontend development server.
Run the following command in the frontend
directory:
yarn dev
Visit http://localhost:3000
in your browser and you should see the blog home page. Click on any one of the articles and you should see a full article.
In conclusion, this article provided a comprehensive guide on building a blog website using Strapi for the backend and Next.js for the frontend. The tutorial covered various steps, including setting up the project folder, creating a Strapi app, seeding the data, setting up the Next.js app, configuring the Strapi API token, setting up middleware, fetching data from Strapi, creating the home page for the blog, creating category pages and creating a single article page.
By following the step-by-step instructions and code examples, you learned how to leverage the power of Strapi and Next.js to create a fully functional blog website. They learned how to fetch data from the Strapi API, display articles in a neat blog-like format, implement pagination, and handle internationalization.
Overall, this tutorial gave developers the necessary knowledge and resources to build their blog website using Next.js and Strapi. By combining the flexibility of Strapi's with the powerful frontend capabilities of Next.js, you can create dynamic and customizable blogs tailored to their specific needs.
Please note: Since we initially published this blog, we released new versions of Strapi, and tutorials may be outdated. Sorry for the inconvenience if it's the case, and please help us by reporting it here.
Get started with Strapi by trying our live demo. Also, consult our forum if you have any questions. We will be there to help you.
The Strapi experience has always been about flexibility, customization, and open-source innovation. But we understand that managing infrastructure and scaling your application can sometimes be a daunting task, diverting your focus from what you do best: developing web experiences.
That's why we're excited to introduce Strapi Cloud, so you can leverage the same robust Strapi capabilities you love, but without the hassle of managing servers, worrying about uptime, or scaling infrastructure as your project grows. It will allow you to future-proof your apps with a CMS that meets the content management needs of all your stakeholders, no matter your use case, services or devices.
Strapi remains committed to open-source values, and self-hosting will always be a viable option. We believe in offering choices that align with your project's unique needs. Strapi Cloud is an additional resource for those who want to focus solely on development, leaving the infrastructure to us.
Aw are here to support you every step of the way, no matter which hosting option you choose. You can reach out to us and the community on our Discord if you have any questions!
Mark Munyaka is a freelance web developer and writer who loves problem-solving and testing out web technologies. You can follow him on Twitter @McMunyaka