Quickstarters
CRUD Samples
Building a Basic CRUD Application with Cycle.js: A Comprehensive Guide
41 min
overview this guide will walk you through constructing a full featured crud (create, read, update, and delete) application using cycle js in this tutorial, you'll configure a back4app project titled basic crud app cyclejs which will serve as a robust backend for your application you'll learn to design a scalable data model, manage your data via the intuitive back4app admin app, and integrate your cycle js frontend with back4app using rest/graphql calls by the end, you'll have a production ready web app capable of executing crud operations along with user authentication and secure data handling key insights build a functional crud system with a reliable backend gain practical experience in architecting a scalable data model utilize a drag and drop admin tool for seamless data management integrate a cycle js frontend with back4app through rest/graphql learn deployment strategies including docker containerization prerequisites before you begin, ensure you have a back4app account with an active project if you need assistance, check out getting started with back4app https //www back4app com/docs/get started/new parse app a cycle js development setup use tools like create cycle app https //github com/cyclejs community/create cycle app and ensure node js (version 14 or later) is installed familiarity with javascript, cycle js, and rest apis for a refresher, consult the cycle js documentation https //cycle js org/ step 1 – project initialization creating a new back4app project sign in to your back4app account press the “new app” button on your dashboard assign the project name basic crud app cyclejs and follow the setup prompts create new project after creation, your project will be visible on the dashboard, ready for backend configuration and management step 2 – defining your database schema structuring your data model for this crud application, you'll create several collections to manage your data below are example collections with essential fields and data types 1\ items collection this collection will store the details of each item field data type description id objectid auto generated unique identifier title string the item’s title description string a brief summary of the item created at date the timestamp for when the item was added updated at date the timestamp for the latest update 2\ users collection this collection handles user details and authentication field data type description id objectid auto generated unique identifier username string the user’s unique identifier email string the user’s email address password hash string encrypted password for secure authentication created at date account creation timestamp updated at date timestamp for the most recent update you can define these collections manually via the back4app dashboard by creating new classes and configuring the corresponding fields create new class to add fields, choose the data type, provide a field name, optionally set a default value, and mark the field as required if needed create column automating schema creation with the back4app ai agent the back4app ai agent simplifies schema creation by automatically generating your data model based on a provided prompt this ensures a consistent and efficient database design steps to utilize the ai agent access the ai agent log into your back4app dashboard and select the ai agent from the menu or project settings detail your data requirements input a comprehensive prompt that lists the necessary collections and their fields review and implement examine the auto generated schema and apply it 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 feature not only saves time but also ensures a well structured and optimized schema step 3 – activating the admin app & managing crud operations exploring the admin app the back4app admin app provides a no code, drag and drop interface for effortless backend data management it streamlines crud operations for your collections enabling the admin app open the “more” menu in your back4app dashboard select “admin app” and then click on “enable admin app ” set up your admin credentials by creating your first admin user this action will also initialize system roles (e g , b4aadminuser ) enable admin app after activation, sign in to the admin app to begin managing your collections admin app dashboard performing crud operations via the admin app within the admin app, you can add records click the “add record” button in any collection (e g , items) to insert new entries view/modify records select an existing record to inspect details or modify fields remove records utilize the delete option to discard unwanted entries this user friendly interface greatly enhances the management and administration of your data step 4 – integrating cycle js with back4app now that your backend is operational via back4app, it's time to integrate your cycle js frontend option utilizing rest/graphql apis we'll focus on rest api calls to interact with your backend below is an example cycle js component that retrieves and displays items from your back4app database using cycle's http driver example fetching and displaying items with cycle js import xs from 'xstream'; import {run} from '@cycle/run'; import {div, h1, ul, li, input, button, makedomdriver} from '@cycle/dom'; import {makehttpdriver} from '@cycle/http'; function main(sources) { // intent capture add item interactions const addclick$ = sources dom select(' add') events('click'); // model make an http request to fetch items const request$ = xs of({ url 'https //parseapi back4app com/classes/items', category 'items', method 'get', headers { 'x parse application id' 'your application id', 'x parse rest api key' 'your rest api key' } }); // intent handle http responses const items$ = sources http select('items') flatten() map(res => res body results); // view render the items list const vdom$ = items$ startwith(\[]) map(items => div(\[ h1('items'), button(' add', 'add item'), ul( items map(item => li(`${item title} — ${item description}`) ) ) ]) ); return { dom vdom$, http request$ }; } const drivers = { dom makedomdriver('#app'), http makehttpdriver() }; run(main, drivers); this sample code demonstrates how to use cycle js to perform an http get request to fetch items and render them dynamically step 5 – securing your backend applying access control lists (acls) secure your objects by defining acls for example, when creating a private item async function createprivateitem(data, owneruser) { const newitem = { title data title, description data description }; // define acl restrict access to the owner only newitem acl = { \[owneruser id] { read true, write true }, ' ' { read false, write false } }; try { const response = await fetch('https //parseapi back4app com/classes/items', { 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(newitem) }); const result = await response json(); console log('created item ', result); } catch (error) { console error('error creating item ', error); } } configuring class level permissions (clps) within the back4app dashboard, adjust clps for each collection to ensure only authenticated users can access sensitive information step 6 – implementing user authentication setting up account registration and login back4app utilizes a user class for authentication use rest api calls to manage user sign ups and logins within your cycle js application below is an example of handling user registration async function signupuser(userdata) { 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({ username userdata username, password userdata password, email userdata email }) }); const result = await response json(); alert('registration successful!'); return result; } catch (error) { alert('registration error ' + error message); } } you can replicate similar patterns for user login and session management step 7 – deploying your cycle js frontend with web deployment back4app’s web deployment feature lets you host your cycle js application effortlessly via integration with your github repository 7 1 preparing your production build open your project directory in a terminal run the build command npm run build this creates a build directory with optimized static files confirm the build ensure the build folder contains an index html and related asset directories 7 2 organizing and uploading your source code your git repository should include the entire cycle js application source an example file structure basic crud app cyclejs frontend/ ├── node modules/ ├── public/ │ └── index html ├── src/ │ ├── main js │ ├── httpdrivers js │ └── components/ │ ├── itemslist js │ └── auth js ├── package json └── readme md example file src/main js import xs from 'xstream'; import {run} from '@cycle/run'; import {div, h1, makedomdriver} from '@cycle/dom'; import {makehttpdriver} from '@cycle/http'; import itemslist from ' /components/itemslist'; function main(sources) { const itemsvtree$ = itemslist(sources); const vdom$ = itemsvtree$ map(tree => div(\[ h1('cycle js crud application'), tree ]) ); return { dom vdom$ }; } const drivers = { dom makedomdriver('#app'), http makehttpdriver() }; run(main, drivers); committing to github initialize a git repository (if not already done) git init stage your files git add commit your work git commit m "initial commit for cycle js frontend" create a github repository (e g , basic crud app cyclejs frontend ) push your repository git remote add origin https //github com/your username/basic crud app cyclejs frontend git git push u origin main 7 3 linking your repository with web deployment access web deployment sign in to back4app, navigate to your project ( basic crud app cyclejs ), and select the web deployment feature connect to github follow the prompts to link your github account so back4app can access your repository select the repository and branch choose your repository (e g , basic crud app cyclejs frontend ) and the branch (typically main ) 7 4 deployment settings build command if your repository lacks a pre built build folder, specify a build command (e g , npm run build ) output directory set this to build so back4app knows where to find the static files environment variables include any necessary api keys or configuration details 7 5 dockerizing your cycle js application if you opt for docker deployment, add a dockerfile to your repository \# use an official node image for building the app from node 16 alpine as build \# set working directory workdir /app \# copy dependency definitions copy package json / \# install dependencies run npm install \# copy the remaining files copy \# build the cycle js application run npm run build \# use nginx to serve the built files from nginx\ stable alpine copy from=build /app/build /usr/share/nginx/html expose 80 cmd \["nginx", " g", "daemon off;"] select the docker deployment option in your web deployment configuration if you choose to containerize your app 7 6 launching your application deploy your app click the deploy button after configuring your settings monitor the deployment back4app will pull your code from github, build the app (if configured), and deploy it access your application once deployment is complete, back4app will provide a url for your live cycle js application 7 7 testing your deployment visit the deployed url open the provided url in your browser confirm functionality ensure all routes and assets load properly debug if necessary use browser developer tools and review back4app deployment logs to troubleshoot any issues step 8 – wrapping up and future enhancements congratulations! you have successfully built a crud application using cycle js and back4app you've set up a project titled basic crud app cyclejs , defined your database schema for items and users, and managed your data via the intuitive admin app additionally, you've integrated your cycle js frontend with your backend using rest/graphql and secured your data with proper access controls next steps expand your frontend add more advanced views, filtering, or real time updates integrate additional backend features consider adding cloud functions, third party apis, or role based access control further learning explore the back4app documentation https //www back4app com/docs for additional insights on performance tuning and custom integrations with this guide, you now possess the skills to build a scalable crud backend for your cycle js application using back4app happy coding!