Quickstarters
How to Build a React Frontend and Connect It to a Backend?
35 min
in this tutorial, you’ll create a to do list application using react and connect it to a backend service this project is an ideal starting point because it involves fundamental crud (create, read, update, delete) operations and a straightforward user interface by the end, you’ll have a fully functional app with a connected backend, demonstrating how to integrate managed backend services into your development workflow building a full stack application from scratch often requires setting up a backend, managing a database, handling authentication, and deploying infrastructure these tasks can be complex and time consuming, especially if you’re focused on frontend development and we will use back4app for this purpose back4app simplifies this process by providing a scalable backend as a service (baas) solution, allowing you to focus on building your application while it handles hosting, databases, and apis back4app offers backend services, including a ready to use database, authentication, cloud code for server side logic, and sdks for seamless integration it also supports containerized deployments, making it a flexible choice for hosting full stack applications with these features, you can quickly build and deploy applications without managing server infrastructure key takeaways by reading this article you will learn to set up a modern react project using industry standard tools seamlessly integrate a backend service to manage application data implement essential crud operations for a dynamic user experience deploy a fully functional todo application and see it running on todo app prerequisites to follow this tutorial effectively, ensure you have the following tools and skills node js and npm installed on your machine you'll use npm to install dependencies and run your react application verify your installation by running node v and npm v in your terminal basic react knowledge , including functional components, state management with hooks, and handling user input this tutorial won’t cover react fundamentals, so familiarity with jsx and component structure is expected a back4app account to set up and manage your backend services sign up at back4app https //www back4app com/ if you don’t have an account with these in place, you're ready to set up your project and start building project setup to get started, you need to set up your local development environment and initialize your frontend project using vite this ensures a fast and efficient development experience while keeping your project structure clean first, ensure you have node js (lts version) installed if not, download it from nodejs org https //nodejs org/ and install it once installed, verify it by running node v npm v now, initialize your react project using vite , a modern build tool that offers superior speed compared to create react app run the following command in your terminal, replacing todo app with your preferred project name npm create vite\@latest todo app template react navigate into the project folder cd todo app install the necessary dependencies npm install start the development server to verify the setup npm run dev this launches your react app locally open the provided url in your browser to confirm it's running with your frontend set up, the next step is creating a backend on back4app to handle data storage and api interactions creating the todo backend back4app provides a fully managed backend service powered by parse , offering a nosql database, authentication, cloud code, and api generation out of the box this allows you to manage your app’s data without building a backend from scratch you'll create a task data model to store to do list items and connect it to your react frontend creating a backend application log in to your back4app dashboard https //www back4app com/ and click "create a new app " enter a name for your application (e g , todoapp ) and select nodejs/parse as the backend type once created, go to "database" > "browser" , click "create a class" , and choose "custom" name it task and set the class level permissions to allow public read and write (you can refine this later) in the task class, add the following fields title (string) – task title description (string) – task details completed (boolean) – completion status duedate (date) – task deadline click "save" to create the schema connecting back4app to react now, integrate back4app into your react project using the parse javascript sdk to communicate with the backend install it via npm npm install parse next, configure the sdk by initializing it with your application id and javascript key retrieve these credentials from the back4app dashboard under the app settings > security & keys section back4app keys page with app id and js key highlighted inside src/main jsx , configure parse by importing the minified sdk and initializing it with your application id and javascript key import parse from 'parse/dist/parse min js'; const parse app id = 'your application id'; const parse js key = 'your javascript key'; const parse server url = 'https //parseapi back4app com/'; parse initialize(parse app id, parse js key); parse serverurl = parse server url; with your backend connected, you can build the to do list ui and integrate crud operations developing the frontend now that your backend is set up and connected, it's time to build the to do list ui in react you’ll create components for adding, displaying, updating, and deleting tasks while efficiently managing state structuring the components your application will consist of three key components taskform jsx – handles adding new tasks tasklist jsx – displays all tasks and provides controls for marking tasks as complete or deleting them taskitem jsx – represents a single task with actions like marking as complete or deleting start by creating a components folder inside src and add these files mkdir src/components touch src/components/taskform jsx src/components/tasklist jsx src/components/taskitem jsx managing state you'll use the usestate and useeffect hooks to manage tasks locally while fetching and updating data from back4app first, define the state inside app jsx import { usestate, useeffect } from "react"; import parse from "parse/dist/parse min js"; import taskform from " /components/taskform"; import tasklist from " /components/tasklist"; function app() { const \[tasks, settasks] = usestate(\[]); useeffect(() => { fetchtasks(); }, \[]); const fetchtasks = async () => { try { const task = parse object extend("task"); const query = new parse query(task); const results = await query find(); settasks(results map((task) => ({ id task id, task tojson() }))); } catch (error) { console error("error fetching tasks ", error); } }; return ( \<div classname="container"> \<h1>to do list\</h1> \<taskform fetchtasks={fetchtasks} /> \<tasklist tasks={tasks} fetchtasks={fetchtasks} /> \</div> ); } export default app; creating the task form inside taskform jsx , create a controlled form to add new tasks this will store input values in state and submit data to back4app import { usestate } from "react"; import parse from "parse/dist/parse min js"; function taskform({ fetchtasks }) { const \[title, settitle] = usestate(""); const \[description, setdescription] = usestate(""); const handlesubmit = async (e) => { e preventdefault(); try { const task = parse object extend("task"); const task = new task(); task set("title", title); task set("description", description); task set("completed", false); await task save(); fetchtasks(); settitle(""); setdescription(""); } catch (error) { console error("error adding task ", error); } }; return ( \<form onsubmit={handlesubmit}> \<input type="text" placeholder="task title" value={title} onchange={(e) => settitle(e target value)} required /> \<input type="text" placeholder="description" value={description} onchange={(e) => setdescription(e target value)} required /> \<button type="submit">add task\</button> \</form> ); } export default taskform; displaying tasks inside tasklist jsx , render the list of tasks and include actions for marking them as completed and deleting them import taskitem from " /taskitem"; function tasklist({ tasks, fetchtasks }) { return ( \<div> {tasks length === 0 ? ( \<p>no tasks available\</p> ) ( tasks map((task) => ( \<taskitem key={task id} task={task} fetchtasks={fetchtasks} /> )) )} \</div> ); } export default tasklist; task item component inside taskitem jsx , define actions to mark a task as complete or delete it from back4app import parse from "parse/dist/parse min js"; function taskitem({ task, fetchtasks }) { const handlecomplete = async () => { try { const query = new parse query("task"); const tasktoupdate = await query get(task id); tasktoupdate set("completed", !task completed); await tasktoupdate save(); fetchtasks(); } catch (error) { console error("error updating task ", error); } }; const handledelete = async () => { try { const query = new parse query("task"); const tasktodelete = await query get(task id); await tasktodelete destroy(); fetchtasks(); } catch (error) { console error("error deleting task ", error); } }; return ( \<div classname={`task item ${task completed ? "completed" ""}`}> \<h3>{task title}\</h3> \<p>{task description}\</p> \<button onclick={handlecomplete}> {task completed ? "undo" "complete"} \</button> \<button onclick={handledelete}>delete\</button> \</div> ); } export default taskitem; styling the application create a styles css file in src and add basic styling / container to center the content and add some spacing / container { max width 600px; margin 40px auto; padding 0 20px; text align center; font family sans serif; } / make the heading stand out and add spacing below it / container h1 { margin bottom 20px; } / style the form so that inputs and the button are nicely spaced and aligned / form { display flex; flex direction column; align items center; gap 10px; margin bottom 20px; } / make the text inputs fill a reasonable width and add padding / form input\[type="text"] { width 80%; max width 400px; padding 8px; box sizing border box; font size 1rem; } / style the 'add task' button / form button { padding 8px 16px; cursor pointer; font size 1rem; border none; background color #eaeaea; transition background color 0 2s ease; } form button\ hover { background color #ccc; } / basic text styles for empty task list message / container p { font size 1rem; } / task item container \ centered in both directions (flex + align items/justify content) \ a gap between elements for visual breathing room / task item { display flex; flex direction column; align items center; justify content center; gap 12px; border 1px solid #ccc; border radius 6px; padding 15px; margin 10px 0; background color #fafafa; text align center; / centers text for titles/descriptions / transition background color 0 2s ease; } / completed tasks visually differ strikethrough and grey text / task item completed h3, task item completed p { text decoration line through; color #888; } / task title / task item h3 { margin 0; font size 1 1rem; } / task description / task item p { margin 0; font size 1rem; } / buttons within each task item (centered and with some spacing) / task item button { padding 6px 12px; border none; background color #eaeaea; cursor pointer; font size 0 9rem; } task item button\ hover { background color #ccc; } / on wider screens, you can display elements in a row but keep them centered adjust justify content/align items if you want them spaced differently / @media (min width 600px) { task item { flex direction row; } } import this css in main jsx import " /styles css"; the ui of the application your to do list app now has a working frontend with a react ui, back4app integration, and basic styling finished todo list app next, you’ll deploy this frontend to back4app web deployment deploying the frontend on back4app web deployment back4app web deployment provides a fully managed, containerized environment for deploying applications it supports docker based deployments , allowing you to package your frontend into a container and run it on back4app’s infrastructure this ensures scalability, security, and an easy ci/cd pipeline by integrating directly with github configuring vite for containerization vite serves applications in a development mode by default for production, you need to build a static version and serve it using a lightweight web server like nginx first, update vite config js to specify a proper base path for deployment import { defineconfig } from 'vite'; import react from '@vitejs/plugin react'; export default defineconfig({ plugins \[react()], base ' /', // ensures correct asset paths in a containerized environment }); now, run the build command to generate production ready files npm run build creating a dockerfile for deployment a dockerfile defines how your react app is containerized create a file named dockerfile in the root of your project and add the following configuration \# use an official lightweight node js image from node 18 alpine as build \# set working directory workdir /app \# copy package json and install dependencies copy package json package lock json / run npm install \# copy project files copy \# build the project run npm run build \# use an nginx server for efficient static file serving from nginx\ alpine copy from=build /app/dist /usr/share/nginx/html \# expose port 80 expose 80 \# start nginx cmd \["nginx", " g", "daemon off;"] this dockerfile does the following uses node js to install dependencies and build the react app copies the built files into an nginx container for efficient static file serving exposes port 80 to serve the application building and testing the container locally before deploying, test the container locally to ensure it works as expected run the following command to build the docker image docker build t todo frontend then, start a container using docker run p 8080 80 todo frontend open http //localhost 8080 in your browser to confirm that your react app is served correctly pushing to github and connecting to back4app to deploy on back4app, first, push your project to github git init git add git commit m "initial commit for back4app deployment" git branch m main git remote add origin \<your github repository url> git push u origin main now, follow these steps to deploy via back4app web deployment platform log in to back4app web deployment https //www back4app com/containers click "create new app" , name your project, and select github repository authorize back4app to access your github and select the todo app repository choose dockerfile deployment and confirm the build settings click "deploy" to trigger the first build managing and monitoring deployments once deployed, navigate to your app in the back4app dashboard here, you can view logs to debug issues monitor container restarts and resource usage redeploy on new commits using the "trigger build" button configure custom domains if hosting on a personal domain back4app web deployment dashboard deployed application you can access the deployed application used in this tutorial at https //todoapp ku5ofg8s b4a run/ https //todoapp ku5ofg8s b4a run/ https //todoapp ku5ofg8s b4a run/ with your front end successfully deployed, the next step is testing and debugging to ensure everything runs smoothly testing and debugging after deploying your front end and back end, you need to ensure that the application functions correctly this involves testing the frontend backend interaction , identifying common issues, and debugging errors effectively integrated application testing to verify that your react frontend interacts properly with the back4app backend, follow these steps test api connectivity open your browser’s developer console ( f12 → network tab ) and check for api calls when adding or fetching tasks if api requests fail, inspect the response status and error messages manually add and retrieve tasks use the to do list ui to add a task refresh the page to ensure the task persists open the back4app database browser and confirm that the task appears under the task class check crud operations complete and delete tasks from the ui, then verify changes in back4app’s database if updates don’t reflect, check for errors in the browser console or api logs test edge cases try submitting empty tasks to ensure validation works simulate slow internet connections ( chrome devtools → network → slow 3g ) to test performance common issues & troubleshooting cors errors ( access control allow origin issue) go to back4app dashboard > app settings > security & keys under "allowed headers and domains" , add your frontend’s url save and restart the backend authentication failures (401 unauthorized errors) ensure that the application id and javascript key are correctly configured in your react app if using user authentication, check that the session token is included in api requests backend deployment issues if the api is unresponsive, navigate to back4app web deployment > logs to check for errors in your backend deployment restart the container if needed with testing and debugging complete, the next step is implementing best practices for using back4app services to optimize performance and maintainability best practices for using back4app services here are some best practices you can follow when using back4app optimizing frontend backend interaction efficient communication between your frontend and back4app’s backend ensures a smooth user experience use batch requests when performing multiple operations to reduce network overhead const tasks = \[task1, task2, task3]; parse object saveall(tasks); for read operations, enable caching and set up indexed queries in the back4app dashboard to speed up frequent requests always request only necessary fields to minimize response size query select("title", "completed"); environment & scaling store sensitive keys, such as application id and javascript key , in environment variables instead of hardcoding them if using vite , create a env file vite parse app id=your app id vite parse js key=your js key in production, enable auto scaling for back4app web deployment to handle increased traffic monitor database usage and optimize queries using the performance monitoring tool in back4app enhanced security & performance restrict class level permissions (clps) so only authenticated users can modify data set read/write permissions dynamically based on user roles task setacl(new parse acl(parse user current())); use cloud code to offload complex business logic from the frontend, reducing api exposure and improving performance finally, enable rate limiting and request validation to prevent abuse and ensure data integrity conclusion you have now built a full stack to do list application by setting up a react frontend, integrating it with back4app’s backend, and deploying via containerized workflows this process demonstrated a clear path from local development to cloud deployment, ensuring smooth frontend backend interaction looking ahead, consider enhancements like advanced user management, real time updates, and third party integrations for further learning, explore the back4app documentation https //www back4app com/docs and community support resources