Quickstarters
CRUD Samples
How to Build a Basic CRUD App with Marko? A Step-by-Step Guide
40 min
overview this guide walks you through creating a complete crud (create, read, update, delete) application using marko and back4app in this tutorial, you will set up a project—named basic crud app marko —on back4app, design a robust database schema, and integrate your marko frontend with back4app’s api the tutorial also explains how to secure your backend and deploy your application for production use what you will learn how to construct crud applications that efficiently manage data using a reliable backend tips for designing a scalable schema and linking it to a marko based frontend utilizing back4app’s user friendly admin interface for managing data effortlessly deployment strategies, including containerization with docker, for launching your web application prerequisites before starting, ensure you have a back4app account and a new project follow the instructions in getting started with back4app https //www back4app com/docs/get started/new parse app if needed a marko development environment set up use the marko cli or your preferred setup method ensure node js (v14 or later) is installed basic knowledge of javascript, marko, and rest apis visit the marko documentation https //markojs com/docs/ for more details step 1 – setting up your project starting a new back4app project sign in to your back4app account select “new app” on your dashboard input the project name basic crud app marko and follow the on screen prompts create new project your new project will now appear on your back4app dashboard, laying the groundwork for your backend step 2 – crafting your database schema building your data model for this crud app, you’ll create a couple of collections below are examples of collections with suggested fields to help you design a practical database schema 1\ collection products this collection will hold details about each product field type details id objectid auto generated primary identifier name string the product name details string a brief description of the product created at date timestamp marking product creation updated at date timestamp of the last update 2\ collection users this collection holds user and authentication data field type details id objectid auto generated unique identifier username string a unique name for the user email string a unique email address password string a hashed version of the user's password created at date record creation timestamp updated at date last modified timestamp you can manually define these collections in the back4app dashboard by creating a new class for each collection and then adding the appropriate columns create new class you can quickly add fields by choosing a type, naming your column, setting default values, and marking it as required if necessary create column utilizing the back4app ai agent for schema creation the back4app ai agent simplifies schema design by generating collection and field definitions based on your prompt this feature saves time and ensures consistency in your database setup how to use the ai agent access the ai agent navigate to your back4app dashboard and find the ai agent in your project settings describe your schema provide a detailed prompt describing the collections and fields you require review and implement after generation, review the suggested schema and apply the changes example prompt create the following collections for my back4app project 1\) collection products \ fields \ id objectid (auto generated) \ name string \ details 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 string \ created at date (auto generated) \ updated at date (auto updated) this approach streamlines your schema creation process step 3 – activating the admin interface & crud functionality introducing the admin interface the back4app admin app is a no code interface that makes data management effortless its drag and drop features let you easily add, modify, view, or remove records enabling the admin interface go to the “more” section in your back4app dashboard select “admin app” and then click on “enable admin app ” set up admin credentials create your first admin account which will also assign system roles like b4aadminuser enable admin app once activated, log in to the admin app to manage your backend admin app dashboard managing crud operations via the admin interface within the admin app you can add new entries use the “add record” option in a collection (e g , products) view/modify records click on any entry to review or update its details remove entries utilize the delete function to remove obsolete records this streamlined interface enhances user experience by simplifying data management tasks step 4 – connecting marko with back4app now that your backend is configured, it’s time to integrate your marko frontend with back4app using the api option a employing the api you will use rest api calls to execute crud operations in your marko application example fetching data via rest // in a marko component script file (e g , fetchproducts marko) import { onmount } from 'marko/src/runtime/client'; onmount(async () => { try { const response = await fetch('https //parseapi back4app com/classes/products', { headers { 'x parse application id' 'your application id', 'x parse rest api key' 'your rest api key' } }); const data = await response json(); console log('products ', data results); } catch (error) { console error('failed to fetch products ', error); } }); this code snippet shows how to pull product data from back4app using a rest api call step 5 – safeguarding your backend configuring access controls enhance security by applying access control lists (acls) to your records for example, to create a private product entry async function createsecureproduct(productdata, owner) { const product = { name productdata name, details productdata details }; // setup acl only the owner has read/write privileges product acl = { " " { read false, write false }, \[owner id] { read true, write true } }; try { const response = await fetch('https //parseapi back4app com/classes/products', { method 'post', headers { 'x parse application id' 'your application id', 'x parse rest api key' 'your rest api key', 'content type' 'application/json' }, body json stringify(product) }); const result = await response json(); console log('secure product created ', result); } catch (error) { console error('error creating product ', error); } } setting default permissions use the back4app dashboard to configure class level permissions (clps) for each collection, ensuring that only authorized users can access sensitive data step 6 – user authentication setup creating user accounts back4app employs a user class for authentication in your marko app, implement user sign up and login like this // in a marko component script (e g , auth marko) import { onmount } from 'marko/src/runtime/client'; async function registeruser(username, email, password) { const userdata = { username, email, password }; try { const response = await fetch('https //parseapi back4app com/users', { method 'post', headers { 'x parse application id' 'your application id', 'x parse rest api key' 'your rest api key', 'content type' 'application/json' }, body json stringify(userdata) }); const result = await response json(); console log('user registered ', result); } catch (error) { console error('registration error ', error); } } this snippet demonstrates a simple user registration flow using rest calls step 7 – deploying your marko frontend back4app’s web deployment feature allows you to host your marko project directly from a github repository 7 1 – building your production version open your project directory in a terminal run the build command npm run build this produces a build directory with your optimized static files confirm the build check that the build folder includes an index html and all asset directories 7 2 – organizing and uploading your code your repository should hold the full source of your marko project a typical directory layout might look like basic crud app marko frontend/ ├── node modules/ ├── public/ │ └── index html ├── src/ │ ├── components/ │ │ ├── fetchproducts marko │ │ └── auth marko │ ├── app marko │ └── api js ├── package json └── readme md example src/api js // src/api js export const api headers = { 'x parse application id' 'your application id', 'x parse rest api key' 'your rest api key', 'content type' 'application/json' }; export async function fetchproducts() { const response = await fetch('https //parseapi back4app com/classes/products', { headers api headers }); const data = await response json(); return data results; } committing to github initialize git (if needed) git init stage your files git add commit your changes git commit m "initial commit for marko crud frontend" create and push to your github repository for example, use a repository named basic crud app marko frontend 7 3 – linking github with web deployment access web deployment sign in to back4app, go to your project (basic crud app marko), and open the web deployment section connect your github account follow the prompts to link your github account select the repository and branch choose the repository (e g , basic crud app marko frontend ) and the branch (e g , main ) to deploy 7 4 – configuring the deployment set additional parameters build command if no pre built build folder exists, set a build command (e g , npm run build ) output directory specify build as the output folder environment variables input any necessary variables (such as api keys) 7 5 – containerizing with docker if you prefer docker, include a dockerfile in your project repository \# use a node image for building the app from node 16 alpine as build \# set working directory workdir /app \# install dependencies copy package json / run npm install \# copy all files and build the app copy run npm run build \# use nginx to serve the build from nginx\ stable alpine copy from=build /app/build /usr/share/nginx/html expose 80 cmd \["nginx", " g", "daemon off;"] in your deployment settings, choose the docker deployment option 7 6 – deploying your application press the deploy button back4app will pull your repository, run the build, and deploy your app monitor the process watch the deployment logs for any build or runtime issues access your site once deployed, back4app provides a url for your hosted marko application 7 7 – confirming your deployment open the provided url check that your application loads correctly run through the app verify that all pages load and crud functionalities operate as expected troubleshoot if required use browser developer tools and back4app logs to address any issues step 8 – final thoughts and future enhancements great work! you’ve now built a full featured crud application with marko and back4app you set up a project called basic crud app marko , crafted detailed collections for products and users, managed data via an intuitive admin interface, integrated your marko frontend using rest apis, and secured your backend with robust controls next steps enhance your ui consider adding advanced features like product details pages, search functionalities, and live notifications expand backend capabilities look into integrating serverless functions or third party apis for added functionality deepen your knowledge refer to the back4app documentation https //www back4app com/docs and additional tutorials for more insights on performance tuning and custom integrations happy coding with marko and back4app!