Building a chat application with React, Strapi, and Firebase combines React's frontend strength with Strapi backend data management skills, Firebase's authentication and messaging functionality. In this tutorial, you'll learn how to create a Strapi chat app, integrate Firebase for user authentication, and get real-time updates.
To follow along with this tutorial, make sure you have:
To set up the Strapi project, ensure you have Strapi installed on your system, or you can follow up as the tutorial proceeds with the installation process. Navigate to your terminal and run the command below:
1 npx create-strapi-app@latest my-project
The above command will create a new project named my-project
and install Strapi on your system. After a successful installation, use the following command to launch your Strapi application:
npm run develop
Once you have successfully launched your project, copy the URL from your console and paste it into your browser's address bar. If you're new to Strapi, you must log in or sign up to access your project.
After successfully logging in, you'll create an Account
collection type to store users who newly join your chat room. Navigate to the side navigation bar, select Content-Type Builder, and click Create new collection type.
Clicking Continue will lead you to the next step, where you can add additional fields to your collection. In this step, you'll add three (3) fields to your collection type, each serving a specific purpose as described below:
uid
: To create the uid
field, choose UID and enter any name you wish; nevertheless, you will use uid
as the name. To proceed, click Add Another Field.Username
: For the Username
field, select a text field and name it Username
. Then, click Add Another Field to continue.Email
: Choose the email field type and name it Email
. Afterward, click the Finish button to complete the process. If done correctly, you should see the same image displayed below:NOTE: Ensure you click save after creating any collection type
To store users' messages, you need to create a new collection type named ChatRoom-Message
with the following fields, as displayed in the image below:
Next, go to Settings, Roles, and click on Public. Then scroll down to Permissions, click on Chat-room-message, select all to authorize the application's activity, and click Save.
Make sure you do the same with Account and Save.
Since this project will make use of ReactJs, ensure you have ReactJs installed on your system. If not, you can create a new React app by opening your command prompt and running the following command:
npm create vite@latest my-app
Follow the prompt, then continue with the following command:
cd my-app
npm install
npm run dev
The command above will install and run your React application on your localhost server at http://localhost:5173/.
You'll be using DaisyUI for this project, but before incorporating the DaisyUI library into your chat app, you will first need to install Tailwind CSS in your React app. Follow these steps to proceed:
cd my app
npm install -D tailwindcss
npx tailwindcss init
Then, add this path to your tailwind.config.js
file:
1module.exports = {
2 content: ["./src/**/*.{html,js}"],
3 theme: {
4 extend: {},
5 },
6 plugins: [],
7};
Next, go to the index.css
file in your React application and include the following directives:
1@tailwind base;
2@tailwind components;
3@tailwind utilities;
Run the command below to install DaisyUI on your ReactJs app:
npm i -D daisyui@latest
Then, update your tailwind.config.js
file:
1export default {
2 content: ["./index.html", "./src/**/*.{js,ts,jsx,tsx}"],
3 theme: {
4 extend: {},
5 },
6 plugins: [require("daisyui")],
7};
Now that you have installed React and DaisyUI on your system, start your front-end development by creating the navigation bar. Open the my-app
directory in a code editor and navigate to the src
folder. Create a new folder called Components
, then create a file named Nav.jsx
, and add the following code:
1import React from "react";
2import { UserAuth } from "../context/AuthContext";
3
4const Nav = () => {
5 const { currentUser, logout } = UserAuth();
6 const handleLogout = async () => {
7 try {
8 await logout();
9 } catch (error) {
10 console.log(error);
11 }
12 };
13 return (
14 <div className="navbar bg-primary text-primary-content">
15 <div className=" container flex justify-between">
16 <a className="btn btn-ghost text-xl">Strapi ChatRoom</a>
17 {currentUser ? <button onClick={handleLogout}>Logout</button> : ""}
18 </div>
19 </div>
20 );
21};
22
23export default Nav;
In the src
folder, create a new folder called pages
. Inside it, create a new file named Login.jsx
and add the following code:
1import React, { useEffect, useState } from "react";
2const Login = () => {
3 return (
4 <div className="hero min-h-screen bg-base-200">
5 <div className="hero-content text-center">
6 <div className="max-w-md">
7 <h1 className="text-5xl font-bold">Welcome to Strapi ChatRoom</h1>
8 <p className="py-6">
9 Join the conversation, meet new people, and make connections in one
10 shared room.
11 </p>
12 <button className="btn btn-primary">LOGIN WITH GOOGLE</button>
13 </div>
14 </div>
15 </div>
16 );
17};
18export default Login;
Go to your component folder and create a new file named SendMessage.jsx
. Add the following code into this file:
1import React, { useState } from "react";
2const SendMessage = () => {
3 const [value, setValue] = useState("");
4 const handleSendMessage = (e) => {
5 e.preventDefault();
6 console.log(value);
7 if (value.trim === "") {
8 alert("Enter valid message!");
9 return;
10 }
11 setValue("");
12 };
13 return (
14 <div className="bg-gray-200 fixed w-full py-10 shadow-lg bottom-0">
15 <form onSubmit={handleSendMessage} className="container flex px-2">
16 <input
17 className="input w-full focus:outline-none bg-gray-100 rounded-r-none"
18 type="text"
19 value={value}
20 onChange={(e) => setValue(e.target.value)}
21 />
22 <button className="w-auto bg-gray-500 text-white rounded-r-lg px-5 text-sm">
23 Send
24 </button>
25 </form>
26 </div>
27 );
28};
29export default SendMessage;
In this code, when the user submits the form, the handleSendMessage
function is triggered. This function stops the form from submitting by default, saves the current message, and checks if it's empty. If empty, it alerts the user to input a message and clears the message input field. Next, create another file named Message.jsx
with the following code :
1import React from "react";
2const Message = ({ message }) => {
3 return (
4 <div>
5 <div className="chat chat-start">
6 <div className="chat-image avatar">
7 <div className="w-10 rounded-full">
8 <img alt="User Avatar" src="" />
9 </div>
10 </div>
11 <div className="chat-header">{message.name}</div>
12 <div className="chat-bubble">{message.text}</div>
13 </div>
14 </div>
15 );
16};
17export default Message;
The above code accepts the message
as a prop and renders the username, and message content. Next, create another file named ChatBox.jsx
in your Component
folder with the following code inside it:
1import React from "react";
2import Message from "./Message";
3import { useState, useRef, useEffect } from "react";
4const ChatBox = () => {
5 const messagesEndRef = useRef();
6 const [messages, setMessages] = useState([]);
7 const scrollToBottom = () => {
8 messagesEndRef.current.scrollIntoView({ behaviour: "smooth" });
9 };
10 useEffect(scrollToBottom, [messages]);
11 return (
12 <div className="pb-44 pt-20 container">
13 {messages.map((message, id) => (
14 <Message key={id} message={message} />
15 ))}
16 <div ref={messagesEndRef}></div>
17 </div>
18 );
19};
20export default ChatBox;
This code serves as a container for displaying chat messages. To render the ChatBox
and SendMessage
components, create a new file named chat.jsx
inside your pages
folder and include the following code:
1import React from "react";
2import ChatBox from "../Components/ChatBox";
3import SendMessage from "../Components/SendMessage";
4const Chat = () => {
5 return (
6 <>
7 <ChatBox />
8 <SendMessage />
9 </>
10 );
11};
12export default Chat;
Next, create a new folder called Routes
. Inside this new folder, create a file named PrivateRoute.jsx
, and add the following code inside it:
1import React from "react";
2import { Navigate } from "react-router-dom";
3import { UserAuth } from "../context/AuthContext";
4export const PrivateRoute = ({ children }) => {
5 const { currentUser } = UserAuth();
6 if (!currentUser) {
7 return <Navigate to="/" replace={true} />;
8 }
9 return children;
10};
The code above defines a private route component that ensures authentication before allowing access to the specified path. Now, to execute your frontend, navigate to App.jsx
and replace the existing code with the following:
1import Login from "./pages/login";
2import Nav from "./Components/Nav";
3import Chat from "./pages/Chat";
4import { Routes, Route } from "react-router-dom";
5import { PrivateRoute } from "./Routes/PrivateRoute";
6function App() {
7 return (
8 <AuthProvider>
9 <Nav />
10 <Routes>
11 <Route path="/" element={<Login />} />
12 <Route
13 path="/Chat"
14 element={
15 <PrivateRoute>
16 <Chat />
17 </PrivateRoute>
18 }
19 />
20 </Routes>
21 </AuthProvider>
22 );
23}
24export default App;
Before diving into Firebase setup, understand what Firebase is and how it fits into this project.
According to Wikipedia, Firebase is a suite of back-end cloud computing services and application development platforms offered by Google. It provides databases, services, authentication, and integration for various apps, including Android, iOS, JavaScript, Node.js, Java, Unity, PHP, and C++.
Firebase is a NoSQL database program that stores data in JSON-style documents. In this project, you will use Firebase for user authentication.
Next, log in to Firebase or create an account if you're new. To create a new Firebase project, go to the Firebase Console, click Add project, and follow the prompts. In this tutorial, you'll name your project strapichat
. Disable Google Analytics and click Create project.
Click the Web option to begin setting up Firebase. The third icon, which resembles a code icon, represents this option and register the app.
Perform the following actions when you click on the Web option:
Step 2: Copy the Firebase configuration given to you.
Afterward, create a file named firebase.jsx
inside the src
folder and paste all the code provided during the Firebase project creation step:
1// Import the functions you need from the SDKs you need
2import { initializeApp } from "firebase/app";
3import { getAuth } from "firebase/auth";
4// Your web app's Firebase configuration
5const firebaseConfig = {
6 apiKey: "AIzaSyCbdtBIaoTLgo1SUEmsfPLHA_4KuptMiTg",
7 authDomain: "strapichat.firebaseapp.com",
8 projectId: "strapichat",
9 storageBucket: "strapichat.appspot.com",
10 messagingSenderId: "1025219426688",
11 appId: "1:1025219426688:web:912f11e71bb818a6922965",
12};
13// Initialize Firebase
14const app = initializeApp(firebaseConfig);
NOTE: Replace the configurations with the one provided to you by Firebase
The code above initializes Firebase in your React app. Next, run the following command to install the latest SDK:
npm install firebase
Click Next.
npm install -g firebase-tools
After creating your Firebase project, please navigate to the Firebase Console dashboard and select it. From the left sidebar menu, choose Authentication to access the authentication section. Here, you'll find a list of available authentication methods. Click on Get Started to activate the authentication methods you want for your project.
Firebase offers various authentication mechanisms, including email/password, Google, Facebook, Twitter, and more. You'll be utilizing Google authentication, so select and enable the Google authentication method.
Next, navigate to the firebase.jsx
file inside the src
folder and replace the code:
1// Import the functions you need from the SDKs you need
2import { initializeApp } from "firebase/app";
3import { getAuth } from "firebase/auth";
4// Your web app's Firebase configuration
5const firebaseConfig = {
6 apiKey: "AIzaSyCbdtBIaoTLgo1SUEmsfPLHA_4KuptMiTg",
7 authDomain: "strapichat.firebaseapp.com",
8 projectId: "strapichat",
9 storageBucket: "strapichat.appspot.com",
10 messagingSenderId: "1025219426688",
11 appId: "1:1025219426688:web:912f11e71bb818a6922965",
12};
13// Initialize Firebase
14const app = initializeApp(firebaseConfig);
15export const auth = getAuth(app);
NOTE: Replace the configuration
In the provided code, you imported getAuth
from Firebase, which retrieves a reference to the Firebase Authentication service instance. Next, create a folder named context
inside the src
directory and then create a new file called AuthContext.jsx
, and paste the following code inside it:
1import { createContext, useState, useEffect, useContext } from "react";
2import {
3 GoogleAuthProvider,
4 onAuthStateChanged,
5 signInWithRedirect,
6 signOut,
7} from "firebase/auth";
8import { auth } from "../firebase";
9//create context
10const AuthContext = createContext();
11//provider context
12export const AuthProvider = ({ children }) => {
13 const [currentUser, setCurrentUSer] = useState("");
14 const [loading, setLoading] = useState(true);
15 // signin with google
16 const signInWithGoogle = () => {
17 const provider = new GoogleAuthProvider();
18 signInWithRedirect(auth, provider);
19 };
20 // signout from google
21 const logout = () => signOut(auth);
22 const value = {
23 currentUser,
24 setCurrentUSer,
25 signInWithGoogle,
26 logout,
27 };
28 // set currentUser
29 useEffect(() => {
30 const unsubscribe = onAuthStateChanged(auth, (user) => {
31 setCurrentUSer(user);
32 setLoading(false);
33 });
34 return unsubscribe;
35 }, []);
36 return (
37 <AuthContext.Provider value={value}>
38 {!loading && children}
39 </AuthContext.Provider>
40 );
41};
42export const UserAuth = () => {
43 return useContext(AuthContext);
44};
The code above sets up a flexible authentication system using Firebase in your React application. It manages the authentication state, initializes state variables for the current user, a loading status, and provides functions for signing in with Google and logging out.
In this phase, you will integrate your Strapi backend with Firebase in your React app. Open the Login.jsx
file located in the pages
folder within your src
directory, and add the following code to it:
1import React, { useEffect, useState } from "react";
2import { UserAuth } from "../context/AuthContext";
3import { useNavigate } from "react-router-dom";
4const Login = () => {
5 const navigate = useNavigate();
6 const { currentUser, signInWithGoogle } = UserAuth();
7 const [displayName, setDisplayName] = useState("");
8 const [uid, setUid] = useState("");
9 const [email, setEmail] = useState("");
10 const handleLogin = async () => {
11 try {
12 await signInWithGoogle();
13 } catch (error) {
14 console.log("Error signing in:", error);
15 }
16 };
17 useEffect(() => {
18 // Check if currentUser exists
19 if (currentUser) {
20 const fetchUserData = async () => {
21 try {
22 // Destructure currentUser to get necessary details
23 const { displayName, uid, email } = currentUser;
24 // Update state with the user details
25 setDisplayName(displayName);
26 setUid(uid);
27 setEmail(email);
28 // Send user details to Strapi API
29 await fetch("http://localhost:1337/api/accounts", {
30 method: "POST",
31 headers: {
32 "Content-Type": "application/json",
33 },
34 body: JSON.stringify({
35 data: {
36 uid: uid,
37 Username: displayName,
38 Email: email,
39 },
40 }),
41 })
42 .then((response) => response.json())
43 .then((data) => {
44 console.log("Data from Strapi API:", data);
45 // navigate to another page after sending data
46 navigate("/Chat");
47 })
48 .catch((error) => {
49 console.log("Error sending user data to Strapi API:", error);
50 });
51 } catch (error) {
52 console.log("Error setting user data:", error);
53 }
54 };
55 // Call fetchUserData function
56 fetchUserData();
57 }
58 }, [currentUser, navigate]); // Include currentUser and navigate in the dependency array
59 return (
60 <div className="hero min-h-screen bg-base-200">
61 <div className="hero-content text-center">
62 <div className="max-w-md">
63 <h1 className="text-5xl font-bold">Welcome to Strapi ChatRomm</h1>
64 <p className="py-6">
65 Join the conversation, meet new people, and make connections in one
66 shared room.
67 </p>
68 <button onClick={handleLogin} className="btn btn-primary">
69 LOGIN WITH GOOGLE
70 </button>
71 </div>
72 </div>
73 </div>
74 );
75};
76export default Login;
The code above handles the login process using Google sign-in via Firebase authentication. It retrieves the user's information, sends it to Strapi if successfully signed, and redirects the user to the Chat page, where users can start communication.
To read chat messages, you need to send a request to Strapi to retrieve messages. To do this, navigate to the Components/ChatBox.jsx
file in your src
directory and add the following code:
1import React from "react";
2import Message from "./Message";
3import { useState, useRef, useEffect } from "react";
4const ChatBox = () => {
5 const messagesEndRef = useRef();
6 const [messages, setMessages] = useState([]);
7 const scrollToBottom = () => {
8 messagesEndRef.current.scrollIntoView({ behaviour: "smooth" });
9 };
10 useEffect(scrollToBottom, [messages]);
11 useEffect(() => {
12 const interval = setInterval(() => {
13 fetch("http://localhost:1337/api/chat-room-messages", {
14 method: "GET",
15 headers: {
16 "Content-Type": "application/json",
17 },
18 })
19 .then((response) => response.json())
20 .then((res) => setMessages(res.data));
21 }, 5000);
22 return () => clearInterval(interval);
23 }, []);
24 return (
25 <div className="pb-44 pt-20 container">
26 {messages.map((message, id) => (
27 <Message key={id} message={message} />
28 ))}
29 <div ref={messagesEndRef}></div>
30 </div>
31 );
32};
33export default ChatBox;
As explained earlier and as seen in the code above, the ChatBox
component displays individual chat messages in the Strapi chatroom, including the username and user photo.
The first useEffect
hook is called whenever the messages
state changes. It scrolls to the bottom of the chatbox.
The second useEffect
hook runs once after the component mounts. It fetches chat room messages from a local server endpoint http://localhost:1337/api/chat-room-messages
, every 5 seconds using setInterval
. Upon receiving the response, it updates the messages
state.
To render your chat messages, navigate to Components/Messages.jsx
in your src
folder and replace the file with the following code:
1import React from "react";
2import { UserAuth } from "../context/AuthContext";
3const Message = ({ message }) => {
4 const { currentUser } = UserAuth();
5 return (
6 <div>
7 <div
8 className={`chat ${
9 message.attributes.User === currentUser.displayName
10 ? "chat-start"
11 : "chat-end"
12 }`}
13 >
14 <div className="chat-image avatar">
15 <div className="w-10 rounded-full">
16 <img alt="User Avatar" src={message.attributes.Photo} />
17 </div>
18 </div>
19 <div className="chat-header">{message.attributes.User}</div>
20 <div className="chat-bubble">{message.attributes.message}</div>
21 </div>
22 </div>
23 );
24};
25export default Message;
To create and post new messages to Strapi, you must capture user input and send it to your Strapi backend. To accomplish this, navigate to the Components/SendMessage.jsx
file in your src
directory and insert the following code:
1import React, { useState } from "react";
2import { UserAuth } from "../context/AuthContext";
3const SendMessage = () => {
4 const [value, setValue] = useState("");
5 const { currentUser } = UserAuth();
6 const [displayName, setDisplayName] = useState("");
7 const [photoURL, setPhotoURL] = useState("");
8 const handleSendMessage = (e) => {
9 e.preventDefault();
10 console.log(value);
11 if (value.trim === "") {
12 alert("Enter valid message!");
13 return;
14 }
15 try {
16 const { displayName, photoURL } = currentUser;
17 if (currentUser) {
18 fetch("http://localhost:1337/api/chat-room-messages", {
19 method: "POST",
20 headers: {
21 "Content-Type": "application/json",
22 },
23 body: JSON.stringify({
24 data: {
25 message: value,
26 User: displayName,
27 Photo: photoURL,
28 },
29 }),
30 })
31 .then((response) => response.json())
32 .then((data) => console.log(data));
33 }
34 } catch (error) {
35 console.log(error);
36 }
37 setValue("");
38 setDisplayName(displayName);
39 setPhotoURL(photoURL);
40 console.log(currentUser);
41 };
42 return (
43 <div className="bg-gray-200 fixed w-full py-10 shadow-lg bottom-0">
44 <form onSubmit={handleSendMessage} className="container flex px-2">
45 <input
46 className="input w-full focus:outline-none bg-gray-100 rounded-r-none"
47 type="text"
48 value={value}
49 onChange={(e) => setValue(e.target.value)}
50 />
51 <button className="w-auto bg-gray-500 text-white rounded-r-lg px-5 text-sm">
52 Send
53 </button>
54 </form>
55 </div>
56 );
57};
58export default SendMessage;
The code above allows users to compose and send messages within your chat application. When a user sends a message, the message content, along with the user's display name and photo URL obtained from Firebase authentication, is sent to Strapi using a POST
request. This function ensures the message gets stored in the Strapi backend for further processing, retrieval or customization.
Your app should look like this:
Since your application data depends on Strapi, you must start your Strapi server before your application launches. To accomplish this, open a new terminal window, navigate to the directory of your Strapi app, and launch the application by running the command below:
npm run develop
Open your React app terminal window and run the following command as well:
npm run dev
The image below demonstrates the success of your chat application:
The short clip above shows how users exchange messages, facilitating real-time communication.
Feel free to add more features to enhance the appearance and functionality of your chat app.
Congratulations on fully implementing your Strapi chat app! Building a chat application using React, Strapi, and Firebase combines powerful front-end and back-end technologies. Strapi provides flexibility in handling data and APIs, while React offers a robust foundation for constructing user interfaces. Firebase enhances the application by providing user authentication. With these tools, you can create dynamic and interactive chat applications.