Quickstarters
CRUD Samples
How to Build a Basic CRUD App with Knockout.js: A Step-by-Step Guide
39 min
overview in this guide, you'll learn how to create a full featured crud (create, read, update, delete) application using knockout js this tutorial demonstrates how to implement essential operations within a web app while leveraging back4app as your backend service we will start by setting up a back4app project titled basic crud app knockout , establishing a reliable data management system for your application after that, you'll design a flexible database schema by defining collections and fields—either manually or with assistance from the back4app ai agent—to ensure your app can handle all crud operations effectively next, you'll use the back4app admin app, a user friendly drag and drop tool, to manage your collections with ease this interface simplifies the process of executing crud operations finally, you'll integrate your knockout js frontend with back4app using rest api calls this integration will also cover secure backend practices with proper access controls by the end of this tutorial, you'll have built a production ready web app that supports basic crud functionality, includes user authentication, and features robust data management key takeaways understand how to develop crud applications that manage data efficiently using back4app gain practical experience in designing a scalable backend and linking it with a knockout js frontend learn to use a no code admin tool (back4app admin app) for executing create, read, update, and delete operations discover deployment strategies, including docker containerization, to launch your web app swiftly prerequisites before starting, make sure you have a back4app account and an active project refer to getting started with back4app https //www back4app com/docs/get started/new parse app if you need guidance a development environment set up for knockout js include libraries via cdn or install via npm if you prefer a modular setup basic knowledge of javascript, knockout js, and rest apis consult the knockout js documentation https //knockoutjs com/documentation/introduction html for an introduction step 1 – project initialization setting up your back4app project access your back4app account select the “new app” option from your dashboard input the project name basic crud app knockout and complete the setup process create new project once created, your project will be visible on your dashboard, forming the backbone for your backend configuration step 2 – crafting your database schema designing the data structure for this crud app, you'll create several collections below are sample collections with suggested fields and data types to guide your database design this schema supports the fundamental crud operations 1\ items collection field data type details id objectid automatically generated unique key title string the item’s title description string a brief summary of the item created at date timestamp when the item is created updated at date timestamp of the last update 2\ users collection field data type details id objectid auto generated unique identifier username string unique identifier for each user email string user’s unique email address password hash string secure hash of the user’s password created at date account creation timestamp updated at date timestamp for last account update you can manually create these collections in the back4app dashboard by adding a new class for each collection and defining the fields create new class define your fields by choosing a data type, naming the field, setting default values, and marking required fields create column using the back4app ai agent for schema automation the back4app ai agent simplifies schema generation directly from your dashboard it can automatically create collections and fields based on your description steps to use the ai agent launch the ai agent access it via your back4app dashboard or project settings detail your data model paste a descriptive prompt listing your required collections and fields review and apply the agent will propose a schema review and confirm the suggestions to integrate them into your project sample prompt create the following 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 process saves time and ensures a consistent, optimized schema for your application step 3 – activating the admin app and managing crud operations overview of the admin interface the back4app admin app provides a no code solution for managing your backend data its intuitive drag and drop interface allows for effortless crud operations how to activate the admin app go to the “more” menu in your back4app dashboard select “admin app” and click on “enable admin app ” set up your admin credentials by creating the first admin user, which also configures roles like b4aadminuser and essential system collections enable admin app after activation, sign in to the admin app to begin data management admin app dashboard using the admin interface for crud within the admin app you can add records click the “add record” button in a collection (for example, items) to create new entries view/modify records select a record to inspect its details or update fields remove records delete any entries that are no longer required this streamlined interface enhances usability and accelerates the management of your data step 4 – connecting knockout js with back4app with your backend in place, it's time to integrate your knockout js frontend using rest api calls using the rest api for crud operations since the parse sdk isn’t typically used with knockout js, you'll perform api calls directly below are examples of how to handle crud tasks fetching items example // example rest call to retrieve items function fetchitems() { fetch('https //parseapi back4app com/classes/items', { headers { 'x parse application id' 'your application id', 'x parse rest api key' 'your rest api key' } }) then(response => response json()) then(data => { viewmodel items(data results); }) catch(error => console error('error retrieving items ', error)); } fetchitems(); knockout js viewmodel example below is an example viewmodel for managing your items function appviewmodel() { var self = this; self items = ko observablearray(\[]); self newtitle = ko observable(""); self newdescription = ko observable(""); self additem = function() { var newitem = { title self newtitle(), description self newdescription() }; fetch('https //parseapi back4app com/classes/items', { method 'post', headers { 'content type' 'application/json', 'x parse application id' 'your application id', 'x parse rest api key' 'your rest api key' }, body json stringify(newitem) }) then(response => response json()) then(data => { self items push(data); self newtitle(""); self newdescription(""); }) catch(error => console error('error adding item ', error)); }; self deleteitem = function(item) { fetch('https //parseapi back4app com/classes/items/' + item objectid, { method 'delete', headers { 'x parse application id' 'your application id', 'x parse rest api key' 'your rest api key' } }) then(() => { self items remove(item); }) catch(error => console error('error deleting item ', error)); }; // additional methods for update and read operations can be added similarly } // activate knockout js ko applybindings(new appviewmodel()); this viewmodel integrates api calls for creating and deleting items while managing state with knockout js observables step 5 – securing your backend access control lists (acls) protect your data by assigning acls to each object for instance, to make an item accessible only to its creator function createsecureitem(itemdata, owneruserid) { var newitem = { title itemdata title, description itemdata description, acl { " " { "read" false, "write" false }, \[owneruserid] { "read" true, "write" true } } }; fetch('https //parseapi back4app com/classes/items', { method 'post', headers { 'content type' 'application/json', 'x parse application id' 'your application id', 'x parse rest api key' 'your rest api key' }, body json stringify(newitem) }) then(response => response json()) then(data => console log('secure item created ', data)) catch(error => console error('error creating item ', error)); } class level permissions (clps) within the back4app dashboard, set clps for each collection to ensure only authenticated or authorized users can access sensitive information step 6 – implementing user authentication configuring user accounts back4app uses a user class for managing authentication in your knockout js app, handle user registration and login using rest api calls example user registration function registeruser(username, password, email) { var user = { username username, password password, email email }; fetch('https //parseapi back4app com/users', { method 'post', headers { 'content type' 'application/json', 'x parse application id' 'your application id', 'x parse rest api key' 'your rest api key' }, body json stringify(user) }) then(response => response json()) then(data => alert('registration successful!')) catch(error => alert('registration error ' + error message)); } a similar approach can be followed for user login and session management additional features like email verification and password resets can be configured via back4app step 7 – deploying your knockout js frontend using web deployment back4app’s web deployment feature lets you host your knockout js frontend effortlessly by linking your github repository follow these steps 7 1 build your production files open your project directory in a terminal run your build process if you’re using a build tool like webpack, run the appropriate command (e g , npm run build ) to compile your assets confirm the build ensure your build folder contains an index html and all required static assets 7 2 organize and commit your code to github your repository should include all source files for your knockout js frontend an example structure might be basic crud app knockout frontend/ ├── node modules/ ├── public/ │ └── index html ├── src/ │ ├── index js │ ├── appviewmodel js │ └── styles css ├── package json └── readme md sample file src/appviewmodel js function appviewmodel() { var self = this; self items = ko observablearray(\[]); self newtitle = ko observable(""); self newdescription = ko observable(""); self additem = function() { var itemdata = { title self newtitle(), description self newdescription() }; fetch('https //parseapi back4app com/classes/items', { method 'post', headers { 'content type' 'application/json', 'x parse application id' 'your application id', 'x parse rest api key' 'your rest api key' }, body json stringify(itemdata) }) then(response => response json()) then(data => { self items push(data); self newtitle(""); self newdescription(""); }) catch(error => console error('error adding item ', error)); }; // additional crud methods (update, delete) can be defined similarly } // apply knockout bindings ko applybindings(new appviewmodel()); committing and pushing code to github initialize git (if not already done) git init stage your files git add commit your changes git commit m "initial commit for knockout js frontend" create a github repository (e g , basic crud app knockout frontend ) push your code git remote add origin https //github com/your username/basic crud app knockout frontend git git push u origin main 7 3 linking your github repository with web deployment access the web deployment feature in your back4app dashboard, select your project (basic crud app knockout) and click on web deployment connect to github follow the prompts to integrate your github account choose your repository and branch select your repository (e g , basic crud app knockout frontend ) and the branch (e g , main ) containing your code 7 4 deployment settings build command if your repository doesn’t include a pre built folder, specify the build command (e g , npm run build ) output directory set this to the folder containing your static files (e g , build or public ) environment variables add any required environment variables, such as api keys 7 5 containerizing your application with docker (optional) if you wish to use docker, include a dockerfile in your repository \# use an official node image for building from node 16 alpine as build \# set working directory workdir /app \# copy package files and install dependencies copy package json / run npm install \# copy source code and build the app copy run npm run build \# use nginx to serve the static files from nginx\ stable alpine copy from=build /app/build /usr/share/nginx/html expose 80 cmd \["nginx", " g", "daemon off;"] 7 6 deploying your application click the deploy button after configuring the settings, initiate deployment monitor the process back4app will fetch your code, build it (if necessary), and deploy your containerized app access your app once complete, back4app will provide a url to access your knockout js app 7 7 testing the deployment open the provided url check if your app loads properly run tests ensure all routes and assets (css, js, images) are functioning debug if necessary use developer tools to inspect any errors and refer to back4app deployment logs step 8 – conclusion and future directions well done! you’ve successfully built a basic crud application using knockout js and back4app you set up a project named basic crud app knockout , crafted detailed collections for items and users, and managed your data via the admin app additionally, you integrated your knockout js frontend with your backend using rest api calls and implemented secure access controls next steps expand your frontend enhance your app with features like detailed item views, search capabilities, or live updates add advanced backend logic explore using cloud functions or integrating third party services dive deeper consult the back4app documentation https //www back4app com/docs for further optimization and advanced integrations by following this tutorial, you now have the knowledge to build a robust and scalable crud app with knockout js using back4app happy coding!