Quickstarters
Feature Overview
How to Build a Backend for NativeScript?
47 min
introduction in this tutorial, you'll learn how to buila a backend for nativescript using back4app, an open source platform that simplifies backend development for mobile apps we'll walk through integrating essential back4app features—like database management, cloud code functions, rest and graphql api endpoints, user authentication, and real time queries (live queries)—to create a secure and scalable backend for your nativescript apps you'll also discover how back4app drastically reduces setup time compared to manual server and database configurations we will explore advanced security mechanisms, scheduling tasks with cloud jobs, and using webhooks to connect with third party services by the end of this guide, you'll have a flexible backend that takes advantage of nativescript core, which powers nativescript’s cross platform mobile solutions with this foundation, you'll be ready to integrate your own custom logic or external apis as needed this will be a major step toward developing production ready nativescript apps prerequisites 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 nativescript development environment you can set this up using the nativescript cli or another preferred workflow nativescript getting started guide https //docs nativescript org/environment setup node js (version 14 or above) installed you will need node js for installing npm packages and running the nativescript cli installing node js https //nodejs org/en/download/ familiarity with javascript and nativescript core nativescript official documentation https //docs nativescript org/ if you’re new to nativescript, review the official docs or a beginner’s tutorial before starting make sure you have all these prerequisites in place before you begin having your back4app project set up and your local nativescript 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 nativescript backend on back4app is creating a new project if you haven't already, 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 , “nativescript backend tutorial”) after creating the project, you’ll see it listed in your back4app dashboard this project will serve as the foundation for all backend configurations covered in this tutorial connect the parse sdk back4app uses the parse platform to handle your data, real time functionality, user authentication, and more to connect your nativescript app to back4app, install the parse npm package and initialize it with the credentials you get from your back4app dashboard retrieve your parse keys in your back4app dashboard, go to your app’s “app settings” or “security & keys” section look for your application id , javascript key , and parse server url (in the format https //parseapi back4app com ) install the parse sdk npm install parse then, initialize parse in a configuration file or your main entry file (e g , app js ) for example, you might create a file named parseconfig js in a nativescript based project src/parseconfig js import parse from 'parse'; // replace the placeholders with your back4app credentials parse initialize('your application id', 'your javascript key'); parse serverurl = 'https //parseapi back4app com'; export default parse; whenever you need to access parse in your nativescript app, simply import this file by completing this step, you have established a secure connection between your nativescript frontend and the back4app backend, simplifying data operations step 2 – setting up the database saving and querying data with your back4app project ready and the parse sdk integrated, you can save and query data from your nativescript app below is an example using the parse object class to save and fetch a list of items // example create a task item import parse from ' /parseconfig'; async function createtaskitem(title, iscompleted) { const task = parse object extend('task'); const task = new task(); task set('title', title); task set('iscompleted', iscompleted); try { const savedtask = await task save(); console log('task saved successfully ', savedtask); return savedtask; } catch (error) { console error('error saving task ', error); } } // example query all task items async function fetchtasks() { const task = parse object extend('task'); const query = new parse query(task); try { const results = await query find(); console log('fetched task items ', results); return results; } catch (error) { console error('error fetching tasks ', error); } } you can also use back4app’s rest api if you prefer direct http calls 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 supplies", "iscompleted" false}' \\ https //parseapi back4app com/classes/task or use graphql mutation { createtask(input { fields { title "clean the house" iscompleted false } }) { task { objectid title iscompleted } } } this flexibility makes it convenient to build backend features for your nativescript apps through the parse sdk, rest, or graphql api endpoints schema design and data types by default, parse can automatically create schema on the fly, or you can define your classes and data types in the back4app dashboard go to the “database” section in your back4app dashboard create a new class (e g , “task”) and add columns like title (string) and iscompleted (boolean) back4app supports data types like string , number , boolean , object , date , file , pointer , array , relation , geopoint , and polygon you can either let parse create these columns when you first save an object or define them for more control using back4app’s ai agent can also help you auto generate schemas open the ai agent in your app dashboard describe your desired data model (e g , “please create a new task class for mobile apps with iscompleted and duedate fields ”) let the agent create the schema automatically relational data if you want relational data—like a category object that points to multiple task items—use pointers or relations in parse // linking a task to a category with a pointer async function createtaskforcategory(categoryobjectid, title) { const task = new parse object('task'); const categorypointer = new parse object('category'); categorypointer id = categoryobjectid; task set('title', title); task set('category', categorypointer); try { return await task save(); } catch (err) { console error('error creating task with category relationship ', err); } } // including the pointer data in a query const query = new parse query('task'); query include('category'); const taskswithcategory = await query find(); this approach helps you fetch complete data for a task and its related category in a single query live queries for real time updates, enable live queries under server settings in the back4app dashboard nativescript developers can subscribe to changes in a specific class update your parse setup to include a live query server url src/parseconfig js import parse from 'parse'; // replace the placeholders with your back4app credentials parse initialize('your application id', 'your javascript key'); parse serverurl = 'https //parseapi back4app com'; parse livequeryserverurl = 'wss\ //your subdomain here b4a io'; export default parse; and then subscribe to real time events import parse from ' /parseconfig'; async function subscribetotasks(callback) { const query = new parse query('task'); const subscription = await query subscribe(); subscription on('create', (newtask) => { console log('new task created ', newtask); callback('create', newtask); }); subscription on('update', (updatedtask) => { console log('task updated ', updatedtask); callback('update', updatedtask); }); subscription on('delete', (deletedtask) => { console log('task deleted ', deletedtask); callback('delete', deletedtask); }); return subscription; } this subscription automatically updates your ui whenever a task is added, modified, or removed—perfect for live, collaborative nativescript apps step 3 – applying security with acls and clps back4app security mechanism back4app incorporates access control lists (acls) and class level permissions (clps) to safeguard your data these security models let you control read/write access both at the class and object levels access control lists (acls) an acl sets permissions for each object for instance, to give only the owner read and write access async function createprivatetask(title, owneruser) { const task = parse object extend('task'); const task = new task(); task set('title', title); const acl = new parse acl(owneruser); acl setpublicreadaccess(false); acl setpublicwriteaccess(false); task setacl(acl); try { return await task save(); } catch (err) { console error('error saving private task ', err); } } this ensures only the specified user can modify or read the object class level permissions (clps) clps set the default permissions for an entire class open the database in back4app and select the relevant class access the class level permissions tab adjust permissions for the public, authenticated users, or specific roles as needed combining acls and clps offers a strong security model for nativescript apps for more info, see app security guidelines https //www back4app com/docs/security/parse security step 4 – writing and deploying cloud functions cloud code lets you run custom javascript code on the server side, so you don't need to maintain infrastructure yourself this is ideal for adding advanced logic or server only integrations in your nativescript backend how it works you typically place your cloud code (javascript functions, triggers, and any required npm modules) in a main js file then you deploy it to back4app, and it runs in the parse server environment without additional server configuration example main js structure 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('task', (request) => { const task = request object; if (!task get('title')) { throw new error('task must have a title'); } }); you can install and use npm packages like axios for http requests this approach enables a wide range of integrations, from payment gateways to external apis, all behind the security of your back4app app typical use cases business logic automatic calculations, data transformations, or status updates data validations ensure required fields are present before saving triggers run code when data is created, updated, or deleted integrations connect with external services for payments, analytics, or messaging security enforcement validate incoming data or user roles before proceeding deploy your function here’s a simple function that computes text length main js parse cloud define('calculatetextlength', async (request) => { const { text } = request params; if (!text) { throw new error('no text provided'); } return { length text length }; }); deploying via https //www back4app com/docs/local development/parse cli install the cli curl https //raw\ githubusercontent com/back4app/parse cli/back4app/installer sh | sudo /bin/bash for windows, download the b4a exe https //github com/back4app/parse cli/releases/download/release 3 3 1/b4a exe file from the releases page https //github com/back4app/parse cli/releases configure your account key b4a configure accountkey deploy your cloud code b4a deploy deploying through the dashboard go to cloud code > functions in your dashboard paste your function code into main js click deploy calling your function from your nativescript app using the parse sdk import parse from ' /parseconfig'; async function gettextlength(text) { try { const result = await parse cloud run('calculatetextlength', { text }); console log('text length ', result length); } catch (err) { console error('error calling cloud function ', err); } } you can also call it using rest or graphql curl x post \\ h "x parse application id your app id" \\ h "x parse rest api key your rest api key" \\ h "content type application/json" \\ d '{"text" "hello back4app"}' \\ https //parseapi back4app com/functions/calculatetextlength mutation { calculatetextlength(input { text "hello graphql" }) { result } } this gives you a flexible way to integrate server side logic into your nativescript based mobile apps step 5 – configuring user authentication user authentication in back4app back4app uses the parse user class to handle authentication, which includes password hashing, session tokens, and more this eliminates much of the complexity associated with managing user accounts setting up user authentication in your nativescript app, you can create a new user import parse from ' /parseconfig'; async function signupuser(username, password, email) { const user = new parse user(); user set('username', username); user set('password', password); user set('email', email); try { await user signup(); console log('user signed up successfully!'); } catch (error) { console error('error signing up user ', error); } } async function loginuser(username, password) { try { const user = await parse user login(username, password); console log('user logged in ', user); } catch (error) { console error('error logging in user ', error); } } a rest example might look like curl x get \\ h "x parse application id your app id" \\ h "x parse rest api key your rest api key" \\ g \\ \ data urlencode 'username=alice' \\ \ data urlencode 'password=secret123' \\ https //parseapi back4app com/login session management after logging in, parse assigns a session token to the user to check the currently logged in user const currentuser = parse user current(); if (currentuser) { console log('logged in user ', currentuser getusername()); } else { console log('no user is logged in'); } logging out is simple await parse user logout(); social login integration parse also integrates with oauth providers like google or facebook setup varies per provider, so see sign in with apple and others https //www back4app com/docs/platform/sign in with apple for details for instance, with facebook const facebooklogin = async () => { try { const user = await parse facebookutils login('email'); console log(user existed() ? 'user logged in' 'user signed up and logged in'); } catch (error) { console error('error logging in with facebook ', error); } }; email verification and password reset enable these features in your back4app dashboard navigate to email settings in your back4app app enable email verification and password reset configure your email templates and “from” address step 6 – handling file storage uploading and retrieving files back4app supports file management through the parse file class in nativescript, you can upload images or documents similarly import parse from ' /parseconfig'; async function uploadimage(file) { const name = file name; const parsefile = new parse file(name, file); try { const savedfile = await parsefile save(); console log('file saved ', savedfile url()); return savedfile url(); } catch (err) { console error('error uploading file ', err); } } async function createphotoobject(file) { const photo = parse object extend('photo'); const photo = new photo(); const parsefile = new parse file(file name, file); photo set('imagefile', parsefile); return await photo save(); } you can retrieve the file’s url from the saved object const imagefile = photo get('imagefile'); const imageurl = imagefile url(); // use imageurl in your nativescript ui components file security parse server lets you configure file upload security { "fileupload" { "enableforpublic" true, "enableforanonymoususer" true, "enableforauthenticateduser" true } } this ensures you can limit or allow file uploads based on your security preferences step 7 – scheduling tasks with cloud jobs cloud jobs cloud jobs help you automate routine tasks, like removing stale records or sending notifications for example // main js parse cloud job('cleanupoldtasks', async (request) => { const task = parse object extend('task'); const query = new parse query(task); 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 oldtasks = await query find({ usemasterkey true }); await parse object destroyall(oldtasks, { usemasterkey true }); return `deleted ${oldtasks length} old tasks `; } catch (err) { throw new error('cleanup error ' + err message); } }); deploy this job via cli or the dashboard in the back4app dashboard > server settings > background jobs , schedule it to run daily or at an interval of your choice step 8 – integrating webhooks webhooks let you send http requests to external services when certain events happen in your app—like new records or user signups this can be used to integrate with slack, payment gateways, or analytics platforms go to the webhooks configuration in your back4app dashboard and select add webhook add your endpoint url (e g , https //your service com/webhook ) configure triggers for specific classes or events you can also define webhooks in cloud code or call external apis directly in triggers like beforesave or aftersave step 9 – exploring the back4app admin panel the back4app admin app is a model centric, user friendly interface for data management it helps teams or non technical users perform crud operations, create custom dashboards, and manage enterprise level tasks without writing code enabling the admin app in your app dashboard , click more > admin app enable admin app create a first admin user (username/password) this setup adds the b4aadminuser role and associated classes ( b4asetting , b4amenuitem , etc ) to your schema choose a subdomain, then log in with your new admin credentials this portal allows for quick data manipulation without leaving a graphical interface—a great solution for collaborating with team members who might not be familiar with coding conclusion by following this guide, you have learned how to buila a backend for nativescript using back4app and created a secure backend for your nativescript apps configured a database with classes, schemas, and relationships implemented real time queries for live updates secured your data with acls and clps extended functionality with cloud code set up authentication for user sign up, login, and session tokens managed file uploads and retrieval via parse file scheduled cloud jobs for automated, periodic tasks created webhooks for third party integrations used the back4app admin panel for code free data management these steps form a robust foundation for building open source, cross platform mobile apps with nativescript core continue exploring advanced features, incorporate more api endpoints, or integrate your own custom logic to tailor the backend to your app’s exact needs next steps scale your nativescript apps by optimizing performance, caching, and security rules explore advanced user management like role based permissions check out official back4app documentation for in depth guides on security, logs, and performance experiment with real world integrations such as payments or analytics tools happy coding, and enjoy the streamlined development workflow that back4app provides!