Quickstarters
CRUD Samples
How to Build a Basic CRUD App with Next.js?
49 min
introduction in this guide, we’ll walk through building a complete crud (create, read, update, delete) application using next js for your frontend, paired with back4app as your backend solution you'll set up a project named basic crud app nextjs , design a dynamic database schema, and integrate robust crud functionality into your next js app we will cover everything from configuring your back4app project and designing collections to connecting your next js interface using the parse sdk or rest/graphql methods by the end, you’ll have a production ready web application with secure user authentication and efficient data management key takeaways build a full crud application with next js and back4app learn to design a flexible backend schema tailored to your data needs utilize an intuitive, drag and drop admin interface for data management discover best practices for deployment, including docker containerization and github integration prerequisites before you begin, ensure you have a back4app account with a new project set up for guidance, refer to getting started with back4app https //www back4app com/docs/get started/new parse app a next js development environment use create next app https //nextjs org/docs/api reference/create next app or a similar tool make sure node js (version 14 or later) is installed a basic understanding of javascript, next js, and api integrations visit the next js documentation https //nextjs org/docs for an overview if needed step 1 – setting up your project initiate a new back4app project log in to your back4app account click the “new app” button on your dashboard enter the project name basic crud app nextjs and follow the prompts create new project your new project appears in the dashboard, serving as the core for your backend create your next js application open your terminal and run npx create next app\@latest basic crud app nextjs change to your project directory cd basic crud app nextjs this command sets up a next js project framework ready for customization step 2 – crafting your database schema structuring your data model for this crud app, you will create essential collections below are two primary collections with field details that enable the core functionalities 1\ items collection this collection stores details about each item field data type description id objectid auto generated unique identifier title string the item’s name or title description string a brief summary of the item created at date timestamp when the item is created updated at date timestamp for the latest update 2\ users collection this collection handles user profiles and authentication data field data type description id objectid auto generated unique identifier username string unique username for the user email string unique email address password hash string securely hashed password for user authentication created at date timestamp when the account was created updated at date timestamp for the last account update you can manually define these collections in the back4app dashboard by creating a new class for each collection and adding the relevant columns create new class create fields by choosing the appropriate data type, naming the column, and setting defaults or requirements create column using the back4app ai assistant for schema setup the back4app ai assistant streamlines database schema generation describe your desired collections and fields, and let the assistant auto generate the structure steps to use the ai assistant open the ai assistant find it in your back4app dashboard menu describe your data model paste a detailed prompt outlining your collections and field requirements review and apply check the generated schema and implement it in your project sample prompt create the following collections in my back4app project 1\) collection items \ fields \ id objectid (auto generated primary key) \ title string \ description string \ created at date (auto generated) \ updated at date (auto updated) 2\) collection users \ fields \ id objectid (auto generated primary key) \ username string (unique) \ email string (unique) \ password hash string \ created at date (auto generated) \ updated at date (auto updated) this method not only saves time but also ensures your schema is consistent and optimized step 3 – activating the admin interface & crud features exploring the admin interface the back4app admin interface offers a no code solution to manage your backend data with its intuitive drag and drop system, you can easily perform crud operations enabling the admin interface navigate to the “more” section in your back4app dashboard click on “admin app” then select “enable admin app ” configure your admin credentials by setting up your first admin user this also establishes roles like b4aadminuser and necessary system collections enable admin app after activation, log in to the admin interface to begin managing your data admin app dashboard executing crud operations via the admin interface within the admin interface you can create records use the “add record” button in a collection (e g , items) to insert new data view or update records click on a record to inspect or modify its fields delete records use the delete option to remove obsolete entries this streamlined interface makes data management straightforward and efficient step 4 – connecting next js to back4app with your backend set up, the next step is to connect your next js application option a using the parse sdk install the parse sdk npm install parse initialize parse in your next js app create a file (e g , lib/parseconfig js ) // lib/parseconfig js import parse from 'parse'; // replace with your back4app credentials parse initialize('your application id', 'your javascript key'); parse serverurl = 'https //parseapi back4app com'; export default parse; integrate parse in a next js page for example, create a page to fetch and display items // pages/index js import { useeffect, usestate } from 'react'; import parse from ' /lib/parseconfig'; export default function home() { const \[items, setitems] = usestate(\[]); useeffect(() => { const loaditems = async () => { const items = parse object extend('items'); const query = new parse query(items); try { const results = await query find(); setitems(results); } catch (error) { console error('error retrieving items ', error); } }; loaditems(); }, \[]); return ( \<div style={{ padding '2rem' }}> \<h1>item list\</h1> \<ul> {items map((item) => ( \<li key={item id}> \<strong>{item get('title')}\</strong> {item get('description')} \</li> ))} \</ul> \</div> ); } option b using rest or graphql if you prefer not to use the parse sdk, you can manage crud operations with rest or graphql for example, to fetch items via rest 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(); console log('items fetched ', data results); } catch (error) { console error('error fetching items ', error); } }; fetchitems(); integrate these api calls into your next js components as needed step 5 – securing your backend implementing access control lists (acls) secure your data by assigning acls to objects for instance, to create an item that only its owner can access async function addprivateitem(itemdetails, owner) { const items = parse object extend('items'); const newitem = new items(); newitem set('title', itemdetails title); newitem set('description', itemdetails description); // configure acl owner only read and write const acl = new parse acl(owner); acl setpublicreadaccess(false); acl setpublicwriteaccess(false); newitem setacl(acl); try { const saveditem = await newitem save(); console log('private item added ', saveditem); } catch (error) { console error('error adding item ', error); } } configuring class level permissions (clps) within the back4app dashboard, adjust the clps for each collection to restrict data access to authorized users only step 6 – implementing user authentication setting up user accounts back4app leverages parse’s built in user class for authentication in your next js app, manage registration and login as shown below // pages/signup js import { usestate } from 'react'; import parse from ' /lib/parseconfig'; export default function signup() { const \[username, setusername] = usestate(''); const \[password, setpassword] = usestate(''); const \[email, setemail] = usestate(''); const registeruser = async (e) => { e preventdefault(); const user = new parse user(); user set('username', username); user set('password', password); user set('email', email); try { await user signup(); alert('registration successful!'); } catch (error) { alert('registration failed ' + error message); } }; return ( \<form onsubmit={registeruser}> \<input type="text" placeholder="username" value={username} onchange={(e) => setusername(e target value)} /> \<input type="password" placeholder="password" value={password} onchange={(e) => setpassword(e target value)} /> \<input type="email" placeholder="email" value={email} onchange={(e) => setemail(e target value)} /> \<button type="submit">register\</button> \</form> ); } a similar approach can be used for login and session management you can also enable additional features such as social logins, email verification, and password recovery via the back4app dashboard step 7 – deploying your next js frontend back4app’s deployment options allow you to host your next js application effortlessly, whether through github integration or docker containerization 7 1 building your production version open your project directory in the terminal run the build command npm run build this generates a next folder containing optimized static and server rendered files 7 2 organizing and uploading your code your repository should contain all source files for your next js app a typical structure might be basic crud app nextjs/ ├── node modules/ ├── pages/ │ ├── index js │ └── signup js ├── lib/ │ └── parseconfig js ├── public/ │ └── favicon ico ├── package json └── readme md example lib/parseconfig js // lib/parseconfig js import parse from 'parse'; // insert your back4app credentials here parse initialize('your application id', 'your javascript key'); parse serverurl = 'https //parseapi back4app com'; export default parse; example pages/index js (refer to the code snippet provided in step 4) committing your code to github initialize a git repository git init add all files git add commit your changes git commit m "initial commit of next js crud application" create a github repository for example, name it basic crud app nextjs push your code git remote add origin https //github com/your username/basic crud app nextjs git git push u origin main 7 3 integrating with back4app web deployment access web deployment log in to your back4app dashboard, navigate to your project, and select the web deployment feature connect your github account follow the prompts to link your repository select your repository and branch choose the repository (e g , basic crud app nextjs ) and the branch (e g , main ) containing your code 7 4 configuring deployment settings build command if your repository does not include a pre built next folder, specify the command (e g , npm run build ) output directory set the output directory to next so that back4app knows where your compiled files reside environment variables add any necessary environment variables, such as api keys 7 5 containerizing your next js application with docker if you prefer docker for deployment, include a dockerfile in your repository \# use an official node runtime as the base image from node 16 alpine as build \# set the working directory workdir /app \# copy package files and install dependencies copy package json / run npm install \# copy the source code copy \# build the next js application run npm run build \# use nginx to serve the built app from nginx\ stable alpine copy from=build /app/ next /usr/share/nginx/html expose 80 cmd \["nginx", " g", "daemon off;"] select the docker deployment option in back4app to containerize and deploy your application 7 6 launching your application deploy your app click the deploy button in back4app monitor the build process back4app will fetch your code, execute the build command, and deploy your application access your live app once deployment completes, a url will be provided where your next js application is hosted 7 7 verifying your deployment visit the provided url open the url in your browser test functionality ensure that your pages load correctly and that all crud operations are working troubleshoot if necessary use browser developer tools and back4app logs to diagnose any issues step 8 – conclusion and next steps congratulations! you have successfully built a robust crud application with next js and back4app you configured your project, designed tailored collections, and connected your next js frontend with a secure backend next steps enhance your frontend expand your next js app with advanced features like detailed views, search functionality, or real time updates augment your backend explore cloud functions, third party integrations, or additional access controls keep learning visit the back4app documentation https //www back4app com/docs and next js resources for further optimization and customization by following this tutorial, you now possess the skills to create a scalable and secure crud application using next js and back4app happy coding!