Quickstarters
Feature Overview
How to Build a Backend for Gatsby?
36 min
introduction in this tutorial, you’ll learn how to build a backend for gatsby using back4app we will show you how to integrate back4app’s features—such as database management, cloud code functions, rest api and graphql query capabilities, user authentication, and real time queries (live queries)—to create a secure, scalable, and robust backend that can be accessed from your gatsby site you’ll also see how back4app’s quick setup and intuitive environment can drastically reduce the time and effort it takes to handle backend tasks by the end, you’ll know exactly how to build a backend for gatsby that stores and retrieves data, handles authentication, integrates cloud functions, and more this sets you up to easily incorporate custom logic, add third party apis, or expand your data model without having to worry about traditional server maintenance what you will build and why it’s valuable complete backend integration you’ll create a scalable backend structure for your gatsby site, incorporating parse sdk, which is perfect for dynamic data needs time savings back4app provides tools like the ai agent, real time queries, and cloud jobs that speed up backend creation extendable skills after finishing, you’ll be able to adapt these concepts for more advanced gatsby features, like create pages at build time or hooking into serverless functions for dynamic operations 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 gatsby development environment you can set this up by installing the gatsby cli https //www gatsbyjs com/docs/tutorial/part 0/#install gatsby cli and running node js (version 14 or above) installed installing node js https //nodejs org/en/download/ familiarity with javascript and gatsby’s concepts gatsby official documentation https //www gatsbyjs com/docs/ read the docs or a beginner’s tutorial if you’re new to gatsby make sure you have these requirements set up this ensures a smooth experience as you create a new file for configuration or run graphql queries in your gatsby environment step 1 – setting up back4app project create a new project the first step in how to build a backend for gatsby on back4app is creating a new project if you have not already log in to your back4app account click the “new app” button on your dashboard give your app a name (e g , “gatsby backend tutorial”) after you create the project, it will appear in your back4app dashboard we’ll use this project as the core of our backend connect the parse sdk back4app uses the parse platform to manage your data, offer real time features, handle user authentication, and more for gatsby, you can still npm install parse and then integrate it into your source files retrieve your parse keys in your back4app dashboard, locate your application id and javascript key , typically under “app settings” or “security & keys ” you’ll also find the parse server url (often something like https //parseapi back4app com ) install the parse sdk in your gatsby site npm install parse create a parseconfig js in your gatsby project’s root directory or within src/ src/parseconfig js // 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 import parse from parseconfig js in your gatsby files (e g , in gatsby node js , gatsby browser js , or pages/components), you’ll have a pre configured instance ready to make queries to your back4app backend step 2 – setting up the database creating a data model in back4app, data is managed as “classes” (similar to tables) with fields for your data let’s create a “todo” class for demonstration we’ll show a few ways you can save and retrieve data in gatsby with parse navigate to the “database” section in your back4app dashboard create a new class (e g , “todo”) and add columns like title (string) and iscompleted (boolean) or you can let parse automatically create columns when objects are first saved from your code creating a data model with the ai agent back4app provides an ai agent to help define your data structure open the ai agent from your app dashboard or menu describe your data model (e g , “please create a new todo app schema with a title and completion status ”) let the ai agent generate the schema for you reading and writing data using sdk a sample snippet in gatsby could look like this (for example, in a react based page or in gatsby browser js ) import parse from ' /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); } } 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); } } reading and writing data using rest api alternatively, you can interact with the database via the rest api 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 reading and writing data using graphql api back4app also supports a graphql api , so you could run queries or mutations like mutation { createtodo(input { fields { title "clean the house" iscompleted false } }) { todo { objectid title iscompleted } } } this is especially convenient if you want your gatsby site to pull data via graphql queries at build time working with live queries gatsby is a static site generator, but you can still set up dynamic real time connections using parse live queries this can be useful in browser run code or in your own serverless hooks enable live queries in your back4app dashboard (under server settings) add the live query server url to parseconfig js parse livequeryserverurl = 'wss\ //your subdomain here b4a io'; subscribe to a class for real time notifications async function subscribetotodos(callback) { const query = new parse query('todo'); const subscription = await query subscribe(); subscription on('create', (newtodo) => { callback('create', newtodo); }); subscription on('update', (updatedtodo) => { callback('update', updatedtodo); }); subscription on('delete', (deletedtodo) => { callback('delete', deletedtodo); }); return subscription; } this will push real time data updates to your gatsby project’s front end step 3 – applying security with acls and clps what are acls and clps? acls (access control lists) let you define permissions on individual objects, while clps (class level permissions) apply to entire classes in your back4app database setting up class level permissions go to database in your back4app dashboard select the class (e g , todo ) click the class level permissions tab configure whether the class is publicly readable, requires authentication, or is restricted to certain roles using acls in code in your gatsby code, you can define acls for each new object async function createprivatetodo(title, owneruser) { const todo = parse object extend('todo'); const todo = new todo(); todo set('title', title); 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); } } step 4 – writing cloud code functions why cloud code? with cloud code, you can add custom server side logic to your back4app backend this is great for business rules, rest api transformations, triggers, or data validations that you may want to keep secure and off the client side example cloud function // 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 cloud code via back4app cli install and configure the cli, then run b4a deploy via dashboard go to cloud code > functions in your dashboard, paste your code into main js , and click deploy calling your function from gatsby/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); } } step 5 – configuring authentication parse user class back4app uses the parse user class for authentication by default, it handles password hashing, sessions, and secure storage sign up and login in gatsby import parse from ' /parseconfig'; // signup 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); } } // login 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); } } after logging in, you can call parse user current() to check if a user is logged in social login you can integrate google , facebook , apple , and other providers with additional setups read more in the social login docs https //www back4app com/docs/platform/sign in with apple step 6 – handling file storage uploading files use parse file to upload images or other files for example, in a gatsby component 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); } } you can then attach this file to a parse object, store it, and later retrieve the file url to display in your gatsby site step 7 – email verification and password reset why it matters email verification confirms the user’s email address, and password reset flows improve user experience both are easily configured in back4app navigate to your app’s email settings in the dashboard enable email verification and set up the password reset email template use the parse sdk methods (e g , parse user requestpasswordreset(email) ) to trigger reset emails step 8 – scheduling tasks with cloud jobs cloud jobs overview use cloud jobs for automating recurring tasks, like removing stale data or sending daily digests for example // 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); } }); then schedule it under app settings > server settings > background jobs step 9 – integrating webhooks webhooks let your back4app app send http requests to external services when specific events happen—like a new record creation go to your back4app dashboard > more > webhooks add a new webhook , specifying the endpoint url for an external service select what triggers the webhook (e g , aftersave on the todo class) you can also integrate with slack or payment gateways by adding the proper endpoint step 10 – exploring the back4app admin panel back4app’s admin app is a model centric interface for data management you can give non technical users secure access to perform crud operations on your classes enabling the admin app go to app dashboard > more > admin app and click “enable admin app ” then create an admin user and choose a subdomain for the admin interface you can now log into your admin app to view and modify data without writing code conclusion in this tutorial, you discovered how to build a backend for gatsby using back4app you’ve learned to configure a secure database with classes, custom fields, and relationships use the parse sdk , along with rest api and graphql query options, for data transactions set up acls and clps for data security write and deploy cloud code to extend business logic and triggers manage user authentication with sign up, login, password reset, and email verification handle file storage for images and documents schedule automated tasks with cloud jobs integrate external services through webhooks leverage the admin app for easy data administration with these skills, your gatsby site can harness powerful dynamic features while still taking advantage of gatsby’s static rendering from here, you can expand your data model and add advanced business logic integrate more external apis for a truly comprehensive platform follow back4app’s official docs for deeper dives into security, performance, and analytics experiment with gatsby’s build time features —for instance, “ create pages ” from dynamic data or set up a “ gatsby source ” plugin for your back4app backend now you have a strong foundation for building future proof, data driven apps with gatsby and back4app