Simply copy and paste the following command line in your terminal to create your first Strapi project.
npx create-strapi-app
my-project
Content Management Systems (CMS) are used to develop applications while creating their content. Traditionally, CMS build applications as one. This means the backend and the frontend of the application are managed by one base system.
The system can store and manage the content as a backend. The same system will still handle the presentation layer as the frontend. The two sets of systems are closely connected to run as a monolith application.
This is a great set of powering applications. However, the approach creates some challenges; some of them are highlighted below.
Above are a few challenges that the traditional CMS fails to solve. However, with the advances in technology, a headless CMS was born to address these challenges.
A headless CMS allows you to run a decoupled system. This means the content management (backend) and the presentation layer (frontend) run independently.
A headless CMS only deals with content management; it is not responsible for how the content will be represented to the user. This approach gives you a tone of advantages such as:
Check the Guide to Headless CMS and learn what is a headless CMS, its benefits, and usage.
One of the most popular headless CMS that fits your content management demands is Strapi. Strapi is an open-source headless CMS based on Node.js. It helps you build and manage your backend content while producing API endpoints to consume your data.
Once you have created your content with Strapi, you need the right framework to handle the content presentation layer. Remix is a good choice to channel your content to the users. In this guide, we will use Remix to consume Strapi generated content.
To continue in this article, it is essential to have the following:
With these, you're ready to continue.
To set up Strapi, create a remix-strapi-app
project directory and open it using the VS Code editor. Using your editor, open a terminal and run the following one-time command to create Strapi CMS backend project.
npx create-strapi-app strapi-notes-app --quickstart
This command will create a local Strapi project inside the strapi-notes-app
directory.
Strapi will then build an admin UI with development configurations and automatically start the administration panel on http://localhost:1337/admin
.
To start using Strapi, create an admin account using your details, then click let's start
. This will direct you to the Strapi administrator Dashboard.
We are building a Notes app using Strapi; therefore, we need to model the data for a Notes app. To build the Notes app content structure, first head over to the Content-Type Builder section and Create new collection type.
Start modeling the Notes content as follows:
Once done, you should have the following fields:
The next step is to create notes content. Here, we'll add some Notes entries to the Strapi CMS. Head over to the Content Manager section:
Manage the Notes as follows:
Now we need to access this backend and use it with Remix. We need to create an API token for Strapi CMS as follows:
Your API token will be generated successfully.
Copy this token and save it in a safe location. We will use to consume the API using Remix. The next step is to set up the Remix Notes application.
To set up Strapi, navigate to the remix-strapi-app
project directory and open it using your text editor. Open a terminal and run the following one-time command to create a Remix frontend project.
npx create-remix@latest
When creating the Remix app, you will be asked basic questions to set up the Remix App. Answer these onboarding command prompts as shown in the image below:
A remix-notes-app
will be created containing the bootstrapped Remix app. To test this app, open a terminal using your text editor and change the directory to the created remix folder:
cd remix-notes-app
Then start the Remix app development server:
npm run dev
You can now access the server on your browser at http://localhost:3000
.
To start using Strapi with Remix, create a .env
file at the root of the remix-notes-app
folder and add in the following:
http://localhost:1337
.Add these environment variables to the .env
file as follows, ensuring you replace the variables with the correct parameters:
1
2
STRAPI_URL_BASE=http://your_ip_address:port_where_strapi_is_running
STRAPI_API_TOKEN=your_strapi_access_token
To consume these variables, head over to the app folder and create a utils
directory. The directory will host errorHandling.js
for handling errors while communicating to Strapi as follows:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// Custom error class for errors from Strapi API
class APIResponseError extends Error {
constructor(response) {
super(`API Error Response: ${response.status} ${response.statusText}`);
}
}
// Checking the status
export const checkStatus = (response) => {
if (response.ok) {
// response.status >= 200 && response.status < 300
return response;
} else {
throw new APIResponseError(response);
}
}
class MissingEnvironmentVariable extends Error {
constructor(name) {
super(`Missing Environment Variable: The ${name} environment variable must be defined`);
}
}
export const checkEnvVars = () => {
const envVars = [
'STRAPI_URL_BASE',
'STRAPI_API_TOKEN'
];
for (const envVar of envVars) {
if (!process.env[envVar]) {
throw new MissingEnvironmentVariable(envVar)
}
}
}
Let's now work on the frontend application. We will make all the changes inside the app/routes/index.jsx
file.
To display the Notes from the CMS, head over to the app/routes/index.jsx
file:
1
2
import { useLoaderData} from "@remix-run/react";
import { checkStatus, checkEnvVars } from "~/utils/errorHandling";
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
export async function loader () {
checkEnvVars();
const res = await fetch(`${process.env.STRAPI_URL_BASE}/api/notes`, {
method: "GET",
headers: {
"Authorization": `Bearer ${process.env.STRAPI_API_TOKEN}`,
"Content-Type": "application/json"
}
});
// Handle HTTP response code < 200 or >= 300
checkStatus(res);
const data = await res.json();
// Did Strapi return an error object in its response?
if (data.error) {
console.log('Error', data.error)
throw new Response("Error getting data from Strapi", { status: 500 })
}
return data.data;
}
Index
function as follows:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
export default function Index() {
const notes = useLoaderData();
return (
<div style={{ fontFamily: "system-ui, sans-serif", lineHeight: "1.4" }}>
<h1>Notes App</h1>
{
notes.length > 0 ? (
notes.map((note,index) => (
<div key={index}>
<h3>{note.attributes.title}</h3>
<p>{note.attributes.description}</p>
<p>{new Date(note.attributes.createdAt).toLocaleDateString()}</p>
<button onClick={null}>
delete note
</button>
</div>
))
) : (
<div>
<h3>Sorry!!, you do not have notes yet!!</h3>
</div>
)
}
</div>
);
}
From above, we are checking whether we have notes. If yes, we are looping through them, displaying each and every one of them, else we are displaying that no notes exist.
Based on the notes added, your page should be similar to the image below.
Now, let's work on adding a note. To do this, follow the instructions below.
1
import { Form,useActionData } from "@remix-run/react";
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
const addNote = async (formData) => {
checkEnvVars();
const response = await fetch(`${ process.env.STRAPI_URL_BASE } /api/notes`, {
method: "POST",
body: JSON.stringify({
"data":{
"title" : formData.title,
"description" : formData.description
}
}),
headers: {
"Authorization": `Bearer ${ process.env.STRAPI_API_TOKEN } `,
"Content-Type": "application/json"
}
});
// Handle HTTP response code < 200 or >= 300
checkStatus(response);
const data = await response.json();
// Did Strapi return an error object in its response?
if (data.error) {
console.log('Error', data.error)
throw new Response("Error getting data from Strapi", { status: 500 })
}
return data.data;
}
Index
function, initialize the action data hook and log the response:1
2
const actionData = useActionData();
console.log("actionData",actionData);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<Form
method="post">
<div>
<input type="text" name="title" placeholder="title of note" />
</div>
<div>
<input type="text" name="description" placeholder="Description of note" />
</div>
<div>
<button type="submit">
add note
</button>
</div>
</Form>
Test the functionality from your browser. When you add a note, it will reflect on the notes section below:
To delete a Note, define a function to handle the delete functionality:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
const deleteNote = async (noteId) => {
const response = await fetch(`http://localhost:1337/api/notes/${noteId}`, {
method: "DELETE",
headers: {
"Authorization": `Bearer your_api_token`,
"Content-Type": "application/json"
}
});
// Handle HTTP response code < 200 or >= 300
checkStatus(response);
const data = await response.json();
// Did Strapi return an error object in its response?
if (data.error) {
console.log('Error', data.error)
throw new Response("Error getting data from Strapi", { status: 500 })
}
window.location.reload(); // refresh the page
}
- Append the functionality to the `deleteNote` button:
<button onClick={() => deleteNote(note.id)}>
delete note
</button>
Now, once you click the button, the note will be deleted.
Headless CMSes are scalable solutions that can be incorporated into the architecture of practically any application. You can maintain and store content to be consumed by various devices, platforms, and applications. This design may be used to handle items in e-commerce apps, store material for blog apps, or create any CRUD-related application.
In this guide, we have learned to use Strapi as headless CMS to build a minimal Remix CRUD application. I hope you enjoyed this tutorial. Happy coding!
You can find the source code for the project on this GitHub repository.
Joseph is fluent in Android Mobile Application Development and has a lot of passion for Fullstack web development. He loves to write code and document them in blogs to share ideas.