Quickstarters
CRUD Samples
How to Build a CRUD App with Astro?
38 min
overview in this guide, you'll learn how to create a crud (create, read, update, and delete) web application using astro this tutorial walks you through setting up a back4app project—our robust backend—and designing a data structure that supports fundamental operations we will then build an astro frontend that communicates with back4app via rest/graphql apis, ensuring secure and efficient data management by the end of this guide, you’ll have a production ready web application complete with user authentication and secure data handling what you'll learn how to structure a crud application with astro and back4app designing a scalable backend with custom collections using a drag and drop admin interface for effortless data management integrating your astro frontend with back4app using rest or graphql deploying your astro project and containerizing it with docker if needed prerequisites before you get started, please confirm you have a back4app account with a new project ready check out getting started with back4app https //www back4app com/docs/get started/new parse app for guidance an astro development environment set up use the official astro documentation https //docs astro build to get started ensure node js (version 14+) is installed basic familiarity with javascript, astro, and rest apis visit the astro docs https //docs astro build if you need a refresher step 1 – initializing your project starting a new back4app project sign in to your back4app account click “new app” from your dashboard name your project basic crud app astro and follow the instructions to complete the setup create new project after creation, your project will appear on your back4app dashboard—your foundation for backend configuration step 2 – crafting your database schema structuring your data model for our crud application, you'll define several collections below are sample collections with fields and types to help you configure your database schema effectively this structure supports efficient crud operations 1\ items collection field type purpose id objectid auto generated primary key title string name or title of the item description string a brief overview of the item created at date timestamp of creation updated at date timestamp for last modification 2\ users collection field type purpose id objectid auto generated primary key username string unique identifier for the user email string user's email address password hash string encrypted password for authentication created at date when the account was created updated at date last update time for the account you can manually configure these collections in your back4app dashboard by creating new classes and adding appropriate columns create new class to add a field, select a data type, provide a field name, define a default if needed, and mark whether the field is required create column leveraging the back4app ai agent for schema setup the integrated ai agent in back4app can auto generate your schema describe your desired collections and fields in the ai agent interface, review its recommendations, and apply them to your project sample prompt create these collections in my back4app project 1\) collection items \ fields \ id objectid (auto generated) \ title string \ description string \ created at date (auto created) \ updated at date (auto updated) 2\) collection users \ fields \ id objectid (auto generated) \ username string (unique) \ email string (unique) \ password hash string \ created at date (auto generated) \ updated at date (auto updated) this tool expedites setup while ensuring your schema meets application requirements step 3 – activating the admin interface & crud actions exploring the admin interface the back4app admin app is a no code tool that provides a visual interface to manage your backend data its drag and drop design lets you easily perform crud operations activating the admin interface open the “more” menu in your back4app dashboard select “admin app” and click “enable admin app ” set up your admin credentials by creating the initial admin user this will also configure default roles (e g , b4aadminuser ) and system collections enable admin app after activation, log in to the admin app to manage your collections admin app dashboard managing data with the admin interface inside the admin app you can add records click “add record” in a collection (like items) to create new entries view/edit records click on a record to inspect or modify its fields remove records delete obsolete entries effortlessly this tool simplifies crud operations with an intuitive interface step 4 – connecting astro with back4app with your backend configured, it’s time to integrate your astro frontend utilizing rest/graphql apis since astro is a static site generator optimized for performance, we’ll interact with back4app using rest or graphql apis this approach avoids the need for the parse sdk example fetching items via rest below is an example of a rest api call within an astro component // src/components/itemslist astro \ import { usestate, useeffect } from 'react'; const \[items, setitems] = usestate(\[]); useeffect(() => { const fetchitems = async () => { try { const response = await fetch('https //parseapi back4app com/classes/items', { headers { 'x parse application id' 'your application id', 'x parse rest api key' 'your rest api key' } }); const data = await response json(); setitems(data results); } catch (error) { console error('failed to fetch items ', error); } }; fetchitems(); }, \[]); \ \<div> \<h2>items\</h2> \<ul> {items map(item => ( \<li key={item objectid}> {item title} – {item description} \</li> ))} \</ul> \</div> integrate similar api calls for creating, updating, and deleting records within your astro components step 5 – safeguarding your backend implementing access control lists (acls) protect your data by setting acls on objects for example, to create an item that only the owner can modify async function createprivateitem(data, owner) { const response = await fetch('https //parseapi back4app com/classes/items', { method 'post', headers { 'content type' 'application/json', 'x parse application id' 'your application id', 'x parse rest api key' 'your rest api key' }, body json stringify({ title data title, description data description, acl { \[owner id] { read true, write true }, ' ' { read false, write false } } }) }); const result = await response json(); console log('created private item ', result); } configuring class level permissions (clps) within the back4app dashboard, adjust the clps for each collection to define who can access and modify your data step 6 – adding user authentication setting up user registration and login back4app uses parse’s user class for authentication in your astro project, create components for user sign up and login by leveraging rest api calls example user sign up // src/components/signup astro \ import { usestate } from 'react'; const \[username, setusername] = usestate(''); const \[password, setpassword] = usestate(''); const \[email, setemail] = usestate(''); const handlesignup = async (event) => { event preventdefault(); try { const response = await fetch('https //parseapi back4app com/users', { method 'post', headers { 'content type' 'application/json', 'x parse application id' 'your application id', 'x parse rest api key' 'your rest api key' }, body json stringify({ username, password, email }) }); const result = await response json(); alert('sign up successful!'); } catch (error) { alert('error during sign up ' + error message); } }; \ \<form on\ submit={handlesignup}> \<input type="text" placeholder="username" value={username} oninput={(e) => setusername(e target value)} /> \<input type="password" placeholder="password" value={password} oninput={(e) => setpassword(e target value)} /> \<input type="email" placeholder="email" value={email} oninput={(e) => setemail(e target value)} /> \<button type="submit">register\</button> \</form> you can build similar components for user login and session management step 7 – deploying your astro frontend back4app's web deployment feature allows you to host your astro project seamlessly by connecting your github repository 7 1 building your production version open a terminal in your project directory run the build command npm run build this generates an optimized dist folder with your static assets check the build ensure that the dist folder contains an index html along with other asset directories 7 2 organizing your project repository your repository should include the complete astro source code an example structure might be basic crud app astro/ ├── node modules/ ├── public/ │ └── favicon ico ├── src/ │ ├── components/ │ │ ├── itemslist astro │ │ └── signup astro │ └── pages/ │ └── index astro ├── package json └── readme md example file src/components/itemslist astro // src/components/itemslist astro \ import { usestate, useeffect } from 'react'; const \[items, setitems] = usestate(\[]); useeffect(() => { const getitems = async () => { try { const res = await fetch('https //parseapi back4app com/classes/items', { headers { 'x parse application id' 'your application id', 'x parse rest api key' 'your rest api key' } }); const json = await res json(); setitems(json results); } catch (err) { console error('error retrieving items ', err); } }; getitems(); }, \[]); \ \<div> \<h2>item list\</h2> \<ul> {items map(item => ( \<li key={item objectid}> {item title} — {item description} \</li> ))} \</ul> \</div> 7 3 committing and pushing your code to github initialize a git repository (if not done) git init add all files git add commit your changes git commit m "initial commit for astro frontend" create a repository on github (e g , basic crud app astro ) and push git remote add origin https //github com/your username/basic crud app astro git git push u origin main 7 4 linking github with back4app web deployment access web deployment log in to your back4app dashboard, navigate to your project ( basic crud app astro ), and select the web deployment option connect your github account follow the prompts to authorize back4app to access your repository choose your repository and branch select the repository (e g , basic crud app astro ) and the branch (typically main ) 7 5 configuring deployment settings build command specify the build command (e g , npm run build ) if your repository lacks a pre built output output directory set it to dist so back4app knows where to locate your static files environment variables add any required variables, such as api keys 7 6 dockerizing your astro application (optional) if you prefer containerized deployments, include a dockerfile like \# use an official node image for building from node 16 alpine as builder \# set the working directory workdir /app \# copy package files and install dependencies copy package json / run npm install \# copy source files and build the project copy run npm run build \# use nginx to serve the static files from nginx\ stable alpine copy from=builder /app/dist /usr/share/nginx/html expose 80 cmd \["nginx", " g", "daemon off;"] integrate docker settings in your web deployment configuration if desired 7 7 launching your application hit the deploy button in the web deployment section monitor the build process back4app will retrieve your code, build it, and deploy your application receive your url once deployed, back4app will supply a url where your site is live step 8 – wrapping up and future enhancements great job! you’ve now created a complete crud application with astro and back4app your project includes a backend with detailed collections for items and users, and a frontend that performs all crud operations through rest/graphql apis next steps enhance the frontend add features such as detailed views, search capabilities, and real time notifications expand backend functionality consider integrating cloud functions or additional api endpoints for more complex logic dive deeper explore further resources in the back4app documentation https //www back4app com/docs and the astro docs https //docs astro build for advanced topics by following this tutorial, you now possess the knowledge to build a robust and scalable crud application using astro and back4app enjoy coding and exploring new possibilities!