Quickstarters
How to Build a Blitz.js Frontend and Connect It to a Backend?
22 min
in this guide, you will build a to do list application using blitz js and connect it to a managed backend on back4app this step by step tutorial is designed to help you implement essential crud operations and create a dynamic user interface using blitz js building a full stack application can be complex if you must manage both frontend and backend systems by leveraging back4app, you can simplify backend management through a scalable baas , letting you concentrate on building an engaging blitz js interface back4app provides a suite of backend services, including a ready to use nosql database, authentication, cloud functions, and api endpoints these features enable you to rapidly develop and deploy your application without the burden of server maintenance key takeaways by the end of this tutorial, you will be able to set up a modern blitz js project using industry standard tools integrate a back4app backend with your blitz js application using the parse sdk implement crud operations to manage your to do list containerize and deploy your blitz js app using back4app’s web deployment prerequisites before you begin, ensure you have the following node js and npm installed on your machine verify installation with node v and npm v in your terminal basic blitz js knowledge , including routing, queries, and mutations familiarity with react is beneficial since blitz js builds on it a back4app account for configuring and managing your backend services sign up at back4app https //www back4app com/ if you haven't already with these prerequisites met, you’re ready to initialize your blitz js project and integrate it with a robust backend project setup start by setting up your blitz js application blitz js provides a streamlined developer experience by combining the power of next js with a full stack framework run the following command to create a new blitz js project replace todo app with your chosen project name npx blitz new todo app navigate to your project directory cd todo app run your development server to verify that everything is set up correctly npm run dev visit the url displayed in your terminal to confirm that your blitz js app is running setting up the todo backend on back4app back4app offers a managed parse backend that simplifies data management for your application in this section, you will create a data model to store tasks for your to do list creating your backend application log in to your back4app dashboard https //www back4app com/ and click "create a new app " provide a name for your application (e g , todoblitzapp ) and select nodejs/parse as the backend type in the "database" > "browser" section, click "create a class" and select "custom " name the class task and set the class level permissions to allow public read and write (you can adjust these settings later) add the following fields to the task class title (string) – the title of the task description (string) – details about the task completed (boolean) – whether the task is finished duedate (date) – the deadline for the task click "save" to create the schema integrating back4app with blitz js to connect your blitz js app to back4app, install the parse javascript sdk npm install parse next, configure the parse sdk in your blitz js project create a new configuration file (for example, src/parseclient js ) and initialize parse as shown below replace the placeholders with your back4app credentials from app settings > security & keys // src/parseclient js import parse from "parse/dist/parse min js"; const parse app id = "your application id"; const parse js key = "your javascript key"; const parse server url = "https //parseapi back4app com/"; parse initialize(parse app id, parse js key); parse serverurl = parse server url; export default parse; you can now import this configuration in your blitz js queries and mutations to interact with your backend building the frontend with blitz js with the backend set up, it’s time to build the to do list interface in blitz js you will use blitz js’s built in queries and mutations to perform crud operations structuring your pages and api calls in blitz js, pages live under the src/pages directory open src/pages/index tsx and add the following code to set up the page, query tasks from back4app, and define mutations for adding, toggling, and deleting tasks // src/pages/index tsx import layout from "src/core/layouts/layout" import { blitzpage } from "@blitzjs/next" import { usequery } from "@tanstack/react query" import parse from " /parseclient" import { usestate } from "react" const fetchtasks = async () => { const task = parse object extend("task") const query = new parse query(task) const results = await query find() return results map((task) => ({ id task id, task tojson() })) } const addtask = async (title string, description string) => { const task = parse object extend("task") const task = new task() task set("title", title) task set("description", description) task set("completed", false) await task save() } const toggletask = async (id string, currentstatus boolean) => { const task = parse object extend("task") const query = new parse query(task) const task = await query get(id) task set("completed", !currentstatus) await task save() } const deletetask = async (id string) => { const task = parse object extend("task") const query = new parse query(task) const task = await query get(id) await task destroy() } const home blitzpage = () => { const { data tasks, refetch, isloading } = usequery(\["tasks"], fetchtasks) const \[title, settitle] = usestate("") const \[description, setdescription] = usestate("") if (isloading) return \<div>loading \</div> return ( \<layout title="home"> \<div classname="container"> \<h1>to do list\</h1> \<form onsubmit={async (e) => { e preventdefault() await addtask(title, description) settitle("") setdescription("") await refetch() }} classname="form" \> \<input type="text" placeholder="task title" value={title} onchange={(e) => settitle(e target value)} required /> \<input type="text" placeholder="description" value={description} onchange={(e) => setdescription(e target value)} required /> \<button type="submit">add task\</button> \</form> \<div classname="tasks"> {tasks length === 0 ? ( \<p>no tasks available\</p> ) ( tasks map((task) => ( \<div key={task id} classname={`task item ${task completed ? "completed" ""}`}> \<h3>{task title}\</h3> \<p>{task description}\</p> \<button onclick={async () => { await toggletask(task id, task completed) await refetch() }} \> {task completed ? "undo" "complete"} \</button> \<button onclick={async () => { await deletetask(task id) await refetch() }} \> delete \</button> \</div> )) )} \</div> \</div> \</layout> ) } export default home this page leverages tanstack’s query hooks to fetch tasks and handle user actions, ensuring a seamless integration with your back4app backend to ensure the usequery works, you need to wrap your entire application in a queryclientprovider you do this in the src/pages/ app tsx file replace the code in src/pages/ app tsx file with the code block below // src/pages/ app tsx import { errorfallbackprops, errorcomponent, errorboundary, appprops } from "@blitzjs/next" import react from "react" import { withblitz } from "src/blitz client" import { queryclient, queryclientprovider } from "@tanstack/react query" const queryclient = new queryclient() function rooterrorfallback({ error } errorfallbackprops) { return ( \<errorcomponent statuscode={(error as any)? statuscode || 400} title={error message || error name} /> ) } function myapp({ component, pageprops } appprops) { const getlayout = component getlayout || ((page) => page) return ( \<queryclientprovider client={queryclient}> \<errorboundary fallbackcomponent={rooterrorfallback}> {getlayout(\<component { pageprops} />)} \</errorboundary> \</queryclientprovider> ) } export default withblitz(myapp) adding global styles to define your app’s basic styling add the code block to the css file at src/styles/globals css / src/styles/globals css / container { max width 600px; margin 40px auto; padding 0 20px; text align center; font family sans serif; } container h1 { margin bottom 20px; } form { display flex; flex direction column; align items center; gap 10px; margin bottom 20px; } form input\[type="text"] { width 80%; max width 400px; padding 8px; font size 1rem; } form button { padding 8px 16px; cursor pointer; font size 1rem; border none; background color #eaeaea; transition background color 0 2s ease; } form button\ hover { background color #ccc; } tasks p { font size 1rem; } task item { display flex; flex direction column; align items center; gap 12px; border 1px solid #ccc; border radius 6px; padding 15px; margin 10px 0; background color #fafafa; text align center; transition background color 0 2s ease; } task item completed h3, task item completed p { text decoration line through; color #888; } task item h3 { margin 0; font size 1 1rem; } task item p { margin 0; font size 1rem; } task item button { padding 6px 12px; border none; background color #eaeaea; cursor pointer; font size 0 9rem; } task item button\ hover { background color #ccc; } @media (min width 600px) { task item { flex direction row; } } import your global styles by adding the following line in src/pages/ app tsx (or your custom app component file) / src/pages/ app tsx / import " /styles/globals css"; your blitz js app now displays a fully functional to do list interface integrated with back4app containerizing and deploying your blitz js app on back4app back4app web deployment provides a containerized environment that simplifies the deployment process you will package your blitz js app into a docker container and deploy it seamlessly preparing your blitz js app for production first, build your blitz js application for production blitz build creating a dockerfile create a dockerfile in the root directory of your project with the following content from node 18 arg database url arg port=3000 env database url ${database url} workdir /usr/src/app copy package json / run npm install run npm install g blitz copy run blitz build expose 3000 cmd \["blitz", "start", " p", "3000"] this dockerfile builds your blitz js project and prepares a production image using a lightweight node js runtime after creating your dockerfile, create a dockerignore file and copy and paste your gitignore file building and testing your docker container build the docker image locally docker build t todo blitz frontend run the container to test it docker run p 3000 3000 todo blitz frontend visit http //localhost 3000 in your browser to verify that your blitz js app is running correctly deploying your app via back4app web deployment push your project to github git init git add git commit m "initial commit for back4app deployment" git branch m main git remote add origin \<your github repository url> git push u origin main then, log in to back4app web deployment https //www back4app com/containers and follow these steps click "create new app" and enter your project details choose github repository and authorize back4app select your todo blitz repository choose dockerfile deployment and verify the build settings click "deploy" to start the deployment process once deployed, use the back4app dashboard to monitor logs, manage builds, and set up custom domains if needed testing and debugging your application after deployment, ensure your app works as expected by checking api connectivity use your browser’s developer tools to verify that api requests for adding, toggling, and deleting tasks are successful verifying data persistence add tasks through the ui and refresh the page to confirm that they are saved in the back4app database testing crud operations validate that tasks can be toggled and deleted, and inspect console logs for any errors handling edge cases try submitting invalid inputs to test the robustness of your validations best practices and optimization tips consider the following recommendations for a secure and efficient application optimize api requests use batch processing and limit queried fields to reduce network overhead secure environment variables store sensitive credentials (application id and javascript key) in a secure env file implement access control use dynamic acls to ensure only authorized users can modify data leverage cloud code offload complex logic to back4app cloud code to enhance performance and security conclusion you have now built a full stack to do list application using blitz js integrated with a back4app backend this tutorial guided you through project initialization, backend integration, and containerized deployment as you move forward, consider expanding your app with features like advanced user management, real time updates, and third party integrations for additional insights, explore the back4app documentation https //www back4app com/docs and blitz js resources