Quickstarters
Feature Overview
How to Build a Backend for htmx?
34 min
introduction in this tutorial, you’ll learn how to build a complete backend for htmx web apps using back4app we’ll walk through integrating essential back4app features such as database management, cloud code functions, rest and graphql apis, user authentication, file storage, and real time queries (live queries) to create a secure, scalable, and robust backend that seamlessly communicates with your htmx front end using htmx, a modern javascript library that leverages html attributes to handle client side interactions, can drastically improve the user experience while focusing on server side rendering by combining htmx with back4app’s powerful server side frameworks and template engines, developers can create full stack web apps with ease and efficiency by the end of this tutorial, you will have built a backend tailored for htmx integration, enabling smooth data operations and improving the client side experience with dynamic html page updates without full page reloads prerequisites to complete this tutorial, you will need a back4app account and a new back4app project getting started with back4app https //www back4app com/docs/get started/new parse app if you do not have an account, you can create one for free follow the guide above to get your project ready basic htmx setup include the htmx library https //htmx org/ in your html page using a web development environment ensure you have a local server setup or use server side frameworks to serve your html templates familiarity with html, css, and javascript htmx documentation https //htmx org/docs/ for more details on html attributes and web apps development make sure you have all of these prerequisites in place before you begin having your back4app project set up and your local htmx environment ready will help you follow along more easily step 1 – setting up back4app project create a new project the first step in building your htmx backend on back4app is creating a new project if you have not already created one, follow these steps log in to your back4app account click the “new app” button in your back4app dashboard give your app a name (e g , “htmx backend tutorial”) once the project is created, you will see it listed in your back4app dashboard this project will be the foundation for all backend configurations discussed in this tutorial connect via rest api back4app relies on the parse platform to manage your data, provide real time features, handle user authentication, and more while htmx itself is a client side library, connecting your htmx front end to back4app involves making rest api calls directly from your html and javascript retrieve your parse keys in your back4app dashboard, navigate to your app’s “app settings” or “security & keys” section to find your application id , rest api key , and the parse server url (often in the format https //parseapi back4app com ) with these keys, you can use htmx to call your backend endpoints and manipulate your html templates accordingly for example, you might use javascript fetch requests combined with htmx attributes to interact with your data via rest calls step 2 – setting up the database saving and querying data with your back4app project set up, you can now start saving and retrieving data using rest api calls, which you can trigger from htmx requests or plain javascript the simplest way to create a record is to make a post request to the parse server curl x post \\ h "x parse application id your application id" \\ h "x parse rest api key your rest api key" \\ h "content type application/json" \\ d '{"title" "buy groceries", "iscompleted" false}' \\ https //parseapi back4app com/classes/todo similarly, you can query data curl x get \\ h "x parse application id your application id" \\ h "x parse rest api key your rest api key" \\ https //parseapi back4app com/classes/todo you can also use graphql queries as needed to interact with your database from the client side schema design and data types by default, parse allows schema creation on the fly , but you can also define your classes and data types in the back4app dashboard for more control navigate to the “database” section in your back4app dashboard create a new class (e g , “todo”) and add relevant columns, such as title (string) and iscompleted (boolean) back4app supports various data types such as string , number , boolean , object , date , file , pointer, array, relation , geopoint , and polygon use these to design a robust schema for your htmx driven application back4app offers an ai agent that can help you design your data model open the ai agent from your app dashboard or on the menu describe your data model in simple language (e g , “please, create a new todo app at back4app with a complete class schema ”) let the ai agent create the schema for you using the ai agent can save you time when setting up your data architecture and ensure consistency across your application relational data if you have relational data, such as linking tasks to categories, you can use pointers or relations in parse via rest api calls for example, adding a pointer // example linking a task to a category using rest api async function createtaskforcategory(categoryid, title) { const response = await fetch('https //parseapi back4app com/classes/todo', { 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({ title title, category { type "pointer", classname "category", objectid categoryid } }) }); return response json(); } when you query, include pointer data as needed // example querying with pointer inclusion async function fetchtodos() { const response = await fetch('https //parseapi back4app com/classes/todo?include=category', { headers { 'x parse application id' 'your application id', 'x parse rest api key' 'your rest api key' } }); return response json(); } live queries for real time updates, back4app provides live queries while htmx focuses on server side rendering and html attributes, integrating live updates can enhance the user experience significantly enable live queries in your back4app dashboard under your app’s server settings make sure “live queries” is turned on initialize a live query subscription using javascript along with htmx triggers if necessary (note live queries typically require parse sdk; however, they can still work alongside htmx by updating parts of the page when data changes this example demonstrates the concept ) import parse from ' /parseconfig'; // this assumes use of the parse sdk in js environment async function subscribetotodos(callback) { const query = new parse query('todo'); const subscription = await query subscribe(); subscription on('create', (newtodo) => { console log('new todo created ', newtodo); callback('create', newtodo); }); subscription on('update', (updatedtodo) => { console log('todo updated ', updatedtodo); callback('update', updatedtodo); }); subscription on('delete', (deletedtodo) => { console log('todo deleted ', deletedtodo); callback('delete', deletedtodo); }); return subscription; } this subscription can then trigger htmx requests or update html templates dynamically to reflect changes on the client side step 3 – applying security with acls and clps back4app security mechanism back4app takes security seriously by providing access control lists (acls) and class level permissions (clps) these features let you restrict who can read or write data on a per object or per class basis, ensuring only authorized users can modify your data access control lists (acls) an acl is applied to individual objects to determine which users, roles, or the public can perform read/write operations for example async function createprivatetodo(title, owneruser) { const response = await fetch('https //parseapi back4app com/classes/todo', { 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({ title title, acl { \[owneruser id] { "read" true, "write" true }, " " { "read" false, "write" false } } }) }); return response json(); } when you save the object, it has an acl that prevents anyone but the specified user from reading or modifying it class level permissions (clps) clps govern an entire class’s default permissions, such as whether the class is publicly readable or writable, or if only certain roles can access it go to your back4app dashboard , select your app, and open the database section select a class (e g , “todo”) open the class level permissions tab configure your defaults, such as “requires authentication” for read or write, or “no access” for the public these permissions set the baseline, while acls fine tune permissions for individual objects a robust security model typically combines both clps (broad restrictions) and acls (fine grained per object restrictions) for more information go to app security guidelines https //www back4app com/docs/security/parse security step 4 – writing and deploying cloud functions cloud code is a feature of the parse server environment that allows you to run custom javascript code on the server side by writing cloud code, you can extend your back4app backend with additional business logic, validations, triggers, and integrations that run securely and efficiently on the parse server how it works when you write cloud code, you typically place your javascript functions, triggers, and any required npm modules in a main js file this file is then deployed to your back4app project, which is executed within the parse server environment // main js const axios = require('axios'); parse cloud define('fetchexternaldata', async (request) => { const url = request params url; if (!url) { throw new error('url parameter is required'); } const response = await axios get(url); return response data; }); parse cloud beforesave('todo', (request) => { const todo = request object; if (!todo get('title')) { throw new error('todo must have a title'); } }); deploy your cloud code using the back4app cli or through the dashboard calling your function from an htmx enhanced interface, you can call your cloud code functions using javascript fetch and update parts of your html page accordingly for example async function gettextlength(text) { const response = await fetch('https //parseapi back4app com/functions/calculatetextlength', { method 'post', headers { 'x parse application id' 'your app id', 'x parse rest api key' 'your rest api key', 'content type' 'application/json' }, body json stringify({ text }) }); const result = await response json(); console log('text length ', result result length); } you can integrate similar calls within your htmx triggers and html attributes to create dynamic, responsive behaviors on the client side, improving the overall user experience step 5 – configuring user authentication user authentication in back4app back4app leverages the parse user class as the foundation for authentication by default, parse handles password hashing, session tokens, and secure storage in the context of an htmx application, user authentication can be managed via rest calls initiated by html form submissions or javascript fetch requests setting up user authentication for example, to create a new user async function signupuser(username, password, email) { const response = await fetch('https //parseapi back4app com/users', { method 'post', headers { 'x parse application id' 'your app id', 'x parse rest api key' 'your rest api key', 'content type' 'application/json' }, body json stringify({ username, password, email }) }); return response json(); } similarly, for user login async function loginuser(username, password) { const response = await fetch(`https //parseapi back4app com/login?username=${encodeuricomponent(username)}\&password=${encodeuricomponent(password)}`, { headers { 'x parse application id' 'your app id', 'x parse rest api key' 'your rest api key' } }); return response json(); } session management after a successful login, parse creates a session token that you can store and manage in your htmx application for subsequent authenticated requests social login integration while htmx focuses on html attributes and server side interactions, integrating social logins such as google or facebook can still be achieved by initiating oauth flows and handling callbacks on the server side refer to social login docs https //www back4app com/docs/platform/sign in with apple for detailed guidance email verification and password reset to enable email verification and password reset navigate to the email settings in your back4app dashboard enable email verification and configure the necessary templates use fetch in your htmx flows to trigger password reset requests as needed step 6 – handling file storage uploading and retrieving files parse includes file storage capabilities which you can utilize via rest api calls from your htmx application for example, to upload an image async function uploadimage(file) { const data = new formdata(); data append('file', file); data append('object', '{" type" "file","name" "' + file name + '"}'); const response = await fetch('https //parseapi back4app com/files/' + file name, { method 'post', headers { 'x parse application id' 'your app id', 'x parse rest api key' 'your rest api key' }, body data }); return response json(); } file security control who can upload and access files by configuring security settings in back4app and setting acls on file objects as needed step 7 – scheduling tasks with cloud jobs cloud jobs cloud jobs in back4app let you schedule routine tasks on your backend, such as cleaning up old data or sending periodic emails these jobs run server side and can be integrated with your htmx workflow when needed // main js parse cloud job('cleanupoldtodos', async (request) => { const todo = parse object extend('todo'); const query = new parse query(todo); const now = new date(); const thirty days = 30 24 60 60 1000; const cutoff = new date(now thirty days); query lessthan('createdat', cutoff); try { const oldtodos = await query find({ usemasterkey true }); await parse object destroyall(oldtodos, { usemasterkey true }); return `deleted ${oldtodos length} old todos `; } catch (err) { throw new error('error during cleanup ' + err message); } }); schedule this job via the back4app dashboard under app settings > server settings > background jobs step 8 – integrating webhooks webhooks allow your back4app app to send http requests to an external service whenever certain events occur this is powerful for integrating with third party systems like payment gateways, email marketing tools, or analytics platforms navigate to the webhooks configuration in your back4app dashboard > more > webhooks and click on add webhook set up an endpoint (e g , https //your external service com/webhook endpoint https //your external service com/webhook endpoint ) configure triggers to specify which events in your back4app classes or cloud code functions will fire the webhook for instance, to notify a slack channel whenever a new todo is created create a slack app that accepts incoming webhooks copy the slack webhook url in your back4app dashboard, set the endpoint to that slack url for the event “new record in the todo class ” optionally, add custom http headers or payloads as needed you can also define webhooks in cloud code by making custom http requests in triggers step 9 – exploring the back4app admin panel the back4app admin app is a web based management interface designed for non technical users to perform crud operations and handle routine data tasks without writing any code it provides a model centric, user friendly interface that streamlines database administration, custom data management, and enterprise level operations enabling the admin app enable it by going to app dashboard > more > admin app and clicking on the “enable admin app” button create a first admin user (username/password), which automatically generates a new role (b4aadminuser) and classes (b4asetting, b4amenuitem, and b4acustomfield) in your app’s schema choose a subdomain for accessing the admin interface and complete the setup log in using the admin credentials you created to access your new admin app dashboard once enabled, the back4app admin app makes it easy to view, edit, or remove records from your database without requiring direct use of the parse dashboard or backend code conclusion by following this comprehensive tutorial on how to build a backend for htmx using back4app, you have created a secure backend tailored for htmx web apps configured a database with class schemas, data types, and relationships integrated real time queries and considered how live queries can enhance user experience on the client side applied security measures using acls and clps to protect and manage data access implemented cloud code functions to run custom business logic on the server side set up user authentication, file storage, scheduled cloud jobs, and integrated webhooks explored the back4app admin panel for efficient data management with this robust backend, you can now leverage htmx’s capabilities to create dynamic, modern web applications that combine client side enhancements with powerful server side frameworks this full stack approach enhances the overall user experience, providing smooth html page updates, efficient server side rendering, and seamless integration across your tech stack next steps extend this backend to incorporate more complex data models, advanced template engines, and custom server side logic explore integration with server side frameworks to create a more dynamic and responsive client side experience check out back4app’s official documentation for deeper dives into advanced security, performance tuning, and analytics continue learning about htmx and modern web development to build user friendly, responsive web apps that combine the best of client side and server side technologies once the project is created, you will see it listed in your back4app dashboard this project will be the foundation for all backend configurations discussed in this tutorial connect via rest api back4app relies on the parse platform to manage your data, provide real time features, handle user authentication, and more while htmx itself is a client side library, connecting your htmx front end to back4app involves making rest api calls directly from your html and javascript retrieve your parse keys in your back4app dashboard, navigate to your app’s “app settings” or “security & keys” section to find your application id , rest api key , and the parse server url (often in the format https //parseapi back4app com ) with these keys, you can use htmx to call your backend endpoints and manipulate your html templates accordingly for example, you might use javascript fetch requests combined with htmx attributes to interact with your data via rest calls step 2 – setting up the database saving and querying data with your back4app project set up, you can now start saving and retrieving data using rest api calls, which you can trigger from htmx requests or plain javascript the simplest way to create a record is to make a post request to the parse server curl x post \\ h "x parse application id your application id" \\ h "x parse rest api key your rest api key" \\ h "content type application/json" \\ d '{"title" "buy groceries", "iscompleted" false}' \\ https //parseapi back4app com/classes/todo similarly, you can query data curl x get \\ h "x parse application id your application id" \\ h "x parse rest api key your rest api key" \\ https //parseapi back4app com/classes/todo you can also use graphql queries as needed to interact with your database from the client side schema design and data types by default, parse allows schema creation on the fly , but you can also define your classes and data types in the back4app dashboard for more control navigate to the “database” section in your back4app dashboard create a new class (e g , “todo”) and add relevant columns, such as title (string) and iscompleted (boolean) back4app supports various data types such as string , number , boolean , object , date , file , pointer, array, relation , geopoint , and polygon use these to design a robust schema for your htmx driven application back4app offers an ai agent that can help you design your data model open the ai agent from your app dashboard or on the menu describe your data model in simple language (e g , “please, create a new todo app at back4app with a complete class schema ”) let the ai agent create the schema for you using the ai agent can save you time when setting up your data architecture and ensure consistency across your application relational data if you have relational data, such as linking tasks to categories, you can use pointers or relations in parse via rest api calls for example, adding a pointer // example linking a task to a category using rest api async function createtaskforcategory(categoryid, title) { const response = await fetch('https //parseapi back4app com/classes/todo', { 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({ title title, category { type "pointer", classname "category", objectid categoryid } }) }); return response json(); } when you query, include pointer data as needed // example querying with pointer inclusion async function fetchtodos() { const response = await fetch('https //parseapi back4app com/classes/todo?include=category', { headers { 'x parse application id' 'your application id', 'x parse rest api key' 'your rest api key' } }); return response json(); } live queries for real time updates, back4app provides live queries while htmx focuses on server side rendering and html attributes, integrating live updates can enhance the user experience significantly enable live queries in your back4app dashboard under your app’s server settings make sure “live queries” is turned on initialize a live query subscription using javascript along with htmx triggers if necessary (note live queries typically require parse sdk; however, they can still work alongside htmx by updating parts of the page when data changes this example demonstrates the concept ) import parse from ' /parseconfig'; // this assumes use of the parse sdk in js environment async function subscribetotodos(callback) { const query = new parse query('todo'); const subscription = await query subscribe(); subscription on('create', (newtodo) => { console log('new todo created ', newtodo); callback('create', newtodo); }); subscription on('update', (updatedtodo) => { console log('todo updated ', updatedtodo); callback('update', updatedtodo); }); subscription on('delete', (deletedtodo) => { console log('todo deleted ', deletedtodo); callback('delete', deletedtodo); }); return subscription; } this subscription can then trigger htmx requests or update html templates dynamically to reflect changes on the client side step 3 – applying security with acls and clps back4app security mechanism back4app takes security seriously by providing access control lists (acls) and class level permissions (clps) these features let you restrict who can read or write data on a per object or per class basis, ensuring only authorized users can modify your data access control lists (acls) an acl is applied to individual objects to determine which users, roles, or the public can perform read/write operations for example async function createprivatetodo(title, owneruser) { const response = await fetch('https //parseapi back4app com/classes/todo', { 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({ title title, acl { \[owneruser id] { "read" true, "write" true }, " " { "read" false, "write" false } } }) }); return response json(); } when you save the object, it has an acl that prevents anyone but the specified user from reading or modifying it class level permissions (clps) clps govern an entire class’s default permissions, such as whether the class is publicly readable or writable, or if only certain roles can access it go to your back4app dashboard , select your app, and open the database section select a class (e g , “todo”) open the class level permissions tab configure your defaults, such as “requires authentication” for read or write, or “no access” for the public these permissions set the baseline, while acls fine tune permissions for individual objects a robust security model typically combines both clps (broad restrictions) and acls (fine grained per object restrictions) for more information go to app security guidelines https //www back4app com/docs/security/parse security step 4 – writing and deploying cloud functions cloud code is a feature of the parse server environment that allows you to run custom javascript code on the server side by writing cloud code, you can extend your back4app backend with additional business logic, validations, triggers, and integrations that run securely and efficiently on the parse server how it works when you write cloud code, you typically place your javascript functions, triggers, and any required npm modules in a main js file this file is then deployed to your back4app project, which is executed within the parse server environment // main js const axios = require('axios'); parse cloud define('fetchexternaldata', async (request) => { const url = request params url; if (!url) { throw new error('url parameter is required'); } const response = await axios get(url); return response data; }); parse cloud beforesave('todo', (request) => { const todo = request object; if (!todo get('title')) { throw new error('todo must have a title'); } }); deploy your cloud code using the back4app cli or through the dashboard calling your function from an htmx enhanced interface, you can call your cloud code functions using javascript fetch and update parts of your html page accordingly for example async function gettextlength(text) { const response = await fetch('https //parseapi back4app com/functions/calculatetextlength', { method 'post', headers { 'x parse application id' 'your app id', 'x parse rest api key' 'your rest api key', 'content type' 'application/json' }, body json stringify({ text }) }); const result = await response json(); console log('text length ', result result length); } you can integrate similar calls within your htmx triggers and html attributes to create dynamic, responsive behaviors on the client side, improving the overall user experience step 5 – configuring user authentication user authentication in back4app back4app leverages the parse user class as the foundation for authentication by default, parse handles password hashing, session tokens, and secure storage in the context of an htmx application, user authentication can be managed via rest calls initiated by html form submissions or javascript fetch requests setting up user authentication for example, to create a new user async function signupuser(username, password, email) { const response = await fetch('https //parseapi back4app com/users', { method 'post', headers { 'x parse application id' 'your app id', 'x parse rest api key' 'your rest api key', 'content type' 'application/json' }, body json stringify({ username, password, email }) }); return response json(); } similarly, for user login async function loginuser(username, password) { const response = await fetch(`https //parseapi back4app com/login?username=${encodeuricomponent(username)}\&password=${encodeuricomponent(password)}`, { headers { 'x parse application id' 'your app id', 'x parse rest api key' 'your rest api key' } }); return response json(); } session management after a successful login, parse creates a session token that you can store and manage in your htmx application for subsequent authenticated requests social login integration while htmx focuses on html attributes and server side interactions, integrating social logins such as google or facebook can still be achieved by initiating oauth flows and handling callbacks on the server side refer to social login docs https //www back4app com/docs/platform/sign in with apple for detailed guidance email verification and password reset to enable email verification and password reset navigate to the email settings in your back4app dashboard enable email verification and configure the necessary templates use fetch in your htmx flows to trigger password reset requests as needed step 6 – handling file storage uploading and retrieving files parse includes file storage capabilities which you can utilize via rest api calls from your htmx application for example, to upload an image async function uploadimage(file) { const data = new formdata(); data append('file', file); data append('object', '{" type" "file","name" "' + file name + '"}'); const response = await fetch('https //parseapi back4app com/files/' + file name, { method 'post', headers { 'x parse application id' 'your app id', 'x parse rest api key' 'your rest api key' }, body data }); return response json(); } file security control who can upload and access files by configuring security settings in back4app and setting acls on file objects as needed step 7 – scheduling tasks with cloud jobs cloud jobs cloud jobs in back4app let you schedule routine tasks on your backend, such as cleaning up old data or sending periodic emails these jobs run server side and can be integrated with your htmx workflow when needed // main js parse cloud job('cleanupoldtodos', async (request) => { const todo = parse object extend('todo'); const query = new parse query(todo); const now = new date(); const thirty days = 30 24 60 60 1000; const cutoff = new date(now thirty days); query lessthan('createdat', cutoff); try { const oldtodos = await query find({ usemasterkey true }); await parse object destroyall(oldtodos, { usemasterkey true }); return `deleted ${oldtodos length} old todos `; } catch (err) { throw new error('error during cleanup ' + err message); } }); schedule this job via the back4app dashboard under app settings > server settings > background jobs step 8 – integrating webhooks webhooks allow your back4app app to send http requests to an external service whenever certain events occur this is powerful for integrating with third party systems like payment gateways, email marketing tools, or analytics platforms navigate to the webhooks configuration in your back4app dashboard > more > webhooks and click on add webhook set up an endpoint (e g , https //your external service com/webhook endpoint https //your external service com/webhook endpoint ) configure triggers to specify which events in your back4app classes or cloud code functions will fire the webhook for instance, to notify a slack channel whenever a new todo is created create a slack app that accepts incoming webhooks copy the slack webhook url in your back4app dashboard, set the endpoint to that slack url for the event “new record in the todo class ” optionally, add custom http headers or payloads as needed you can also define webhooks in cloud code by making custom http requests in triggers step 9 – exploring the back4app admin panel the back4app admin app is a web based management interface designed for non technical users to perform crud operations and handle routine data tasks without writing any code it provides a model centric, user friendly interface that streamlines database administration, custom data management, and enterprise level operations enabling the admin app enable it by going to app dashboard > more > admin app and clicking on the “enable admin app” button create a first admin user (username/password), which automatically generates a new role (b4aadminuser) and classes (b4asetting, b4amenuitem, and b4acustomfield) in your app’s schema choose a subdomain for accessing the admin interface and complete the setup log in using the admin credentials you created to access your new admin app dashboard once enabled, the back4app admin app makes it easy to view, edit, or remove records from your database without requiring direct use of the parse dashboard or backend code conclusion by following this comprehensive tutorial on how to build a backend for htmx using back4app, you have created a secure backend tailored for htmx web apps configured a database with class schemas, data types, and relationships integrated real time queries and considered how live queries can enhance user experience on the client side applied security measures using acls and clps to protect and manage data access implemented cloud code functions to run custom business logic on the server side set up user authentication, file storage, scheduled cloud jobs, and integrated webhooks explored the back4app admin panel for efficient data management with this robust backend, you can now leverage htmx’s capabilities to create dynamic, modern web applications that combine client side enhancements with powerful server side frameworks this full stack approach enhances the overall user experience, providing smooth html page updates, efficient server side rendering, and seamless integration across your tech stack next steps extend this backend to incorporate more complex data models, advanced template engines, and custom server side logic explore integration with server side frameworks to create a more dynamic and responsive client side experience check out back4app’s official documentation for deeper dives into advanced security, performance tuning, and analytics continue learning about htmx and modern web development to build user friendly, responsive web apps that combine the best of client side and server side technologies