Quickstarters
CRUD Samples
Building a Basic CRUD Application with Lit?
42 min
overview in this guide, you will create a fully functioning crud (create, read, update, delete) application using lit we will demonstrate how to manage data dynamically by building an application that performs these essential operations initially, you'll set up a back4app project called basic crud app lit that serves as your robust backend after establishing your project, you'll design a flexible database schema by defining collections and fields, either manually or with the help of the back4app ai agent this step is crucial for ensuring that your system reliably handles crud operations next, you'll utilize the back4app admin app—a user friendly, drag and drop interface—to manage your collections efficiently finally, you'll integrate your lit frontend with back4app using rest/graphql , ensuring that your backend remains secure with proper access controls by the end of this tutorial, you'll have a production ready web application that not only performs basic crud functions but also includes user authentication and secure data handling key points master the development of crud applications that effectively manage data with a dependable backend learn to design a scalable database and seamlessly integrate it with a lit based frontend utilize a drag and drop admin tool (the back4app admin app) to simplify crud operations understand deployment strategies, including containerization with docker, to launch your web application efficiently prerequisites before starting, make sure you have a back4app account with a new project for assistance, see getting started with back4app https //www back4app com/docs/get started/new parse app a lit development environment set up your project using your preferred starter kit and ensure node js (v14 or later) is installed basic knowledge of javascript, lit, and rest apis consult the lit documentation https //lit dev/docs/ if needed step 1 – initializing your project establishing a new back4app project sign in to your back4app account select the “new app” option from your dashboard name your project basic crud app lit and follow the instructions to create it create new project once your project is created, it will appear on the dashboard, providing you with the foundation for backend configuration and project management step 2 – crafting your database schema constructing your data model for this crud application, you'll define several collections below are example collections with suggested fields and data types, which will help you set up an effective schema capable of handling crud operations 1\ items collection field data type details id objectid auto generated primary key title string name of the item description string brief details about the item created at date timestamp when the item was created updated at date timestamp when the item was last modified 2\ users collection field data type details id objectid auto generated primary key username string unique identifier for the user email string user's unique email address password hash string hashed password for secure authentication created at date timestamp for account creation updated at date timestamp for the latest account update you can add these collections manually through the back4app dashboard by creating new classes and defining the appropriate columns create new class for each field, simply choose a data type, assign a name, set a default value if needed, and specify whether it’s mandatory create column utilizing the back4app ai agent for schema creation the back4app ai agent, available from your dashboard, can automatically generate your schema based on a descriptive prompt this feature streamlines project management by ensuring consistency in your backend setup how to use the ai agent launch the ai agent navigate to the ai agent from your back4app dashboard or within project settings detail your data model paste a comprehensive prompt describing the collections and fields you require review and apply inspect the generated suggestions and confirm them to update your project sample prompt create the following collections in my back4app application 1\) collection items \ fields \ id objectid (auto generated primary key) \ title string \ description string \ created at date (auto generated) \ updated at date (auto updated) 2\) collection users \ fields \ id objectid (auto generated primary key) \ username string (unique) \ email string (unique) \ password hash string \ created at date (auto generated) \ updated at date (auto updated) using this ai feature saves valuable time while ensuring that your database is structured optimally step 3 – activating the admin app & crud functionalities introduction to the admin app the back4app admin app offers a no code interface for effortless backend data management its intuitive drag and drop functionality allows you to execute crud operations—create, read, update, and delete records—with ease how to enable the admin app access the “more” section on your back4app dashboard select “admin app” and click “enable admin app ” set up your admin credentials by creating an initial admin user, which will configure roles (such as b4aadminuser ) and system collections enable admin app after activation, log into the admin app to manage your collections admin app dashboard performing crud operations via the admin app inside the admin app, you can create entries click the “add record” button within a collection (e g , items) to generate new entries read/modify records click on a record to inspect its details or modify its fields remove records use the delete function to eliminate entries that are no longer needed this straightforward interface significantly improves the user experience by streamlining data management step 4 – connecting lit with back4app now that your backend is configured and managed, it's time to integrate your lit frontend with back4app option a using the parse sdk (when applicable) install the parse sdk npm install parse set up parse in your lit app create a configuration 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; implement parse in a lit component create a lit component that retrieves and displays items // src/components/itemslist js import { litelement, html, css } from 'lit'; import parse from ' /parseconfig'; class itemslist extends litelement { static properties = { items { type array } }; constructor() { super(); this items = \[]; } connectedcallback() { super connectedcallback(); this fetchitems(); } async fetchitems() { const items = parse object extend("items"); const query = new parse query(items); try { const results = await query find(); this items = results; } catch (error) { console error("error fetching items ", error); } } render() { return html` \<h2>items\</h2> \<ul> ${this items map( (item) => html` \<li>${item get("title")} — ${item get("description")}\</li> ` )} \</ul> `; } } customelements define('items list', itemslist); export default itemslist; option b utilizing rest or graphql if the parse sdk isn’t suitable for your project, perform crud operations using rest or graphql for instance, to retrieve items via rest // example rest request to get 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('items retrieved ', data results); } catch (error) { console error('error fetching items ', error); } }; fetchitems(); integrate these api calls within your lit components as needed step 5 – protecting your backend implementing access control lists (acls) secure your objects by setting acls for example, 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); // set acl so only the owner has 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); } } configuring class level permissions (clps) within the back4app dashboard, adjust the clps for each collection to enforce default access rules this ensures that only authenticated or authorized users can access sensitive information step 6 – implementing user authentication creating user accounts back4app utilizes parse’s user class to manage authentication in your lit application, implement user registration and login as demonstrated below // src/components/auth js import { litelement, html, css } from 'lit'; import parse from ' /parseconfig'; class signupform extends litelement { static properties = { username { type string }, password { type string }, email { type string } }; constructor() { super(); this username = ''; this password = ''; this email = ''; } async handlesignup(e) { e preventdefault(); const user = new parse user(); user set('username', this username); user set('password', this password); user set('email', this email); try { await user signup(); alert('user registration successful!'); } catch (error) { alert('registration error ' + error message); } } render() { return html` \<form @submit="${this handlesignup}"> \<input type="text" placeholder="username" value="${this username}" @input="${e => this username = e target value}" /> \<input type="password" placeholder="password" value="${this password}" @input="${e => this password = e target value}" /> \<input type="email" placeholder="email" value="${this email}" @input="${e => this email = e target value}" /> \<button type="submit">register\</button> \</form> `; } } customelements define('sign up form', signupform); export default signupform; you can similarly implement login and session management additional features like social authentication, email verification, and password resets can be set up via the back4app dashboard step 7 – deploying your lit frontend via web deployment back4app’s web deployment feature allows you to host your lit application by deploying code from a github repository follow these steps to prepare your production build, push your code to github, and deploy your site 7 1 creating your production build open your project directory in a terminal run the build command npm run build this will create a build folder containing optimized static assets check the build confirm that the build folder includes an index html file along with necessary subdirectories 7 2 organizing and uploading your code your github repository should house the complete source code for your lit frontend a typical project structure might look like basic crud app lit frontend/ ├── node modules/ ├── public/ │ └── index html ├── src/ │ ├── app js │ ├── parseconfig js │ └── components/ │ ├── itemslist js │ └── auth js ├── package json └── readme md example configuration file src/parseconfig js import parse from 'parse'; // insert your actual back4app credentials here parse initialize('your application id', 'your javascript key'); parse serverurl = 'https //parseapi back4app com'; export default parse; example main application file src/app js import { litelement, html } from 'lit'; import parse from ' /parseconfig'; class approot extends litelement { static properties = { items { type array }, newtitle { type string }, newdescription { type string } }; constructor() { super(); this items = \[]; this newtitle = ''; this newdescription = ''; } connectedcallback() { super connectedcallback(); this loaditems(); } async loaditems() { const items = parse object extend("items"); const query = new parse query(items); try { const results = await query find(); this items = results; } catch (error) { console error("failed to load items ", error); } } async additem() { const items = parse object extend("items"); const item = new items(); item set("title", this newtitle); item set("description", this newdescription); try { await item save(); this newtitle = ''; this newdescription = ''; this loaditems(); } catch (error) { console error("error adding item ", error); } } render() { return html` \<div style="padding 2rem;"> \<h1>items\</h1> \<div> \<input type="text" placeholder="title" value="${this newtitle}" @input="${e => this newtitle = e target value}" /> \<input type="text" placeholder="description" value="${this newdescription}" @input="${e => this newdescription = e target value}" /> \<button @click="${this additem}">add item\</button> \</div> \<ul> ${this items map(item => html` \<li> \<strong>${item get("title")}\</strong> ${item get("description")} \</li> `)} \</ul> \</div> `; } } customelements define('app root', approot); export default approot; pushing code to github initialize git in your project directory git init add all your files git add commit your changes git commit m "initial lit frontend commit" create a new repository on github (e g , basic crud app lit frontend ) push your code git remote add origin https //github com/your username/basic crud app lit frontend git git push u origin main 7 3 connecting your github repository with back4app web deployment access web deployment log into your back4app dashboard, choose your project (basic crud app lit), and select the web deployment option link your github account follow the prompts to connect your github account, allowing back4app to access your repository choose your repository and branch select the repository (e g , basic crud app lit frontend ) and the branch (e g , main ) containing your lit code 7 4 configuring deployment settings specify your build settings build command if a pre built build folder is missing, use a command like npm run build back4app will execute this command during deployment output directory set this to build so back4app can locate your static files environment variables include any necessary api keys or other environment specific values 7 5 containerizing your lit application with docker if you prefer docker, include a dockerfile in your repository \# use a lightweight node image for building the app from node 16 alpine as build \# set the working directory workdir /app \# copy package files and install dependencies copy package json / run npm install \# copy remaining source code and build the app copy 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;"] in your back4app deployment settings, choose the docker deployment option to containerize your app 7 6 launching your application initiate the deployment click the deploy button after finalizing your settings monitor the process back4app will fetch your github code, run the build command, and deploy your container get your live url once deployment finishes, a url will be provided where your lit application is hosted 7 7 validating your deployment visit the url open the provided link in your browser test functionality ensure that the application loads properly, navigation works, and all assets are correctly served debug if necessary use browser developer tools to inspect any issues if problems arise, review the deployment logs in back4app step 8 – final thoughts and future enhancements great work! you have successfully developed a basic crud application using lit and back4app you set up a project called basic crud app lit , defined a detailed database schema for items and users, and managed your data with the admin app furthermore, you integrated your lit frontend with the backend and implemented robust security measures next steps improve your frontend add features like detailed item pages, search functionality, and real time updates expand backend capabilities integrate advanced functionalities such as cloud functions, external api services, or role based access controls explore more resources visit the back4app documentation https //www back4app com/docs and other tutorials for deeper insights into performance and customization by following this guide, you now possess the skills to create a scalable, secure crud backend for your lit application using back4app enjoy coding and keep innovating!