Quickstarters
Feature Overview
How to Build a Backend for NodeJS?
52 min
introduction in this tutorial, you’ll learn how to build a complete backend for a nodejs application using back4app we’ll walk through integrating essential back4app features such as database management, cloud code functions, rest and graphql apis, user authentication, and real time queries (live queries) to create a secure, scalable, and robust backend that seamlessly communicates with your nodejs code you’ll also see how back4app’s quick setup and intuitive environment can drastically reduce the time and effort compared to manually configuring servers and databases along the way, you’ll gain hands on experience with key functionalities, including advanced security features, scheduling tasks with cloud jobs, and setting up webhooks for external integrations by the end of this tutorial, you’ll be well prepared to enhance this foundational setup into a production ready application, or easily incorporate custom logic and third party apis as needed 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 node js (version 14 or above) installed you will need node js for installing npm packages and running your backend server installing node js https //nodejs org/en/download/ a basic nodejs setup you can initialize a node project by running npm init (or yarn init ) ensure you have a package json file for managing your dependencies familiarity with javascript and basic nodejs concepts nodejs official documentation https //nodejs org/en/docs/ if you’re new to node, review the official docs or a beginner’s tutorial before starting make sure you have all of these prerequisites in place before you begin having your back4app project set up and your local nodejs 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 nodejs 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 , “nodejs 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 the parse sdk back4app relies on the parse platform to manage your data, provide real time features, handle user authentication, and more connecting your nodejs application to back4app involves installing the parse npm package and initializing it with the credentials from your back4app dashboard retrieve your parse keys in your back4app dashboard, navigate to your app’s “app settings” or “security & keys” section to find your application id and javascript key you will also find the parse server url (often in the format https //parseapi back4app com ) install the parse sdk in your nodejs project npm install parse if you’re using yarn, you can install it with yarn add parse initialize parse in your nodejs application create a file (e g , parseconfig js ) at the root of your node project src/parseconfig js const parse = require('parse/node'); // replace the placeholders with your back4app credentials parse initialize('your application id', 'your javascript key'); parse serverurl = 'https //parseapi back4app com'; module exports = parse; then, in your main entry file (e g , index js ), import parse to establish the connection const parse = require(' /src/parseconfig'); // your nodejs logic here, now fully connected to back4app by completing this step, you have established a secure connection between your nodejs backend and the back4app infrastructure all requests and data transactions are securely routed through this sdk, reducing the complexity of manual rest or graphql calls (although you can still use them when needed) step 2 – setting up the database saving and querying data with your back4app project set up and the parse sdk integrated into your node app, you can now start saving and retrieving data the simplest way to create a record is to use the parse object class // example create a todo item const parse = require(' /src/parseconfig'); async function createtodoitem(title, iscompleted) { const todo = parse object extend('todo'); const todo = new todo(); todo set('title', title); todo set('iscompleted', iscompleted); try { const savedtodo = await todo save(); console log('todo saved successfully ', savedtodo); return savedtodo; } catch (error) { console error('error saving todo ', error); } } // example query all todo items async function fetchtodos() { const todo = parse object extend('todo'); const query = new parse query(todo); try { const results = await query find(); console log('fetched todo items ', results); return results; } catch (error) { console error('error fetching todos ', error); } } alternatively, you can use back4app’s rest api endpoints 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 back4app also provides a graphql interface mutation { createtodo(input { fields { title "clean the house" iscompleted false } }) { todo { objectid title iscompleted } } } these diverse options let you integrate data operations in the way that best suits your development process whether that's through the parse sdk, rest, or graphql 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 also supports various data types string , number , boolean , object , date , file , pointer , array , relation , geopoint , and polygon you can choose the appropriate type for each field if you prefer, you can also let parse automatically create these columns when you first save an object from your node app 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 say, a category object that points to multiple todo items you can use pointers or relations in parse for example, adding a pointer to a category // linking a task to a category with a pointer async function createtaskforcategory(categoryobjectid, title) { const todo = new parse object('todo'); // construct a pointer to the category const categorypointer = new parse object('category'); categorypointer id = categoryobjectid; // set fields todo set('title', title); todo set('category', categorypointer); try { return await todo save(); } catch (err) { console error('error creating task with category relationship ', err); } } when you query, you can also include pointer data const query = new parse query('todo'); query include('category'); const todoswithcategory = await query find(); this include('category') call fetches category details alongside each todo, making your relational data seamlessly accessible live queries for real time updates, back4app provides live queries in your nodejs app, you can subscribe to changes in a specific class 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 in your code src/parseconfig js const parse = require('parse/node'); // replace the placeholders with your back4app credentials parse initialize('your application id', 'your javascript key'); parse serverurl = 'https //parseapi back4app com'; // live query's subdomain parse livequeryserverurl = 'wss\ //your subdomain here b4a io'; module exports = parse; const parse = require(' /parseconfig'); 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; } by subscribing, you receive real time notifications whenever a new todo is created, updated, or deleted this feature is particularly valuable for collaborative or dynamic apps where multiple users need to see the latest data without manually polling the server 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 todo = parse object extend('todo'); const todo = new todo(); todo set('title', title); // create an acl granting read/write access only to the owner const acl = new parse acl(owneruser); acl setpublicreadaccess(false); acl setpublicwriteaccess(false); todo setacl(acl); try { return await todo save(); } catch (err) { console error('error saving private todo ', err); } } 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 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 without needing to manage your servers or infrastructure 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 (or another js file) and deploy it to your back4app project this code is then executed within the parse server environment since these functions and triggers run on the server, you can trust them to handle confidential logic, process sensitive data, or make backend only api calls processes you might not want to expose directly to the client all cloud code for your back4app app runs inside the parse server that is managed by back4app, so you don’t have to worry about server maintenance, scaling, or provisioning whenever you update and deploy your file, the running parse server is updated with your latest code main js file structure a typical main js might contain require statements for any needed modules (npm packages, built in node modules, or other cloud code files) cloud function definitions using parse cloud define() triggers such as parse cloud beforesave() , parse cloud aftersave() , etc npm modules you installed (if needed) for example, you might install a package like axios to make http requests you can then require it at the top of your file // main js // 1 import necessary modules and other cloud code files const axios = require('axios'); // 2 define a custom cloud function 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; }); // 3 example of a beforesave trigger parse cloud beforesave('todo', (request) => { const todo = request object; if (!todo get('title')) { throw new error('todo must have a title'); } }); with the ability to install and use npm modules, cloud code becomes incredibly flexible, allowing you to integrate with external apis, perform data transformations, or execute complex server side logic typical use cases business logic for example, you may calculate a user’s score in a game by aggregating multiple object properties, and then store that data automatically data validations ensure certain fields are present or that a user has correct permissions before saving or deleting a record triggers perform actions when data changes (e g , send a notification when a user updates their profile) integrations connect with third party apis or services for example, you could integrate with payment gateways, slack notifications, or email marketing platforms directly from cloud code security enforcement add an extra layer of security by validating and sanitizing input parameters in your cloud code functions deploy your function below is a simple cloud code function that calculates the length of a text string sent from the client main js // 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 the back4app cli 1 install the cli for linux/macos curl https //raw\ githubusercontent com/back4app/parse cli/back4app/installer sh | sudo /bin/bash for windows download the b4a exe file from the releases page https //github com/back4app/parse cli/releases 2 configure your account key b4a configure accountkey 3 deploy your cloud code b4a deploy deploying through the dashboard in your app’s dashboard, go to cloud code > functions copy/paste the function into the main js editor click deploy calling your function from your nodejs code using the parse sdk const parse = require(' /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 via rest 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 or via graphql mutation { calculatetextlength(input { text "hello graphql" }) { result } } this flexibility enables you to integrate your custom logic into any part of your nodejs environment or other clients that support rest or graphql 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 this means you don’t have to set up complex security flows manually setting up user authentication in a nodejs environment, you can create a new user with const parse = require(' /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); } } log in an existing user 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); } } via rest, a login 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 a successful login, parse creates a session token that is stored in the user object in your node code, you can access the currently logged in user if you maintain sessions in your application logic const currentuser = parse user current(); if (currentuser) { console log('currently logged in user ', currentuser getusername()); } else { console log('no user is logged in'); } parse automatically handles token based sessions in the background, but you can also manually manage or revoke them for logging out await parse user logout(); social login integration back4app and parse can integrate with popular oauth providers, such as google or facebook , by installing additional packages or using existing adapters for example, you can set up a facebook login by configuring your facebook app id and using parse facebookutils login() detailed instructions vary, so refer to the social login docs https //www back4app com/docs/platform/sign in with apple 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 to enable email verification and password reset navigate to the email settings in your back4app dashboard enable email verification to ensure new users verify ownership of their email addresses configure the from address , email templates, and your custom domain if desired these features improve account security and user experience by validating user ownership of emails and providing a secure password recovery method step 6 – handling file storage uploading and retrieving files parse includes the parse file class for handling file uploads, which back4app stores securely const parse = require(' /parseconfig'); async function uploadimage(filepath) { // filepath is the path to your file on the server const fs = require('fs'); const filedata = fs readfilesync(filepath); const filename = filepath split('/') pop() || 'upload png'; const parsefile = new parse file(filename, array from(filedata)); try { const savedfile = await parsefile save(); console log('file saved ', savedfile url()); return savedfile url(); } catch (err) { console error('error uploading file ', err); } } to attach the file to an object in the database, you can do async function createphotoobject(filepath) { const photo = parse object extend('photo'); const photo = new photo(); const fs = require('fs'); const filedata = fs readfilesync(filepath); const filename = filepath split('/') pop() || 'upload png'; const parsefile = new parse file(filename, array from(filedata)); photo set('imagefile', parsefile); return await photo save(); } retrieving the file url is straightforward const imagefile = photo get('imagefile'); const imageurl = imagefile url(); file security parse server provides flexible configurations to manage file upload security the following example shows how you can set permissions to control who can upload files to the server enableforpublic when set to true, allows anyone, regardless of authentication status, to upload files enableforanonymoususer controls whether anonymous users (not signed up) can upload files enableforauthenticateduser specifies whether only authenticated users can upload files this is ideal for ensuring that only trusted users have access to this functionality step 7 – scheduling tasks with cloud jobs cloud jobs cloud jobs in back4app let you schedule and run routine tasks on your backend like cleaning up old data or sending a daily summary email a typical cloud job might look like this // main js parse cloud job('cleanupoldtodos', async (request) => { // this runs in the background, not triggered by a direct user request const todo = parse object extend('todo'); const query = new parse query(todo); // for example, remove todos older than 30 days 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); } }); deploy your cloud code with the new job (via cli or the dashboard) go to the back4app dashboard > app settings > server settings > background jobs schedule the job to run daily or at whatever interval suits your needs cloud jobs enable you to automate background maintenance or other periodic processes without requiring manual intervention 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 (e g , stripe), email marketing tools, or analytics platforms navigate to the webhooks configuration in your back4app dashboard > more > webhooks and then 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, if you want 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 ” you can also add custom http headers or payloads if needed you can also define webhooks in cloud code by making custom http requests in triggers like beforesave, aftersave 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 with configurable access controls, you can safely share this interface with team members or clients who need a clear, point and click way to manage data conclusion by following this comprehensive tutorial, you have created a secure backend for a nodejs app on back4app configured a database with class schemas, data types, and relationships integrated real time queries (live queries) for immediate data updates 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 with support for email verification and password resets managed file uploads and retrieval, with optional file security controls scheduled cloud jobs for automated background tasks used webhooks to integrate with external services explored the back4app admin panel for data management with a solid nodejs foundation and a robust back4app backend, you are now well equipped to develop feature rich, scalable, and secure applications continue exploring more advanced functionalities, integrate your business logic, and harness the power of back4app to save you countless hours in server and database administration happy coding! next steps build a production ready nodejs app by extending this backend to handle more complex data models, caching strategies, and performance optimizations integrate advanced features such as specialized authentication flows, role based access control, or external apis (like payment gateways) check out back4app’s official documentation for deeper dives into advanced security, performance tuning, and logs analysis explore other tutorials on real time chat applications, iot dashboards, or location based services you can combine the techniques learned here with third party apis to create complex, real world applications