This guide will teach you the importance of previews in Jamstack. I will also walk you through the process of adding the previews mode to a blog built with Next.js and Strapi headless CMS for a better content editing experience.
One of the major features of the Jamstack web development architecture is its core principle of pre-rendering, i.e., generating the website's content during build time instead of every request time. Pre-rendering improves the speed, reduces the complexity, and reduces the cost of hosting the website.
The pre-rendering process in the Jamstack web development methodology is achieved with the help of a static site generator(SSG). An SSG collects content from a headless CMS, where the files are created and stored with the help of an API.
The contents are then converted into static files (prebuilt HTML, CSS, and Javascript files) by the SSG during the SSG build time. Finally, the generated static files can be deployed to a production server or stored in a content delivery network(CDN) and served as a whole to the end-user in every request.
Even though it is very beneficial, this pre-rendering process tends not to be ideal during content creation. Content creators and editors must render a draft preview at every request instead of waiting for the complete website build process before viewing their changes.
The easiest solution to the problem conferred by most static site generators is setting up a Preview Mode that will bypass the static site generator pre-rendering process. With the preview mode activated, content editors can view their changes on every page request instead of waiting for the complete build process to run.
For the sake of this tutorial, we will create a simple blog website for which we will later activate the previews mode to allow for a better editing experience.
To follow through with the guide, you will need a basic knowledge of the following:
This tutorial assumes you have the following system configuration:
The first step in this guide will be creating our blog's backend. We will use the strapi blog template as a starter for faster and easier development.
npx create-strapi-app backend --quickstart --template @strapi/template-blog@1.0.0 blog
This command will create a new backend folder with the Strapi backend fully set up and all dependencies installed during installation.
After the successful installation, you will automatically be redirected to your browser, where you will be prompted to register before using Strapi. If not redirected, visit http://localhost:1337/admin in your browser.
Add your details and click LET’S START to access the Strapi dashboard. Navigate to the Content Manager. Select Article under COLLECTION TYPES, and you will see a list of articles.
The blog template for Strapi comes with some preconfigured schema for blogging apps, making our development easier and faster.
Set the STATE
of the articles in COLLECTION TYPES to either Published
or Draft
. First, click on the pen symbol next to Published.
Click Unpublish. Choose Yes, confirm in the Confirmation dialog box, then Save to change the state of the article.
Repeat the procedure for the articles you want to make drafts, and your list of articles should be similar to this:
The next step in this guide will be the frontend setup with Next.js. First, initialize your front-end project with this command.
npx create-next-app frontend
A frontend folder is created in your root directory. Navigate into the folder and run npm run dev
to start the frontend server. You can view your front end locally using http://localhost:3000.
Stop your front-end server by pressing Ctrl
plus C
on your keyboard. Install Tailwind CSS into your front end with npm.
npm install -D tailwindcss@latest postcss@latest autoprefixer@latest
Then, generate tailwind CSS configuration files.
npx tailwindcss init -p
This command will generate a postcss.config.js
and a tailwind.config.js
file to the root directory of your project. We will use these two files for any configuration of tailwind CSS in our project.
Navigate to the pages/_app.js
file and replace import '../styles/globals.css'
with import 'tailwindcss/tailwind.css'
. You can delete the styles
folder since we will not use any custom CSS for our blog.
Next, add the paths to all your template files in your tailwind.config.js
file.
1 /* ./tailwind.config.js */
2 /** @type {import('tailwindcss').Config} */
3 module.exports = {
4 content: [
5 "./pages/**/*.{js,ts,jsx,tsx}",
6 "./components/**/*.{js,ts,jsx,tsx}",
7 ],
8 theme: {
9 extend: {},
10 },
11 plugins: [],
12 }
Complete your Tailwind CSS setup by adding the @tailwind
directives for each of Tailwind’s layers to your ./styles/globals.css
file.
1 /* ./styles/globals.css */
2 @tailwind base;
3 @tailwind components;
4 @tailwind utilities;
For more information on installing Tailwind CSS, refer to the Install Tailwind CSS with Next.js guide.
Install the markdown-to-jsx package into your front using the following command:
npm install markdown-to-jsx
The markdown-to-jsx npm package will convert the markdown files obtained from Strapi into JSX files to be rendered in our frontend framework.
To connect our Next.js frontend app to our backend, we will create a helper function to make API calls to the Strapi backend with the fetch API.
To create the helper function, create a lib
folder in your frontend root folder, and add a file named api.js
to the lib
folder.
Add the following code lines to the api.js file:
1 /* ./lib/api.js */
2 export function getStrapiURL(path = "") {
3 return `${process.env.NEXT_PUBLIC_STRAPI_API_URL || "http://localhost:1337/api"
4 }${path}`;
5 }
6
7 // Helper to make GET requests to Strapi
8 export async function fetchAPI(path) {
9 const requestUrl = getStrapiURL(path);
10 const response = await fetch(requestUrl);
11 const data = await response.json();
12 return data;
13 }
This code sends a GET
request to Strapi URL with the fetch API. Since we are only building a blog, a helper to fetch the content using GET
requests is enough for our project.
Now that we have our front and backend connected and Tailwind CSS fully installed, the next step will be creating a layout for our blog.
Firstly, create a components
folder in the root folder and add a layout.js
file into the folder. Next, add the following code to the ./components/layout.js
file:
1 /* ./components/layout.js */
2 import Header from './header';
3 import Footer from './footer';
4
5 const Layout = ({ children }) => (
6 <>
7 <Header />
8 {children}
9 <Footer />
10 </>
11 );
12
13 export default Layout;
Then, we will create our header and footer files. First, add a header.js
and a footer.js
file to the components
folder.
Add the following code to your ./components/header.js
file:
1 /* ./components/header.js */
2 import React from "react";
3 import Link from "next/link";
4
5 const Header = () => {
6 return (
7 <div>
8 <nav className="flex justify-center items-center h-16 py-2 mb-2 bg-gray-100 w-full border-b">
9 <div>
10 <Link href="/">
11 <a href="/" className="px-2 font-black lg:px-0 text-lg">
12 Sybox Digital Blog
13 </a>
14 </Link>
15 </div>
16 </nav>
17 </div>
18 );
19 };
20
21 export default Header;
Then, add the following code to the ./components/footer.js
file.
1 /* ./components/footer.js */
2 import React from "react";
3
4 const Footer = () => {
5 return (
6 <footer className="border-t mt-10 pt-12 pb-32 px-4 lg:px-0">
7 <div className="px-4 pt-3 pb-4 border-b -mx-4 border-gray-100">
8 <div className="max-w-xl mx-auto">
9 <h2 className="text-xl text-left inline-block font-semibold text-gray-800">Subscribe to Our Newsletter</h2>
10 <div className="text-gray-700 text-xs pl-px">
11 Latest news, articles and monthly updates delivered to your inbox.
12 </div>
13 <form action="#" className="mt-2">
14 <div className="flex items-center">
15 <input type="email" className="w-full py-4 mr-2 bg-gray-100 shadow-inner rounded-md border border-gray-400 focus:outline-none" required />
16 <button className="bg-blue-600 text-gray-200 text-sm rounded">Sign Up</button>
17 </div>
18 </form>
19 </div>
20 </div>
21 </footer>
22 );
23 };
24
25 export default Footer;
The layout component will be wrapped around our page code to give our blog a uniform header and footer.
Move to your ./pages/index.js
file and discard the pre-existing code there. Then add the following lines of code to the ./pages/index.js
file:
1 /* ./pages/index.js */
2 import Link from "next/link";
3 import Layout from "../components/layout";
4 import { fetchAPI } from "../lib/api";
5
6 export default function Home({ articles }) {
7 return (
8 <>
9 <Layout>
10 <body className="antialiased md:bg-gray-100">
11 <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
12 {articles.data.map((article) => (
13 <div key={article.id} className="md:p-8 p-2 bg-white">
14 <div>
15 {article.attributes.image && (
16 <img src={`http://localhost:1337${article.attributes.image.data.attributes.url}`} />
17 )}
18 </div>
19 {article.attributes.title}
20 <div>
21 {article.attributes.category && (
22 <div className="text-indigo-500 font-semibold text-base mt-2">
23 {article.attributes.category.data.attributes.name}
24 </div>
25 )}
26 </div>
27 <h1 className="font-semibold text-gray-900 leading-none text-xl mt-1 capitalize truncate">
28 {article.attributes.title}
29 </h1>
30 <Link href={`/article/${article.attributes.slug}`}>
31 <div className="max-w-full">
32 <div className="text-base font-medium tracking-wide text-gray-600 mt-1">
33 {article.attributes.description}
34 </div>
35 </div>
36 </Link>
37 <div className="flex items-center space-x-2 mt-20">
38 <div>
39 {article.attributes.author && (
40 <div className="text-gray-900 font-semibold pb-2">
41 {article.attributes.author.data.attributes.name}
42 </div>
43 )}
44 <div className="text-gray-500 font-semibold text-sm">
45 Created on - {new Date(article.attributes.createdAt).toDateString()}
46 </div>
47 <div className="text-gray-500 font-semibold text-sm">
48 Updated on - {new Date(article.attributes.updatedAt).toDateString()}
49 </div>
50 </div>
51 </div>
52 </div>
53 ))}
54 </div>
55 </body>
56 </Layout>
57 </>
58 );
59 }
60 export async function getStaticProps() {
61 try {
62 const articles = await fetchAPI("/articles?populate=*");;
63 return {
64 props: {
65 articles
66 },
67 };
68 } catch (error) {
69 return { error };
70 }
71 }
In this code, we exported articles with the published status from the Strapi backend with getStaticProps()
. The getStaticProps()
is a Next.js API that will pre-render our page at build time using the props returned in it.
We then pass the props(articles)
returned by getStaticProps()
into the <Home />
component. The props are then rendered in a UI built with Tailwind CSS. We will also wrap the page in the <Layout />
component to access our pre-made header and footer components.
Start your frontend server:
npm run dev`
The homepage on http://localhost:3000 should be similar to this:
In this step, we will design a dynamic route to render each blog post page based on their slug. Thus, the URL of each page will be dependent on the slug of the page.
Stop your server if you haven’t already. Create an article
folder in the pages
folder, and add a [slug].js
file to the ./pages/article
folder.
Add the following lines of code to the ./pages/article/[slug].js
file:
1 /* ./pages/article/[slug].js */
2 import Markdown from "markdown-to-jsx";
3 import { fetchAPI } from "../../lib/api";
4 import Layout from "../../components/layout";
5 const Article = ({ article }) => {
6 return (
7 <>
8 <Layout>
9 <div className="mt-10">
10 <div className="mb-4 md:mb-0 w-full max-w-screen-md mx-auto">
11 <div className="absolute left-0 bottom-0 w-full h-full" />
12 <div>
13 {article.data[0].attributes.image && (
14 <img src={`http://localhost:1337${article.data[0].attributes.image.data.attributes.url}`} />
15 )}
16 </div>
17 <div>
18 {article.data[0].attributes.category && (
19 <a
20 href="#"
21 className="px-4 py-1 bg-black text-blue-200 inline-flex text-md items-center justify-center mb-2"
22 >
23 {article.data[0].attributes.category.data.attributes.name}
24 </a>
25 )}
26 </div>
27 <h2 className="text-4xl pt-2 font-semibold text-gray-500 leading-tigh`t">
28 {article.data[0].attributes.description}
29 </h2>
30 <div className="mt-3">
31 {article.data[0].attributes.author && (
32 <p className="text-blue-900 font-semibold pb-2">
33 Written by - {article.data[0].attributes.author.data.attributes.name}
34 </p>
35 )}
36 </div>
37 </div>
38 <article className="prose lg:prose-xl px-4 lg:px-0 mt-12 text-gray-700 max-w-screen-md mx-auto text-lg leading-relaxed">
39 <Markdown>{article.data[0].attributes.content}</Markdown>
40 </article>
41 </div>
42 </Layout>
43 </>
44 );
45 };
46 export default Article;
47 export async function getStaticPaths() {
48 const articles = await fetchAPI("/articles?populate=*");
49 return {
50 paths: articles.data.map((article) => ({
51 params: {
52 slug: article.attributes.slug,
53 },
54 })),
55 fallback: false,
56 };
57 }
58 export async function getStaticProps({ params }) {
59 const article = await fetchAPI(`/articles/?filters\[slug\][$eq]=${params.slug}&populate=*`);
60 return {
61 props: { article },
62 revalidate: 1,
63 };
64 }
This gets a single article with its slug and displays the article. So, first, we query our backend for every article with the getStaticPaths()
API. Then, we get the slug and store them in the slug params
.
The slug params
are then passed into the getStaticProps()
API. The getStaticProps()
function queries the backend with a single slug and returns the data collected from the backend as props. The props data are then passed into the < Article />
component and rendered with our UI created with tailwind CSS.
Start your frontend server:
npm run dev
Visit one of the published articles by entering Sample Published Articles in your browser. Replace ${slug}
with a slug to one of the posts, for example, http://localhost:3000/article/what-s-inside-a-black-hole.
Each blog post should appear similar to this:
Now that our blog is wholly designed, we can configure the preview API for a more effortless content editing experience on our platform.
The first step will be to create a preview secret. Then, we will use this secret to access the preview mode securely in our browser. Create an .env file in the root of your frontend folder and add your preview secret to the file.
1PREVIEW_SECRET=****
Replace ** with a unique string of characters.
Next, we will add a helper function to our ./lib/api.js
file. We will use this helper to query our backend for preview data.
1 /* ./lib/api.js
2 *
3 * Add this code below the last line of code
4 */
5
6 export async function getPageData(slug, preview = false) {
7 // Find the pages that match this slug
8 const pagesData = await fetchAPI(
9 `/articles?publicationState=preview&filters\[slug\][$eq]=${slug}&populate=*`
10 );
11 // Make sure we found something, otherwise return null
12 if (pagesData == null || pagesData.length === 0) {
13 return null;
14 }
15 // Return the first item since there should only be one result per slug
16 return pagesData;
17 }
The code queries the Strapi for the requested slug and returns either published or draft blog posts.
The next step will be to create and configure the preview API route. In ./pages/api
, add a new file called preview.js
. Then, add the following code to the file:
1 /* ./pages/api/preview.js */
2
3 import { getPageData } from "../../lib/api"
4
5 export default async function handler(req, res) {
6 if (req.query.secret !== (process.env.PREVIEW_SECRET || 'secret-token')) {
7 return res.status(401).json({ message: "Invalid token" });
8 }
9
10 const pageData = await getPageData(req.query.slug, true);
11
12 if (!pageData) {
13 return res.status(401).json({ message: "Invalid slug" });
14 }
15
16 res.setPreviewData({});
17
18 res.writeHead(307, { Location: `/article/${req.query.slug}` });
19 res.end();
20 };
This code matches the secret in the preview URL to the preview secret in the .env
file. After verifying the preview request, the API then activates the preview mode and redirects to the article location.
When the preview mode is activated, Next.js sets some cookies in your browser. We will add these cookies to any request going to Next.js automatically, and Next.js treats any request with this cookie as a preview mode request.
Go back to your [slug].js
file, import the getPageData helper from the ./lib/api
page:
1import { fetchAPI, getPageData } from "../../lib/api";
Change your getStaticProps()
code as follows:
1 /* ./pages/article/[slug].js
2 *
3 * Change getStaticProps()
4 */
5 export async function getStaticProps({ params, preview = null }) {
6 const article = await getPageData(params.slug, preview);
7
8 return {
9 props: { article, preview },
10 revalidate: 1,
11 };
12 }
Access the preview mode by navigating to this url http://localhost:3000/api/preview?secret=
Where:
.env
file
Navigate to the ./pages/api/
folder and create a new file named exit-preview.js
. Next, add the following lines of code to the exit-preview.js
file:
1 /*. /pages/api/exit-preview.js */
2
3 export default function handler(req, res) {
4
5 try {
6 // Clears the preview mode cookies.
7 // This function accepts no arguments.
8 res.clearPreviewData()
9
10 return res.status(200).json({ message: 'Cookies Cleared' })
11 } catch (error) {
12 return res.status(500).json({ message: error })
13 }
14 }
This code clears all the cookies set by the previews mode API in your browser. Also, navigate to ./pages/articles/[slug].js
and change the <Article />
component.
1 /* ./pages/articles/[slug].js */
2
3 import Markdown from "markdown-to-jsx";
4 import { fetchAPI, getPageData } from "../../lib/api";
5 import Layout from "../../components/layout";
6
7 const Article = ({ article, preview }) => {
8 return (
9 <>
10
11 /* Section of code to add */
12 /* Beginning of Section */
13 <div>
14 {preview ? (
15 <div className="relative bg-indigo-600">
16 <div className="max-w-7xl mx-auto py-3 px-3 sm:px-6 lg:px-8">
17 <div className="pr-16 sm:text-center sm:px-16">
18 <p className="font-medium text-white">
19 <span>Preview mode is on,</span>
20 <span className="block sm:ml-2 sm:inline-block">
21 <a
22 href="http://localhost:3000/api/exit-preview"
23 className="underline hover:text-cyan transition-colors"
24 >
25 turn off
26 </a>
27 </span>
28 </p>
29 </div>
30 </div>
31 </div>
32 ) : null}
33 </div>
34 /* End of section */
35
36 <Layout>
37 <div className="mt-10">
38 <div className="mb-4 md:mb-0 w-full max-w-screen-md mx-auto">
39 <div className="absolute left-0 bottom-0 w-full h-full" />
40 <h1 className="text-6xl font-bold pb-4 text-center">{article.data[0].attributes.title}</h1>
41 <div>
42 {article.data[0].attributes.image && (
43 <img src={`http://localhost:1337${article.data[0].attributes.image.data.attributes.url}`} />
44 )}
45 </div>
46 <div>
47 {article.data[0].attributes.category && (
48 <a
49 href="#"
50 className="px-4 py-1 bg-black text-blue-200 inline-flex text-md items-center justify-center mb-2"
51 >
52 {article.data[0].attributes.category.data.attributes.name}
53 </a>
54 )}
55 </div>
56 <h2 className="text-4xl pt-2 font-semibold text-gray-500 leading-tight">
57 {article.data[0].attributes.description}
58 </h2>
59 <div className="mt-3">
60 {article.data[0].attributes.author && (
61 <p className="text-blue-900 font-semibold pb-2">
62 Written by - {article.data[0].attributes.author.data.attributes.name}
63 </p>
64 )}
65 </div>
66 </div>
67 <article className="prose lg:prose-xl px-4 lg:px-0 mt-12 text-gray-700 max-w-screen-md mx-auto text-lg leading-relaxed">
68 <Markdown>{article.data[0].attributes.content}</Markdown>
69 </article>
70 </div>
71 </Layout>
72 </>
73 );
74 };
75
76 export default Article;
77
78 export async function getStaticPaths() {
79 const articles = await fetchAPI("/articles?populate=*");
80
81 return {
82 paths: articles.data.map((article) => ({
83 params: {
84 slug: article.attributes.slug,
85 },
86 })),
87 fallback: false,
88 };
89 }
90
91 export async function getStaticProps({ params, preview = null }) {
92 // const article = await fetchAPI(`/articles/?filters\[slug\][$eq]=${params.slug}&populate=*`);
93 const article = await getPageData(params.slug, preview);
94
95 return {
96 props: { article, preview },
97 revalidate: 1,
98 };
99 }
The blog post pages should look like this when preview mode is activated.
Click turn off to deactivate the preview mode. You can also deactivate the preview mode by navigating to http://localhost:3000/api/exit-preview
.
The preview mode is an essential static site generator tool that can improve the content editor experience using the Jamstack architecture. To learn more about Next.js previews, check out the Next.js Preview Mode documentation.
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