Quickstarters
CRUD Samples
How to Create a Basic CRUD App with StencilJS? A Comprehensive Tutorial
42 min
overview in this guide, you'll learn how to construct a basic crud (create, read, update, and delete) application using stenciljs this tutorial walks you through building a web app that executes essential operations to manage data effectively we'll start by launching a back4app project dubbed basic crud app stenciljs , which will serve as your robust backend afterward, you'll design a scalable database by defining collections and fields—either manually or with assistance from the back4app ai agent this step ensures that your database is tailored to support all crud operations reliably next, you'll utilize the back4app admin app, an intuitive drag and drop interface, to manage your collections seamlessly this no code tool simplifies the handling of crud actions finally, you'll connect your stenciljs frontend to back4app via rest/graphql apis while the parse sdk is available, we'll focus on api integrations which suit stenciljs perfectly, ensuring your backend remains secure through advanced access controls by the end of this tutorial, you'll have a production ready web application that supports essential crud functions along with user authentication and robust data management essential insights master the process of building crud apps with a dependable backend system understand how to design a scalable backend and connect it with a stenciljs frontend learn to use a no code admin tool (the back4app admin app) for efficient data operations discover deployment strategies, including docker containerization, for launching your web application swiftly prerequisites before you get started, make sure you have a back4app account with an active project need assistance? check out getting started with back4app https //www back4app com/docs/get started/new parse app a stenciljs development setup use the official stenciljs documentation https //stenciljs com/docs/introduction to set up your environment ensure node js (v14 or later) is installed basic knowledge of javascript, web components, and rest apis brush up on stenciljs concepts https //stenciljs com/docs if necessary step 1 – initiate your project launching a new back4app project sign in to your back4app account select the “new app” option from your dashboard name your project basic crud app stenciljs and follow the on screen instructions to complete the setup create new project once set up, your project will be visible on the dashboard, providing a solid base for your backend configuration step 2 – crafting your database schema defining the data model for this crud application, you'll need to set up multiple collections below are sample collections along with their fields and data types to help you structure your database for efficient crud operations 1\ collection items this collection holds details for each item field data type details id objectid auto generated primary key title string name or title of the item description string brief description of the item created at date timestamp when the item was created updated at date timestamp for the last update 2\ collection users this collection manages user profiles and authentication field data type details id objectid auto generated unique identifier username string unique identifier for the user email string unique email address password hash string encrypted password for authentication created at date account creation timestamp updated at date last updated timestamp for the user account you can add these collections manually in the back4app dashboard by creating a new class for each and adding columns with appropriate data types create new class follow the prompts to select a data type, specify a field name, set default values, and mark whether the field is mandatory create column utilizing the back4app ai agent for schema creation the back4app ai agent is an innovative tool available within your dashboard that automates the generation of your database schema based on a simple prompt this feature speeds up project setup and ensures your schema is aligned with your application needs how to leverage the ai agent access the ai agent open your back4app dashboard and find the ai agent within the menu or under project settings input your schema requirements provide a detailed prompt describing the collections and fields you require review and confirm once the ai agent processes your prompt, review the generated schema suggestions and 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 method ensures your schema is both consistent and optimized step 3 – activating the admin app & crud functions introduction to the admin app the back4app admin app offers a no code interface that makes it simple to manage backend data its intuitive drag and drop system allows you to perform all crud operations—create, read, update, and delete—with ease enabling the admin app open the “more” menu on your back4app dashboard select “admin app” and then click on “enable admin app ” set up your admin credentials by creating an admin user this process also configures default roles like b4aadminuser and system collections enable admin app once activated, sign in to the admin app to start managing your data admin app dashboard managing crud actions via the admin app within this interface you can add records click the “add record” option within any collection (e g , items) to create new entries view and edit records select a record to inspect or modify its fields remove records utilize the delete function to eliminate obsolete records this streamlined tool enhances the user experience by simplifying data management tasks step 4 – linking stenciljs with back4app with your backend configured and managed through the admin app, the next step is to connect your stenciljs frontend to back4app option a employing rest or graphql apis for stenciljs we'll focus on api integrations to keep things simple example fetching data via rest // example rest api 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('items retrieved ', data results); } catch (error) { console error('error retrieving items ', error); } }; fetchitems(); integrate these api calls into your stenciljs components as needed option b utilizing the parse sdk (if desired) if you prefer to use the parse sdk, you can still integrate it within your stenciljs project since it’s a javascript library however, our example here focuses on api calls step 5 – fortifying your backend implementing access control lists (acls) ensure data security by setting acls on your objects for example, to create a private item async function createsecureitem(itemdata, owneruser) { const items = parse object extend('items'); const item = new items(); item set('title', itemdata title); item set('description', itemdata description); // define acl restrict read/write access to the owner const acl = new parse acl(owneruser); acl setpublicreadaccess(false); acl setpublicwriteaccess(false); item setacl(acl); try { const saveditem = await item save(); console log('secure item created ', saveditem); } catch (error) { console error('error creating item ', error); } } configuring class level permissions (clps) within the back4app dashboard, set clps for each collection to ensure that only authorized users can access sensitive data step 6 – managing user authentication establishing user accounts back4app uses parse’s user class for managing authentication in your stenciljs project, implement user registration and login as follows // example component for user signup import { component, h, state } from '@stencil/core'; import parse from ' /parseconfig'; @component({ tag 'app auth', styleurl 'app auth css', shadow true, }) export class appauth { @state() username string = ''; @state() password string = ''; @state() email string = ''; async handlesignup(event event) { event 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 registered successfully!'); } catch (error) { alert('registration error ' + error message); } } render() { return ( \<form onsubmit={(e) => this handlesignup(e)}> \<input type="text" placeholder="username" value={this username} oninput={(e any) => this username = e target value} /> \<input type="password" placeholder="password" value={this password} oninput={(e any) => this password = e target value} /> \<input type="email" placeholder="email" value={this email} oninput={(e any) => this email = e target value} /> \<button type="submit">register\</button> \</form> ); } } a similar structure can be applied for login and session management you can also enable features like social logins, email verification, and password resets directly from the back4app dashboard step 7 – launching your stenciljs frontend with web deployment back4app’s web deployment feature allows you to host your stenciljs application by deploying code directly from a github repository 7 1 building your production bundle open your project directory in a terminal execute the build command npm run build this produces a www folder containing optimized static assets confirm the build ensure the www folder includes an index html along with necessary css, js, and image files 7 2 organizing and uploading your source code your repository should encompass all the source files for your stenciljs application an example structure might be basic crud app stenciljs frontend/ ├── node modules/ ├── www/ │ └── index html ├── src/ │ ├── components/ │ │ ├── app auth tsx │ │ └── app items tsx │ ├── global/ │ └── parseconfig ts ├── stencil config ts ├── package json └── readme md example source file src/parseconfig ts // src/parseconfig ts 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; example source file src/components/app items tsx import { component, h, state } from '@stencil/core'; import parse from ' /parseconfig'; @component({ tag 'app items', styleurl 'app items css', shadow true, }) export class appitems { @state() items any\[] = \[]; @state() newtitle string = ''; @state() newdescription string = ''; @state() editingid string | null = null; @state() editingtitle string = ''; @state() editingdescription string = ''; async componentwillload() { await 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('error fetching 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); } } async deleteitem(id string) { try { const item = await parse object createwithoutdata("items", id); await item destroy(); this loaditems(); } catch (error) { console error('error deleting item ', error); } } startedit(item any) { this editingid = item id; this editingtitle = item get("title"); this editingdescription = item get("description"); } async updateitem() { try { const items = parse object extend("items"); const item = new items(); item id = this editingid!; item set("title", this editingtitle); item set("description", this editingdescription); await item save(); this editingid = null; this editingtitle = ''; this editingdescription = ''; this loaditems(); } catch (error) { console error('error updating item ', error); } } render() { return ( \<div style={{ padding '2rem' }}> \<h1>items\</h1> \<div> \<h2>add new item\</h2> \<input type="text" placeholder="title" value={this newtitle} oninput={(e any) => this newtitle = e target value} /> \<input type="text" placeholder="description" value={this newdescription} oninput={(e any) => this newdescription = e target value} /> \<button onclick={() => this additem()}>add item\</button> \</div> \<ul> {this items map(item => \<li key={item id}> {this editingid === item id ? ( \<div> \<input type="text" value={this editingtitle} oninput={(e any) => this editingtitle = e target value} /> \<input type="text" value={this editingdescription} oninput={(e any) => this editingdescription = e target value} /> \<button onclick={() => this updateitem()}>save\</button> \<button onclick={() => this editingid = null}>cancel\</button> \</div> ) ( \<div> \<strong>{item get("title")}\</strong> {item get("description")} \<button onclick={() => this startedit(item)}>edit\</button> \<button onclick={() => this deleteitem(item id)}>delete\</button> \</div> )} \</li> )} \</ul> \</div> ); } } committing your code to github initialize a git repository in your project directory (if not already done) git init stage your files git add commit your changes git commit m "initial commit of stenciljs frontend code" create a new github repository name it something like basic crud app stenciljs frontend push your code to github git remote add origin https //github com/your username/basic crud app stenciljs frontend git git push u origin main 7 3 connecting your repository via web deployment access web deployment log into your back4app dashboard, select your project ( basic crud app stenciljs ), and click on the web deployment section integrate github connect your github account following the provided instructions this will enable back4app to access your repository select the repository and branch choose your repository (e g , basic crud app stenciljs frontend ) and pick the appropriate branch (e g , main ) 7 4 setting up your deployment enter additional deployment details build command if your repository doesn’t include a pre built www folder, specify a build command (e g , npm run build ) back4app will execute this during deployment output directory set the output directory to www so that back4app knows where to locate your static files environment variables add any required environment variables (e g , api keys) in the deployment settings 7 5 containerizing your stenciljs project with docker if you favor docker for deployment, include a dockerfile in your repository similar to \# use an official node image to build the app from node 16 alpine as build \# set working directory workdir /app \# copy dependency files copy package json / \# install dependencies run npm install \# copy source code copy \# build the app run npm run build \# use nginx to serve the app from nginx\ stable alpine copy from=build /app/www /usr/share/nginx/html expose 80 cmd \["nginx", " g", "daemon off;"] include this file in your repo and choose docker deployment in back4app 7 6 deploying your application initiate deployment click the deploy button after configuring your settings watch the build process back4app will fetch your code from github, run the build command (if set), and deploy your containerized application access your application once deployed, back4app will provide a url where your stenciljs app is live 7 7 validating your deployment visit the url open the provided url in your web browser test functionality ensure the application loads properly, routes work correctly, and all assets (css, js, images) are served without issues debug if necessary use browser developer tools to inspect any errors check back4app logs and verify github and build configurations if issues occur step 8 – summary and future directions well done! you have successfully built a complete crud application using stenciljs and back4app you set up a project titled basic crud app stenciljs , designed collections for items and users, and managed data with the admin app additionally, you connected your stenciljs frontend to your backend and implemented robust security measures next steps enhance the frontend consider expanding your stenciljs app with advanced features such as detailed item views, search capabilities, and real time notifications add more functionalities integrate complex backend logic (e g , cloud functions), third party api integrations, or implement role based permissions deepen your knowledge explore the back4app documentation https //www back4app com/docs and other tutorials for further insights into performance tuning and custom integrations by following this tutorial, you've acquired the skills needed to create a robus