Strapi is an open-source headless CMS. A headless CMS is a backend content management system (CMS) that makes content available via RESTful APIs or GraphQL APIs. Strapi is 100% Javascript, fully customizable, and developer-first.
Strapi enables you to build your applications without having to worry about the backend. You can integrate any frontend framework of your choice with Strapi.
This tutorial will help you get started with building desktop applications with Next.js and Strapi. This tutorial will show you how to create a backend for a quiz application using Strapi and create a quiz desktop application using Next.js and TailwindCSS.
To follow this article, you should have Node.js installed on your computer. The installed Node.js must be version 12.x and above so that you can install Strapi.
First of all, we are going to set up our Strapi application. We are going to be using Strapi templates to set up our Strapi application. Strapi templates are Strapi applications that contain pre-built collection types and single-types suited for the appropriate use case and data type. In this tutorial, we will use the quiz template.
Run the command below to create the project directory in your preferred folder:
1 mkdir quiz-app
2 cd quiz-app
Run the command below to create a Strapi application with the quiz template:
1 npx create-strapi-app backend --quickstart --template https://github.com/malgamves/strapi-template-quiz
2 /** OR **/
3 yarn create strapi-app backend --quickstart --template https://github.com/malgamves/strapi-template-quiz
The above command creates a strapi backend folder called backend/
using the quiz template URL specified with the --template
flag. The command automatically runs the strapi application when it’s done creating the strapi backend folder. This command automatically opens a new browser tab at http://localhost:1337/admin/auth/register-admin
.
Fill in the relevant information and click “LET’S START.” It will take you to the admin panel, where we can already see the content types created by the template and the sample data in them.
The template already helped create the “Questions” content type. In addition to that, we are going to create a “Quizzes” content type. The “Quizzes” content type has a one-to-many relationship with the “Questions” content type.
We are going to create 3 fields in the “Quizzes” content-type:
At this point, the “Quizzes” content type dashboard should look like the screenshot below
Next, click on the green “Save” button. This action will restart the server and implement the /quizzes
endpoint. You should now be able to see “Quizzes” under “Collection Types” in the navigation panel.
Click on “Add New Quizzes” to add sample quiz data.
Fill in all the required fields, click save and click on publish.
You can add more sample quizzes if you want.
Next, we have to make the /quizzes
endpoint public to access the published data. From the navigation panel, navigate to Settings>Roles>Public.
Under “Quizzes” in the “Permissions” section, click on “findone” and “find.” Click on Save. We have just done what we have just done will allow unauthenticated users to get all quizzes or get just one quiz with the quiz id. You can go to https://localhost:1337/quizzes
on your web browser to see all the quiz data saved.
Next, we are going to build the desktop application.
We will use Nextron to build the desktop application. Nextron enables us to build desktop applications with Next.js. We will use TailwindCSS to help add styles to the desktop application.
Execute the commands below to create the Nextron application.
1 npx create-nextron-app desktop-app
2 cd desktop-app
3 npm install
The folder structure in the desktop-app/
directory should look like the screenshot below:
Delete the files in the renderer/pages/
directory. Next, we will set up TailwindCSS. Execute the commands to install and setup TailwindCSS config files:
1 npm install -D tailwindcss@latest postcss@latest autoprefixer@latest
2 cd renderer
3 npx tailwindcss init -p
The renderer/
folder contains the Next.js files we are going to use to build the desktop application. The above commands install the required libraries and generate tailwind.config.js
and postcss.config.js
files in the renderer/
folder.
We are going to set up TailwindCSS in our application. Create a folder called styles/
in the renderer/
folder. Create a file called globals.css
in the renderer/styles/
folder and copy the code below inside:
1 @tailwind base;
2 @tailwind components;
3 @tailwind utilities;
Next, create a file called _app.jsx
in the renderer/pages
folder and copy the following code inside:
1 import '../styles/globals.css'
2 function MyApp({ Component, pageProps }) {
3 return <Component {...pageProps} />
4 }
5 export default MyApp
Note that you must import the globals.css
file in the _app.jsx
file for TailwindCSS to work.
Next, we will write functions to call the quiz APIs. Create a folder called api/
in the renderer/
folder. Create a file called quiz.js
in the renderer/api
folder and copy the following code inside:
1 const QUIZ_URLS = {
2 get: 'http://localhost:1337/quizzes',
3 };
4 export const getAll = async () => {
5 const res = await fetch(QUIZ_URLS.get);
6 return await res.json();
7 };
8 export const getById = async (id) => {
9 const res = await fetch(`${QUIZ_URLS.get}/${id}`);
10 return await res.json();
11 };
The above code contains functions to get a quiz by id and get all quizzes.
Next, we are going to create the home page. It is the page that will get displayed by default when you start the desktop application. Create a file called home.jsx
in the renderer/pages
directory and copy the following code inside:
1 import Link from "next/link";
2 import {getAll} from "../api/quiz";
3
4 function getCards(data) {
5 return data.map((quiz) => (
6 <div
7 key={quiz.id}
8 className="quiz border shadow-md p-3 flex-initial flex flex-col rounded-md space-y-3 mr-2 w-2/6"
9 >
10 <div className="name text-2xl">{quiz.title}</div>
11 <div className="description text-sm">{quiz.description}</div>
12 <div className="questions text-sm">{quiz.questions.length} questions</div>
13 <div>
14 <Link href={`/quiz/${quiz.id}`}>
15 <a className="start-button px-2 py-1 rounded border border-green-500">
16 Start
17 </a>
18 </Link>
19 </div>
20 </div>
21 ));
22 }
23 export default function IndexPage({quizzes}) {
24 return (
25 <div className="home container font-sans px-4">
26 <div className="header text-3xl font-bold my-8">Quiz App</div>
27 <div className="home-body flex flex-wrap">
28 {getCards(quizzes)}
29 </div>
30 </div>
31 );
32 }
33 export async function getStaticProps() {
34 const quizzes = await getAll();
35 return {
36 props: {
37 quizzes,
38 }
39 }
40 }
From the above code, we can see that we are using TailwindCSS classes to style the page. The getStaticProps
function calls the function to get all quizzes and passes it to the IndexPage
component as props.
Next, we will create a page for taking the quizzes. We will make use of Next.js dynamic routing to achieve this. In the pages/
directory, create the folders /quiz/[id]/
and create a file called index.jsx
in the quiz/[id]
folder.
The folder structure created will enable us to create a route for urls like /quiz/:id
where id
is the quiz id
. Copy the following code into the quiz/[id]/index.jsx
file:
1 import {useState} from "react";
2 import {useRouter} from "next/router";
3 import {getAll, getById} from "../../../api/quiz";
4
5 const getQuestion = (questions, index) => {
6 return questions[index];
7 };
8
9 export async function getStaticProps({params}) {
10 const quiz = await getById(params.id);
11 return {
12 props: {
13 quiz,
14 }
15 }
16 }
17
18 export async function getStaticPaths() {
19 const quizzes = await getAll();
20 const paths = quizzes.map(quiz => ({params: {id: `${quiz.id}`}}));
21 return {
22 paths,
23 fallback: false
24 }
25 }
26
27 const Quiz = ({quiz}) => {
28 const router = useRouter();
29 const [index, setIndex] = useState(0);
30 const [correctAnswers, setCorrectAnswers] = useState(new Set());
31 const question = getQuestion(quiz.questions, index);
32
33 const hasNext = () => {
34 return index < quiz.questions.length - 1;
35 };
36
37 const isCorrectlyAnswered = () => {
38 return correctAnswers.has(index);
39 };
40
41 const nextQuestion = () => {
42 if (!hasNext()) {
43 finishQuiz();
44 } else {
45 setIndex(index + 1);
46 }
47 };
48
49 const hasPrev = () => {
50 return index > 0;
51 };
52
53 const prevQuestion = () => {
54 if (index !== 0) {
55 setIndex(index - 1);
56 }
57 };
58
59 const finishQuiz = () => {
60 alert(`Your score is ${correctAnswers.size}`);
61 router.push("/home");
62 };
63
64 const checkOption = (option) => {
65 if (option.isCorrect && !isCorrectlyAnswered()) {
66 correctAnswers.add(index);
67 setCorrectAnswers(correctAnswers);
68 } else if (!option.isCorrect && isCorrectlyAnswered()) {
69 correctAnswers.delete(index);
70 setCorrectAnswers(correctAnswers);
71 }
72 nextQuestion();
73 };
74
75 return (
76 <div className="container font-sans px-4">
77 <div className="text-3xl font-bold my-8">{quiz.title}</div>
78 <div className="flex flex-col rounded-md shadow-md w-full py-4 px-4 mb-4">
79 <div className="font-bold">Question {index + 1}</div>
80 <div>{question.questionText}</div>
81 </div>
82 <div className="flex flex-initial flex-wrap justify-between text-center gap-4">
83 {question.answerOptions.map((option) => (
84 <button
85 key={option.id}
86 onClick={() => checkOption(option)}
87 className="block md:w-5/12 w-full option rounded-md shadow-md p-2"
88 >
89 {option.answerText}
90 </button>
91 ))}
92 </div>
93
94 <div className="flex gap-x-4 mt-10 justify-center">
95 {hasPrev() ? (
96 <p className="px-2 button rounded border border-green-500">
97 <button onClick={prevQuestion}>Previous</button>
98 </p>
99 ) : null}
100
101 {hasNext() ? (
102 <p className="px-2 button rounded border border-green-500">
103 <button onClick={nextQuestion}>Next</button>
104 </p>
105 ) : null}
106 </div>
107 </div>
108 );
109 };
110
111 export default Quiz;
From the above code, we can see that the API call is made in the *getStaticProps*
function. getStaticProps
is given params
, which contains id
. We then use the id
passed to make an API request to the Strapi backend to get specific quiz data.
The getStaticPaths
function is required if a page has dynamic routes and uses getStaticProps
. The getStaticPaths
function defines a list of paths that have to be rendered to HTML at build time.
In the Quiz
function, we use the useRouter
hook to redirect users to the home page when the quiz is done. The useState
hooks store the index of the current question being displayed and store a set of the correct questions answered.
To keep track of the score, we used the set logic instead of storing and updating a score state variable. We did this because storing the score without knowing the questions answered will enable users to add to their score by answering a question more than once.
When the user is done with the quiz, the user gets alerted of their score and redirected to the home page. We are done building the application. The file structure in the renderer/
folder should look like the screenshot below.
Run the command yarn dev
to run the application. The screenshots below show a user taking a sample quiz created earlier.
The homepage below is the page the application defaults to on startup. The page makes an API request to the Strapi backend to get all the published quizzes.
This page shows a question. This is the first question directed after you click on the Sample 1
quiz.
You can go from one question to the other with the Next
and Previous
buttons. The set logic implemented earlier makes sure that a user can not game the system by answering the same question correctly more than once.
The score gets displayed when the quiz ends. Once the user clicks OK
, the user gets redirected to the home page shown earlier.
In this article, we built a quiz desktop application with Next.js and Strapi. You can extend the application by persisting the result and adding user management. You can find the application code.
I am a software engineer dedicated to using various technologies to solve problems.