Quickstarters
CRUD Samples
Building a Basic CRUD Application with Mithril.js: A Detailed Tutorial
42 min
overview this guide walks you through creating a crud (create, read, update, and delete) application using mithril js throughout this tutorial, you'll learn how to configure a back4app project titled basic crud app mithriljs to serve as a powerful backend for your web app we’ll design an efficient data schema, manage it via back4app’s admin panel, and integrate your mithril js frontend using rest api calls what you will learn how to set up a crud system that reliably handles data using a robust backend strategies to build a scalable database design and link it to a mithril js application utilizing back4app’s intuitive drag and drop admin interface to perform crud actions deployment methods, including docker containerization, to get your application live quickly requirements before you get started, please confirm you have a back4app account and an active project for assistance, refer to getting started with back4app https //www back4app com/docs/get started/new parse app a mithril js development environment you can include mithril via npm or a cdn ensure you have node js (v14+) installed fundamental knowledge of javascript, mithril js, and restful apis for additional guidance, check out the mithril js documentation https //mithril js org/ step 1 – initializing your project setting up a new back4app project sign in to your back4app account click the new app button from your dashboard provide the project name basic crud app mithriljs and follow the guided steps create new project once set up, your project will be listed on your dashboard, serving as the backend hub for your application step 2 – crafting your database schema constructing the data model for this crud app, you’ll design a couple of key collections below is an outline for creating collections with their respective fields to effectively handle crud operations 1\ items collection this collection holds the details for each item field type purpose id objectid auto generated unique identifier title string name or title of the item description string brief summary about the item created at date timestamp of creation updated at date timestamp for the latest update 2\ users collection this collection manages user profiles and authentication details field type purpose id objectid auto generated unique identifier username string user’s unique name email string user’s unique email address password hash string hashed password for secure authentication created at date timestamp when the user was registered updated at date timestamp for any modifications you can manually add these collections and fields via the back4app dashboard by creating new classes and defining each column accordingly create new class to add fields, simply select the appropriate data type, provide a name, set defaults, and mark if required create column leveraging back4app’s ai agent for schema automation the integrated ai agent on back4app streamlines schema creation by auto generating your collections based on a provided prompt how to utilize the ai agent access the ai agent from your project dashboard describe your desired schema by detailing the collections and fields review the generated schema and apply the changes 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 tool helps ensure that your database design is both consistent and optimal for handling crud operations step 3 – activating the admin interface & crud functionalities overview of the admin interface the back4app admin interface is a no code solution designed to help you manage your backend data effortlessly its drag and drop design makes performing crud operations a breeze how to enable the admin interface head to the more section in your back4app dashboard click on admin app then select enable admin app set up your administrator credentials to create your first admin user this process also configures roles (such as b4aadminuser ) and system collections enable admin app after activation, log into the admin interface to manage your collections admin app dashboard performing crud operations via the admin interface add new records use the “add record” option in any collection (for instance, items) to create entries view/modify records click on a record to inspect details or edit its fields remove records utilize the delete function to clear obsolete entries this intuitive interface enhances user experience by simplifying routine crud actions step 4 – linking mithril js with back4app with your backend ready and managed through the admin interface, it’s time to connect your mithril js frontend to back4app using rest api calls using rest api calls with mithril js we will rely on rest api calls to interact with your back4app backend example fetching and displaying items create a mithril component that retrieves items from the items collection // src/components/itemslist js const itemslist = { items \[], loaditems async function() { 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(); itemslist items = data results; } catch (error) { console error('error retrieving items ', error); } }, oninit function() { itemslist loaditems(); }, view function() { return m('div', \[ m('h2', 'items'), m('ul', itemslist items map(item => m('li', { key item objectid }, `${item title} — ${item description}` ) ) ) ]); } }; export default itemslist; this component employs mithril’s lifecycle method oninit to load data when the component is initialized example adding a new item you can integrate a form to send a post request to add new items // src/components/additem js const additem = { title '', description '', submititem async function() { try { const response = await 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({ title additem title, description additem description }) }); const data = await response json(); console log('item added ', data); // optionally, refresh the list or redirect the user } catch (error) { console error('error adding item ', error); } }, view function() { return m('div', \[ m('h2', 'add item'), m('input\[type=text]', { placeholder 'title', oninput m withattr('value', value => additem title = value), value additem title }), m('input\[type=text]', { placeholder 'description', oninput m withattr('value', value => additem description = value), value additem description }), m('button', { onclick additem submititem }, 'add item') ]); } }; export default additem; you can similarly implement update and delete operations using corresponding http methods (put/patch for updates and delete for removals) step 5 – enhancing backend security implementing access controls secure your data by applying access control lists (acls) to each object for instance, to create an item that only the owner can modify async function createsecureitem(itemdata, ownerid) { try { const response = await 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({ title itemdata title, description itemdata description, acl { \[ownerid] { read true, write true }, " " { read false, write false } } }) }); const data = await response json(); console log('secure item created ', data); } catch (error) { console error('error creating secure item ', error); } } setting class level permissions (clps) within your back4app dashboard, adjust clps for each collection to define default security policies this ensures that only authorized users have access to sensitive information step 6 – user authentication setup configuring user accounts back4app uses the parse user class to manage authentication with mithril js, you can manage registration and login through rest api calls below is an example for user sign up // src/components/auth js const auth = { username '', email '', password '', signup async function() { try { const response = await 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({ username auth username, email auth email, password auth password }) }); const data = await response json(); alert('user registered successfully!'); } catch (error) { alert('registration error ' + error message); } }, view function() { return m('form', { onsubmit function(e) { e preventdefault(); auth signup(); } }, \[ m('input\[type=text]', { placeholder 'username', oninput m withattr('value', value => auth username = value), value auth username }), m('input\[type=email]', { placeholder 'email', oninput m withattr('value', value => auth email = value), value auth email }), m('input\[type=password]', { placeholder 'password', oninput m withattr('value', value => auth password = value), value auth password }), m('button', { type 'submit' }, 'sign up') ]); } }; export default auth; you can adopt a similar method for logging in and managing sessions step 7 – deploying your mithril js frontend back4app’s web deployment feature lets you host your mithril js application seamlessly by linking your github repository 7 1 building the production version open your project directory in a terminal run the build command npm run build this will generate a build folder containing optimized static files 7 2 organizing and committing your code your repository should have a structure similar to basic crud app mithriljs frontend/ ├── node modules/ ├── public/ │ └── index html ├── src/ │ ├── index js │ ├── components/ │ │ ├── itemslist js │ │ ├── additem js │ │ └── auth js │ └── app js ├── package json └── readme md example src/index js import m from "mithril"; import itemslist from " /components/itemslist"; import additem from " /components/additem"; import auth from " /components/auth"; // define a simple routing system m route(document body, "/", { "/" { view function() { return m("div", \[ m(itemslist), m(additem), m(auth) ]); } } }); committing and pushing to github initialize git (if not already) git init add your files git add commit the changes git commit m "initial commit of mithril js frontend" create a repository on github (e g , basic crud app mithriljs frontend ) and push your code git remote add origin https //github com/your username/basic crud app mithriljs frontend git git push u origin main 7 3 linking github with web deployment log into your back4app dashboard, navigate to your project ( basic crud app mithriljs ), and select web deployment connect your github account following the on screen prompts choose your repository and branch (e g , main ) that contains your mithril js source code 7 4 setting up deployment configurations configure build command specify npm run build if the build folder isn’t present output directory set this to build to point to your static assets environment variables add any necessary api keys or settings 7 5 dockerizing your application (optional) if you prefer containerization, include a dockerfile \# use an official node image for building from node 16 alpine as builder workdir /app copy package json / run npm install copy run npm run build \# serve using nginx from nginx\ stable alpine copy from=builder /app/build /usr/share/nginx/html expose 80 cmd \["nginx", " g", "daemon off;"] 7 6 deploying your application hit the deploy button in your back4app web deployment section monitor the build process as back4app pulls, builds, and deploys your application once complete, you’ll receive a url for your live mithril js app 7 7 verifying the deployment open the provided url in your browser confirm that your application loads, navigations work, and assets are served properly use browser dev tools for troubleshooting if necessary step 8 – wrapping up and future directions well done! you’ve successfully built a basic crud app with mithril js integrated with back4app you set up a project called basic crud app mithriljs , defined your database schema for items and users, and managed your backend via the admin interface furthermore, you connected your mithril js frontend using rest api calls and applied security measures to protect your data what’s next? improve the frontend add features like detailed views, search capabilities, or live updates extend backend functions explore cloud functions, additional api integrations, or role based permissions learn more dive deeper into the back4app documentation https //www back4app com/docs and mithril js guides for advanced enhancements happy coding and best of luck with your project!