Quickstarters
CRUD Samples
How to Create a Basic CRUD App with Preact?
48 min
overview in this guide, you'll develop a crud (create, read, update, and delete) application using preact we will walk you through building a system that handles basic data operations, from initializing a back4app project named basic crud app preact to managing data effortlessly this project provides a robust backend and a sleek, minimal frontend built with preact we'll begin by setting up a new project on back4app, then craft an efficient database schema—either manually or with the help of the back4app ai assistant this design will support all essential crud functionalities next, we introduce the back4app admin app, a drag and drop interface that simplifies data management you can quickly add, modify, or remove records using this tool finally, you will connect your preact frontend to back4app using rest/graphql , ensuring your backend is secure with advanced access rules by the end of this tutorial, you'll have a production ready web application featuring user authentication and robust data management—all built with preact and powered by back4app main insights master building crud applications that efficiently manage data using a dependable backend learn to design a scalable data model and integrate it with a preact frontend for an optimal user experience discover how the drag and drop back4app admin app simplifies create, read, update, and delete operations understand deployment strategies, including containerization with docker, to quickly launch your application prerequisites before starting, please make sure you have a back4app account and an initialized project for guidance, check out getting started with back4app https //www back4app com/docs/get started/new parse app a preact development environment use tools like preact cli https //github com/preactjs/preact cli or equivalent, ensuring node js (v14 or later) is installed basic knowledge of javascript, preact, and rest apis refer to the preact documentation https //preactjs com/guide/v10/ if needed step 1 – setting up your project initializing a back4app project sign in to your back4app account select the “new app” option on your dashboard name your project basic crud app preact and follow the setup prompts create new project after creation, your project will be visible on your back4app dashboard, laying the groundwork for backend configuration step 2 – crafting your database schema structuring your data model for our crud app, you'll need several collections below are examples that outline the collections and fields essential for supporting crud operations 1\ items collection this collection keeps details about each item field data type purpose id objectid auto generated primary key title string the name of the item description string a short description of the item created at date the creation timestamp updated at date last update timestamp 2\ users collection this holds user credentials and profile details field data type purpose id objectid auto generated primary key username string unique username email string unique email address password hash string hashed password for authentication created at date account creation timestamp updated at date last account update timestamp you can create these collections manually via the back4app dashboard by adding a new class for each collection and defining the appropriate fields create new class you can add columns by selecting a data type, naming the column, and setting default values and required flags create column using the back4app ai assistant for schema creation the ai assistant available in back4app can auto generate your schema based on a prompt describing your collections and fields this feature expedites the setup and ensures consistency steps to use the ai assistant open the ai assistant from your back4app dashboard input a detailed description of your data model review the auto generated collections and field definitions, then apply them to your project sample prompt create these collections in my back4app project 1\) collection items \ fields \ id objectid (auto generated) \ title string \ description string \ created at date (auto generated) \ updated at date (auto updated) 2\) collection users \ fields \ id objectid (auto generated) \ username string (unique) \ email string (unique) \ password hash string \ created at date (auto generated) \ updated at date (auto updated) this approach saves time and guarantees a well structured schema step 3 – activating the admin app & managing crud operations introducing the admin app the back4app admin app provides a no code interface to manage your backend data effortlessly its drag and drop functionality enables you to perform crud operations without hassle activating the admin app go to the “more” menu in your back4app dashboard select “admin app” and click “enable admin app ” set up your first admin user, which will also configure roles like b4aadminuser and system collections enable admin app after activation, log in to the admin app to manage your data admin app dashboard performing crud actions with the admin app within the interface you can add records use the “add record” option in any collection (e g , items) to create new entries view and edit records select a record to see its details or modify its fields remove records delete entries that are no longer needed this intuitive tool enhances user experience by streamlining data management step 4 – connecting your preact frontend to back4app with the backend in place, it’s time to integrate your preact frontend option a utilizing the parse sdk install the parse sdk npm install parse set up parse in your preact project create a file (e g , src/parseconfig js ) // src/parseconfig js import parse from 'parse'; // insert your back4app credentials here parse initialize('your application id', 'your javascript key'); parse serverurl = 'https //parseapi back4app com'; export default parse; integrate parse in a preact component for instance, build a component to fetch and display items // src/components/itemslist js import { h } from 'preact'; import { useeffect, usestate } from 'preact/hooks'; import parse from ' /parseconfig'; const itemslist = () => { const \[items, setitems] = usestate(\[]); useeffect(() => { const fetchitems = async () => { const items = parse object extend("items"); const query = new parse query(items); try { const results = await query find(); setitems(results); } catch (error) { console error("error fetching items ", error); } }; fetchitems(); }, \[]); return ( \<div> \<h2>items\</h2> \<ul> {items map(item => ( \<li key={item id}> {item get("title")} — {item get("description")} \</li> ))} \</ul> \</div> ); }; export default itemslist; option b leveraging rest or graphql if the parse sdk is not viable, use rest or graphql for crud operations for instance, to fetch items via rest // sample rest call to retrieve items const fetchitems = async () => { try { const response = await fetch('https //parseapi back4app com/classes/items', { headers { 'x parse application id' 'your application id', 'x parse rest api key' 'your rest api key' } }); const data = await response json(); console log('fetched items ', data results); } catch (error) { console error('error fetching items ', error); } }; fetchitems(); integrate these api calls within your preact components as required step 5 – enhancing backend security using access control lists (acls) secure your data by assigning acls to your objects for instance, to create a private item async function createprivateitem(itemdata, owneruser) { const items = parse object extend('items'); const item = new items(); item set('title', itemdata title); item set('description', itemdata description); // configure acl only the owner has read/write access const acl = new parse acl(owneruser); acl setpublicreadaccess(false); acl setpublicwriteaccess(false); item setacl(acl); try { const saveditem = await item save(); console log('private item created ', saveditem); } catch (error) { console error('error saving item ', error); } } class level permissions (clps) within the back4app dashboard, adjust clps for each collection to restrict access to authenticated or authorized users only step 6 – implementing user authentication configuring user accounts back4app utilizes parse’s user class for managing authentication in your preact application, manage user sign up and login as follows // src/components/auth js import { h } from 'preact'; import { usestate } from 'preact/hooks'; import parse from ' /parseconfig'; export const signup = () => { const \[username, setusername] = usestate(''); const \[password, setpassword] = usestate(''); const \[email, setemail] = usestate(''); const handlesignup = async (e) => { e preventdefault(); const user = new parse user(); user set('username', username); user set('password', password); user set('email', email); try { await user signup(); alert('user registration successful!'); } catch (error) { alert('registration error ' + error message); } }; return ( \<form onsubmit={handlesignup}> \<input type="text" placeholder="username" value={username} onchange={e => setusername(e target value)} /> \<input type="password" placeholder="password" value={password} onchange={e => setpassword(e target value)} /> \<input type="email" placeholder="email" value={email} onchange={e => setemail(e target value)} /> \<button type="submit">sign up\</button> \</form> ); }; a similar method can be used for login and managing sessions additional features like social authentication and password recovery can be set up via the back4app dashboard step 7 – launching your preact frontend with web deployment back4app’s web deployment feature lets you host your preact application by linking a github repository in this part, you'll prepare your production build, commit your code, integrate with web deployment, and deploy your site 7 1 build your production files open your project directory in a terminal run the build command npm run build this generates a build folder with optimized static assets (html, js, css, images) 3\ confirm that the build folder includes an index html file and necessary assets 7 2 organize and commit your source code your repository should contain the complete preact frontend source code a sample directory structure basic crud app preact frontend/ ├── node modules/ ├── public/ │ └── index html ├── src/ │ ├── app js │ ├── parseconfig js │ └── components/ │ ├── itemslist js │ └── auth js ├── package json └── readme md example files src/parseconfig js // src/parseconfig js import parse from 'parse'; // enter your back4app credentials parse initialize('your application id', 'your javascript key'); parse serverurl = 'https //parseapi back4app com'; export default parse; src/app js // src/app js import { h } from 'preact'; import { useeffect, usestate } from 'preact/hooks'; import parse from ' /parseconfig'; function app() { const \[items, setitems] = usestate(\[]); const \[newitemtitle, setnewitemtitle] = usestate(""); const \[newitemdescription, setnewitemdescription] = usestate(""); const \[editingitemid, seteditingitemid] = usestate(null); const \[editingtitle, seteditingtitle] = usestate(""); const \[editingdescription, seteditingdescription] = usestate(""); const fetchitems = async () => { const items = parse object extend("items"); const query = new parse query(items); try { const results = await query find(); setitems(results); } catch (error) { console error("error fetching items ", error); } }; useeffect(() => { fetchitems(); }, \[]); const handleadditem = async () => { const items = parse object extend("items"); const item = new items(); item set("title", newitemtitle); item set("description", newitemdescription); try { await item save(); setnewitemtitle(""); setnewitemdescription(""); fetchitems(); } catch (error) { console error("error saving item ", error); } }; const handledeleteitem = async (id) => { try { const item = await parse object createwithoutdata("items", id); await item destroy(); fetchitems(); } catch (error) { console error("error deleting item ", error); } }; const starteditingitem = (item) => { seteditingitemid(item id); seteditingtitle(item get("title")); seteditingdescription(item get("description")); }; const handleupdateitem = async () => { try { const items = parse object extend("items"); const item = new items(); item id = editingitemid; item set("title", editingtitle); item set("description", editingdescription); await item save(); seteditingitemid(null); seteditingtitle(""); seteditingdescription(""); fetchitems(); } catch (error) { console error("error updating item ", error); } }; return ( \<div style={{ padding '2rem' }}> \<h1>items\</h1> \<div style={{ marginbottom '1rem' }}> \<h2>add item\</h2> \<input type="text" placeholder="title" value={newitemtitle} onchange={(e) => setnewitemtitle(e target value)} style={{ marginright '0 5rem' }} /> \<input type="text" placeholder="description" value={newitemdescription} onchange={(e) => setnewitemdescription(e target value)} style={{ marginright '0 5rem' }} /> \<button onclick={handleadditem}>add item\</button> \</div> \<h2>item list\</h2> \<ul> {items map((item) => ( \<li key={item id} style={{ marginbottom '1rem' }}> {editingitemid === item id ? ( \<div> \<input type="text" value={editingtitle} onchange={(e) => seteditingtitle(e target value)} style={{ marginright '0 5rem' }} /> \<input type="text" value={editingdescription} onchange={(e) => seteditingdescription(e target value)} style={{ marginright '0 5rem' }} /> \<button onclick={handleupdateitem}>save\</button> \<button onclick={() => seteditingitemid(null)} style={{ marginleft '0 5rem' }}> cancel \</button> \</div> ) ( \<div> \<strong>{item get("title")}\</strong> {item get("description")} \<button onclick={() => starteditingitem(item)} style={{ marginleft '1rem' }}> edit \</button> \<button onclick={() => handledeleteitem(item id)} style={{ marginleft '0 5rem' }}> delete \</button> \</div> )} \</li> ))} \</ul> \</div> ); } export default app; committing your code to github initialize a git repository (if not already done) git init stage your source files git add commit your changes git commit m "initial commit of preact frontend source code" create a new github repository, for example, basic crud app preact frontend push your code git remote add origin https //github com/your username/basic crud app preact frontend git git push u origin main 7 3 connecting your repository with web deployment go to the web deployment section in your back4app dashboard, open your project ( basic crud app preact ), and select web deployment link your github account as prompted, so back4app can access your repository select the repository (e g , basic crud app preact frontend ) and choose the appropriate branch (e g , main ) 7 4 deployment configuration specify additional settings build command if a pre built build folder is absent, set the build command (e g , npm run build ) back4app will run this command during deployment output directory define the output folder as build so that back4app identifies the static files environment variables add any necessary api keys or settings required by your application 7 5 containerizing your preact application with docker if you prefer docker, include a dockerfile in your repository similar to \# use an official node image for building from node 16 alpine as build \# set working directory workdir /app \# copy package files copy package json / \# install dependencies run npm install \# copy the source code copy \# build the app run npm run build \# use nginx to serve the built app from nginx\ stable alpine copy from=build /app/build /usr/share/nginx/html expose 80 cmd \["nginx", " g", "daemon off;"] select the docker deployment option in your back4app web deployment settings 7 6 deploying your application click the deploy button once configuration is complete monitor the build process as back4app fetches your code, builds, and deploys your application once finished, back4app will provide a url where your application is hosted 7 7 verifying your deployment visit the provided url to see your live site test all functionalities to ensure every feature, including routes and assets, loads correctly if issues occur, review browser console logs and deployment logs in back4app step 8 – wrap up and future directions great work! you've successfully developed a full crud application using preact and back4app you set up a project named basic crud app preact , defined robust database collections, and used the admin app for efficient data management you then connected your preact frontend to your backend and implemented strict access controls what’s next? enhance your preact app with additional features such as detailed views, search capabilities, and real time updates incorporate more advanced backend logic like cloud functions or third party api integrations consult the back4app documentation https //www back4app com/docs and other resources for deeper insights into optimization and custom configurations by following this tutorial, you’ve gained the skills to build a scalable, secure crud backend for your preact applications using back4app enjoy coding and exploring new features!