Quickstarters
How to Build a Preact Frontend and Connect It to a Backend?
33 min
in this tutorial, you’ll build a to do list application using preact and connect it to a robust backend provided by back4app this guide is perfect for getting started because it covers core crud (create, read, update, delete) operations and walks you through creating a clean, functional ui by the end, you’ll have a fully operational app that shows you how to integrate a managed backend while using preact for a lightweight and fast frontend building a full stack application can be complex, especially when dealing with backend setup, database management, authentication, and deployment to simplify these challenges, we use back4app—a scalable backend as a service (baas) solution—so you can focus on developing your frontend while it handles hosting, databases, and apis back4app delivers comprehensive backend services including a ready to use database, authentication, cloud code for server side logic, and sdks for smooth integration it also supports containerized deployments, making it an excellent choice for modern full stack applications with these resources, you can rapidly develop and deploy applications without the burden of managing server infrastructure key takeaways by following this tutorial you will learn to initialize a modern preact project using vite integrate a backend service to manage your application’s data implement core crud operations for an interactive user interface deploy a fully functional to do list application using containerized workflows on back4app prerequisites before you start, ensure you have the following node js and npm install the latest lts version of node js from nodejs org https //nodejs org/ and verify by running node v and npm v in your terminal basic preact knowledge familiarity with functional components, hooks (like usestate and useeffect ), and jsx syntax is expected if you’re new to preact, consider reviewing its basics first a back4app account sign up at back4app https //www back4app com/ to set up and manage your backend services with these prerequisites in place, you’re ready to set up your project and start building project setup start by setting up your local development environment and initializing your preact project using vite for a streamlined development experience confirm that node js (lts version) is installed if needed, download and install it from nodejs org https //nodejs org/ verify by running node v npm v initialize your preact project using vite run the following command in your terminal (replace todo app with your preferred project name) npm create vite\@latest todo app template preact navigate into your project directory cd todo app install the required dependencies npm install start the development server to verify your setup npm run dev your preact application should now be running locally open the provided url in your browser to confirm next, you’ll set up your backend on back4app to manage data storage and api interactions creating the todo backend back4app offers a fully managed backend service powered by parse , which provides a nosql database, authentication, cloud code, and auto generated apis out of the box this section will guide you through creating a task data model to store your to do items and connecting it to your preact frontend setting up your backend application log in to your back4app dashboard https //www back4app com/ and click "create a new app " name your application (for example, todopreactapp ) and choose nodejs/parse as the backend type once the app is created, navigate to "database" > "browser" click "create a class" and select "custom" name the class task and set the class level permissions to allow public read and write (you can adjust these settings later) in the task class, add the following fields title (string) – the task title description (string) – details about the task completed (boolean) – indicates whether the task is finished duedate (date) – the deadline for the task click "save" to complete your schema setup integrating back4app with preact integrate back4app into your preact project using the parse javascript sdk install the sdk via npm npm install parse configure the sdk by initializing it with your application id and javascript key retrieve these credentials from your back4app dashboard under app settings > security & keys in your src/main jsx , import and configure parse as follows import { render } from 'preact' import ' /index css' import app from ' /app jsx' 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; render(\<app />, document getelementbyid('app')) with the backend connected, you’re ready to build the to do list ui in preact and implement crud operations developing the frontend with preact now that your backend is configured, build the user interface for your to do list application using preact you’ll create components to add, display, update, and delete tasks while managing state with hooks organizing your components your application will include the following key components taskform jsx – manages the addition of new tasks tasklist jsx – displays all tasks and provides controls to complete or delete them taskitem jsx – represents an individual task with actions to toggle completion or remove the task create 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 with hooks use preact’s hooks ( usestate and useeffect ) for state management and side effects begin by setting up state in app jsx import { usestate, useeffect } from "preact/hooks"; import taskform from " /components/taskform jsx"; import tasklist from " /components/tasklist jsx"; import parse from "parse/dist/parse min js"; function app() { const \[tasks, settasks] = usestate(\[]); 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); } }; useeffect(() => { fetchtasks(); }, \[]); return ( \<div class="container"> \<h1>to do list\</h1> \<taskform fetchtasks={fetchtasks} /> \<tasklist tasks={tasks} fetchtasks={fetchtasks} /> \</div> ); } export default app; building the task form component in taskform jsx , create a controlled form for adding tasks use usestate to manage input values and submit data to back4app import { usestate } from "preact/hooks"; 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} oninput={(e) => settitle(e target value)} required /> \<input type="text" placeholder="description" value={description} oninput={(e) => setdescription(e target value)} required /> \<button type="submit">add task\</button> \</form> ); } export default taskform; displaying the task list in tasklist jsx , render the list of tasks by mapping through the tasks array and using the taskitem component import taskitem from " /taskitem jsx"; 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; creating the task item component in taskitem jsx , create a component that allows you to mark a task as complete or delete it 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 class={`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 your application add the following styles in the index css file in the src folder / container styling / container { max width 600px; margin 40px auto; padding 0 20px; text align center; font family sans serif; } container h1 { margin bottom 20px; } form { display flex; flex direction column; align items center; gap 10px; margin bottom 20px; } form input\[type="text"] { width 80%; max width 400px; padding 8px; box sizing border box; font size 1rem; } 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; } container p { font size 1rem; } 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; transition background color 0 2s ease; } task item completed h3, task item completed p { text decoration line through; color #888; } task item h3 { margin 0; font size 1 1rem; } task item p { margin 0; font size 1rem; } task item button { padding 6px 12px; border none; background color #eaeaea; cursor pointer; font size 0 9rem; } task item button\ hover { background color #ccc; } @media (min width 600px) { task item { flex direction row; } } import this css in your src/main jsx import " /index css"; finalizing the ui your preact to do list application now features a dynamic frontend integrated with back4app and custom styling the app allows you to add, display, update, and delete tasks while maintaining efficient frontend backend communication next, you’ll deploy your preact app using back4app’s web deployment platform deploying the frontend on back4app web deployment back4app web deployment provides a fully managed, containerized environment for deploying your applications with docker based deployments, you can package your preact frontend and deploy it effortlessly configuring vite for production preact projects built with vite run in development mode by default for production, build a static version and serve it using a lightweight web server such as nginx update your vite config js to set the correct base path import { defineconfig } from 'vite'; import preact from '@preact/preset vite'; export default defineconfig({ plugins \[preact()], base ' /', // ensures asset paths are correct in a containerized environment }); generate production ready files npm run build creating a dockerfile for your app create a dockerfile in the root directory to define your container \# build stage using a lightweight node js image from node 18 alpine as build workdir /app copy package json package lock json / run npm install copy run npm run build \# production stage using nginx to serve static files from nginx\ alpine copy from=build /app/dist /usr/share/nginx/html expose 80 cmd \["nginx", " g", "daemon off;"] testing the container locally before deploying, build and test your docker container locally docker build t todo preact frontend run the container docker run p 8080 80 todo preact frontend visit http //localhost 8080 in your browser to confirm that your app is served correctly pushing to github and deploying via back4app 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 then, deploy using back4app web deployment log in to back4app web deployment https //www back4app com/containers click "create new app" , provide a name, and select github repository authorize back4app to access your repository and select the todo preact repo choose dockerfile deployment and confirm the build settings click "deploy" to initiate the build process monitoring and managing deployments after deployment, use the back4app dashboard to view logs for troubleshooting monitor container performance and resource usage trigger redeployments on new commits configure custom domains if needed testing and debugging your application after deployment, thoroughly test your preact app verify api connectivity open your browser’s developer console (f12 → network) to monitor api calls during task operations add and retrieve tasks use the ui to add tasks, then refresh the page to verify persistence in the back4app database browser test crud operations ensure that marking tasks complete and deletion are properly reflected in the backend edge case handling validate form inputs and simulate slow network conditions using developer tools if you encounter issues, review the back4app logs or check your api configuration best practices for using back4app services improve your application’s performance and security by following these best practices optimize api calls use batch requests for multiple operations and select only necessary fields in your queries secure sensitive data store credentials like application id and javascript key in environment variables with vite, create a env file vite parse app id=your app id vite parse js key=your js key enable auto scaling activate auto scaling in back4app web deployment to manage high traffic enhance security restrict class level permissions (clps) to control data modifications and set up acls as needed utilize cloud code offload complex logic to cloud code for better performance and reduced api exposure conclusion you have now built a full stack to do list application using preact for the frontend and back4app’s robust backend services this tutorial guided you through initializing a preact project, integrating the parse sdk, and deploying your app using containerized workflows on back4app as you continue developing, consider adding features such as advanced user authentication, real time updates, and third party integrations for additional details and support, refer to the back4app documentation https //www back4app com/docs