owned this note
owned this note
Published
Linked with GitHub
# Building an Inventory Management Software with Strapi, Zod, Mapbox and Web Sockets
## **Introduction**
In this blog series, we will dive into building🚀 an inventory management web application called "**Rentory**" for a construction equipment rental company. We'll leverage the all new **[Strapi 5](https://strapi.io/five)!!**, a powerful [headless CMS](https://strapi.io), and Next.js to build this application.
## **The Need for Inventory Management**
Inventory management entails accurate record keeping of goods available for sale. For a regular sales/production company, this would include raw-materials, work-in-progress and finished goods ready for the market sale.
However in the context of an **equipment rental company**, it involves managing the availability, maintenance and rental of heavy duty equipment.
Implementing inventory management offers multiple adavantages such as: Cost savings, customer satisfaction, provides accurate company statistics for growth and improvement.
## **Tutorial Outline**
This article is the first of a three-part blog series with the following content outlines below:
* Part 1: Setting up Strapi with Next.js, login/signup form validation, implementing mapbox for location.
* Part 2: Implementing socket.io from using Strapi plugin for real-time equipment monitoring.
* Part 3: Implementing Algolia for AI search and Chart.js for charting on the application.
## **Prerequisites for the Article Series**
* A Familiar code editor, preferrably [VsCode](https://code.visualstudio.com/).
* [Node.js](https://nodejs.org/en) Runtime installed on your local machine.
* Basic knowledge of [Next.js](https://nextjs.org/).
* Basic Knowledge of [Strapi headless CMS](https://strapi.io).
* Willingness to learn new concepts!!
## **At the End of the Article Series**
You will gain familiarity with the following and more:
* Setting up and working with [Strapi Headless CMS](https://strapi.io) including content types.
* Building intuitive user interfaces with Next.js using tailwindCSS for styling.
* Form data validation in web applications using [zod](https://zod.dev/).
* Data Fetching in Next.js through the Strapi API.
* Implementing real-time functionalities with socket.io websocket library.
* Geo-location integrations for your applications with [mapbox](https://www.mapbox.com/) library.
* Implementing [Algolia](https://www.algolia.com/) for intelligent AI search, [Chart.js](https://www.chartjs.org/) for javaScript charting in modern web applications.
* Build a fullstack application with Next.js and Strapi.
## **Inventory Management Software Overview**
This software will consist mainly of the landing page, Admin dashboard, inventory management, rental management, profile page and equipment availability status page for customers.
The image below shows the landing of the landing page for the web application, in the third part of this series we would focus on building the rest of the frontend application. For now we will focus on setup, installations and some data fetching.
![Screenshot (1074)](https://hackmd.io/_uploads/Bk1HuaePC.png)
## Key Features to be Built in this Article (Part 1)
For this first part of the series we will be focusing on the following features:
* Building the landing page with **Next.js** and **TailwindCSS** for styling.
* Building the **signup** and **Login** pages for users on the application.
* Implementing **Zod**, a Typescript validation for signup and login forms in our application
* Geo-location of equipment with **mapbox** for tracking in the equipment list page.
## **Project Setup and Installations**
In order to build successfully, we need to create a **folder/directory** for the fullstack application. Spin up your preferred code editor (Eg Vscode), with the help of the terminal create the folder and enter using the below commands.
```
mkdir inventory-app
cd inventory-app
```
## **Next.js (Frontend) Setup**
**Introduction:** Next.js is an open-source React framework for fullstack web development. Built by Vercel, It offers a suite of convinient features like Server-side rendering and static website generation.
We would combine these advantages with [Strapi Headless CMS](https://strapi.io/) to build a wonderful inventory application.
Still inside the inventory-app folder, run the following command to create a Next.js app.
```
npx create-next-app@latest
```
Select the following crossed options:
```
√ What is your project named? ... ~~frontend~~
√ Would you like to use TypeScript? ... No / ~~Yes~~
√ Would you like to use ESLint? ... ~~No ~~/ Yes
√ Would you like to use Tailwind CSS? ... No / ~~Yes~~
√ Would you like to use `src/` directory? ... ~~No~~ / Yes
√ Would you like to use App Router? (recommended) ... No / ~~Yes~~
√ Would you like to customize the default import alias (@/*)? ... No / ~~Yes~~
√ What import alias would you like configured? ... @/*
```
Once the project "**frontend**" is created, navigate to the frontend in your terminal with the command.
```
cd frontend
```
Start the Project for the first time.
```
npm run dev
```
Search the address below in your browser to see the project run initially.
```
http://localhost:3000
```
![Screenshot (1060)](https://hackmd.io/_uploads/Skx2PcCLC.png)
If you observed= clearly, the Next.js setup provides an option for installing [tailwindcss](https://tailwindcss.com/) automatically during setup. We would make use of Tailwindc\CSS for styling.
At this point, the folder structure should look just like the image below.
![Screenshot (1061)](https://hackmd.io/_uploads/SklhjqA8R.png)
## **Strapi(Backend) Setup**
**Introduction**: [Strapi](https://strapi.io/) is the leading open source [headless CMS](https://strapi.io/what-is-headless-cms)(Content Management System) that is 100% JavaScript/TypeScript compatible. It enables developers build cutomisable APIs quickly allowing for use with multiple frontend technologies. in this series, we would be working with the all new Strapi 5!!
Still in the **inventory-app** directory, let us start by running the following command.
```
npx create-strapi-app@rc inventory --quickstart
```
You should see the auto setup initialize in your terminal like below.
```
npx create-strapi-app@rc inventory --quickstart
Need to install the following packages:
create-strapi-app@5.0.0-rc.9
Ok to proceed? (y) y
We can't find any auth credentials in your Strapi config.
Ok to proceed? (y) y
We can't find any auth credentials in your Strapi config.
Create a free account on Strapi Cloud and benefit from:
- ✦ Blazing-fast ✦ deployment for your projects
- ✦ Exclusive ✦ access to resources to make your project successful
- An ✦ Awesome ✦ community and full enjoyment of Strapi's ecosystem
Start your 14-day free trial now!
? Please log in or sign up. Login/Sign up
[INFO] 🔌 Connecting to the Strapi Cloud API...
If a browser tab does not open automatically, please follow the next steps:
1. Open this url in your device: https://auth.cloud.strapi.io/activate?user_code=HCXZ-FDJZ
2. Enter the following code: HCXZ-FDJZ and confirm to login.
✔ Authentication successful!
You are now logged into Strapi Cloud.
To access your dashboard, please copy and paste the following URL into your web browser:
https://cloud.strapi.io/projects
Creating a new Strapi application at C:\Users\duzie\Desktop\fullstack\inventory-app\inventory.
```
The terminal would pop up **Login/Signup** buttons inviting you to create an account on Strapi cloud. You can use the arrow keys to select them, then create an account accordingly. More information can be found [here](https://docs.strapi.io/dev-docs/quick-start).
Subsequently, you would be prompted to login to your admin panel with the details previously created on the Strapi Cloud.
![Screenshot (1062)](https://hackmd.io/_uploads/Hk7zE2A8R.png)
The admin dashboard loads up next, here you will create content types and perform other operations on the backend.
![Screenshot (1064)](https://hackmd.io/_uploads/HkYmB2CLC.png)
After the setup, you should have your frontend and backend(inventory) folders just like below.
![Screenshot (1154)](https://hackmd.io/_uploads/Hygo5JGc0.png)
## **Create Content Types**
Now, we have our Strapi backend setup. Let us create our first content type starting from the pages. We would create type for the landing Page in this tutorial, you can read more about content types [here](https://docs.strapi.io/user-docs/content-type-builder).
Navigate to the **Content-Type** Builder under **SINGLE TYPE**, click **create-new-single-type**.
// GIF HERE
### **A simple Guide**
**Single Type - Landing Page
Text - Short Text => Title
Text - Long Text => Description**
Once done, click save. Congratulations, you have successfully created your first content type. Now, time to add some basic data to the content types.
## **Testing the data flow from the Strapi API**
Now that we have created a new content type, we can test our API and get responses via tools like Postman, Insomnia or simply your browser.
First we have to enable permissions, this allows any client we choose to access the API response.
Navigate to Settings -> USERS & PERMISSION PLUGIN -> Roles -> Public
Select **Landing Page** and check the **find** checkbox.
// GIF HERE
Recall that when we enabled permissions, Strapi provided an endpoint (**/api/landing-page**) to access the API content.
This means together with the localhost url, we can access the API data at the endpoint **http://localhost:1337/api/landing-page**.
### **Via Postman**
Postman is a platform for buildin and testing APIs, it offers numerous advantages just like it will enable us test the Strapi API.
![Screenshot (1070)](https://hackmd.io/_uploads/ry179q1w0.png)
As mentioned earlier, a simple **GET** request to the endpoint will return the following results as shown above.
### **Via Web Browser**
By default, a browser sends a GET request to any **url** on search. As simple search on any web browser of your choice would display the API response.
![Screenshot (1066)](https://hackmd.io/_uploads/Sk6PJbkvA.png)
Now we can see our response and move ahead with receiving our API from our Next.js frontend.
```
{
"data": {
"id": 1,
"attributes": {
"title": "Landing Page",
"description": "This page contains a brief summary of the software service plus a call to action to Login/signup.",
"createdAt": "2024-06-30T12:45:22.588Z",
"updatedAt": "2024-06-30T12:45:31.032Z",
"publishedAt": "2024-06-30T12:45:31.018Z"
}
},
"meta": {
}
}
```
## Making fetch Requests from the Next.js frontend
In the previous section, we ran tests and got API resposes from a GET request sent to the API. Now we would demonstrate the usage of this API in our Next.js frontend application in an API call.
The image below shows the code configuration for data fetching in visual studio code enviroment.
![Screenshot (1069)](https://hackmd.io/_uploads/BJbjuqJwR.png)
For visibily, check out the code sample below. Copy and paste this code in your **page.tsx** file of your application.
```
"use client"
import React, {useState, useEffect } from "react"
import { LandingPageData } from './types';
//define the data fetching function
async function getStrapiData(url:string) {
const baseurl = "http://localhost:1337";
try {
const response = await fetch(baseurl + url);
const data = await response.json()
return data;
} catch (error) {
console.error(error)
return null;
}
}
export default function Home() {
const [data, setData] = useState<LandingPageData | null>(null);
useEffect(() => {
async function fetchData() {
const strapiData = await getStrapiData("/api/landing-page")
setData(strapiData?.data)
}
fetchData();
}, [])
if(!data) return <div>Loading...</div>;
const {title, description} = data.attributes;
return (
<main className="mx-auto">
<h1 className="text-4xl">{title}</h1>
<p className="text-xl">{description}</p>
</main>
);
}
```
### **Note**
Notice the "**use client**" phrase at the top of the **Page.tsx** file
Create a file, "**types.ts**" in your /app directory and paste the following code provided below.
The types.ts file defines the structure of the data on the landingPage, defining types like this is important in TypeScripe applications. It offers advantages in type safety and consistency of code while reducing the risk of bugs.
```
export interface LandingPageData {
id: number;
attributes: {
title: string;
description: string;
// Add more fields as needed
};
}
```
The resulting effect is shown on the web page below:
![Screenshot (1068)](https://hackmd.io/_uploads/SkTJ9N1DC.png)
Now lets us add more styling to make the landing page more intitive.
# **File Structure**
```
/your-app
├── public/
│ ├── images/ # Static images
│ └── ... # Other public assets
├── src/
│ ├── app/
│ │ ├── layout.tsx # Global layout including top nav and sidebar
│ │ ├── page.tsx # Home page (dashboard or landing page)
│ │ ├── availability/
│ │ │ └── page.tsx # Availability page (dynamic content area)
│ │ ├── inventory/
│ │ │ └── page.tsx # Inventory page (dynamic content area)
│ │ ├── login/
│ │ │ └── page.tsx # Login page
│ │ ├── signup/
│ │ │ └── page.tsx # Signup page
│ │ ├── profile/
│ │ │ └── page.tsx # Company profile page
│ │ ├── reports/
│ │ │ └── page.tsx # Reports page
│ │ └── _error.tsx # Custom error page (optional)
│ ├── components/
│ │ ├── TopNavigationBar.tsx # Top navigation bar component
│ │ ├── Sidebar.tsx # Sidebar component
│ │ └── ... # Other reusable components
│ ├── lib/
│ │ ├── api.ts # API utility functions
│ │ ├── mapbox.ts # Mapbox-related utilities
│ │ └── algolia.ts # Algolia-related utilities
│ ├── styles/
│ │ ├── globals.css # Global CSS styles
│ │ └── tailwind.css # Tailwind CSS configuration (if using Tailwind)
│ ├── types/
│ │ └── index.d.ts # TypeScript type definitions
│ └── utils/
│ └── helpers.ts # Utility functions
├── .env.local # Environment variables
├── next.config.js # Next.js configuration
├── package.json # Project metadata and dependencies
└── tsconfig.json # TypeScript configuration
```
## **Conclusion**
Well done if you made it this far, For a quick recap of everything.
Firstly, we discussed the need for inventory management, then the outline of this blog series plus concepts and moved on to installations and configurations with Strapi and Next.js.
We created a sample content type and made the endpoint accessible by clients. Then we peformed API tests on the Strapi API from Postman and a browser. Finally, passed data from the backend to our frontend application.
In the next part of this blog series we will delve into building with advanced functionality for the backend with Strapi and then Next.js frontend for the third part.
For reference, this is the link to the project [repo](https://github.com/vector-10/inventory-app).