Welcome to the third installment of our series on building a SaaS application using Next.js, Prisma, and Supabase! In this post, we will focus on implementing server actions in Next.js. Server actions allow you to handle server-side logic within your application efficiently. By the end of this post, you’ll know how to create server actions for common tasks and follow best practices for server-side logic.
What are Server Actions?
Server actions in Next.js are essentially API routes that enable you to handle server-side operations such as data fetching, form handling, and more. These actions are defined within the pages/api directory, and each file in this directory maps to an API endpoint.
Setting Up API Routes
Let s start by setting up a basic API route in our Next.js application.
In this example, we created a simple API route that responds with a "Hello, World!" message. You can access this route by navigating to /api/hello in your browser.
Implementing CRUD Operations with Prisma
Now, let’s implement server actions for CRUD (Create, Read, Update, Delete) operations using Prisma. We'll assume you have a User model defined in your Prisma schema.
Prisma Schema (prisma/schema.prisma)
1// prisma/schema.prisma2model User {3 id Int @id @default(autoincrement())4 email String @unique5 name String?6 createdAt DateTime @default(now())7 updatedAt DateTime @updatedAt8}9
Validation: Always validate the input data to ensure it meets the expected format and constraints before processing it.
Error Handling: Implement robust error handling to manage unexpected errors gracefully and provide informative responses to the client.
Security: Use authentication and authorization mechanisms to protect sensitive routes and data. Sanitize user inputs to prevent SQL injection and other attacks.
Logging: Add logging to track server-side operations and help with debugging and monitoring.
Integrating Server Actions with the Frontend
Let’s integrate these server actions with our frontend to perform CRUD operations from our React components.
We can similarly create forms and functions to update and delete users, following the same principles as above.
Update User Form
Create a form for updating a user in pages/dashboard.tsx or in a dedicated update page. Use a PUT request to the /api/users/[id] endpoint.
Delete User Function
Add a delete button next to each user in pages/dashboard.tsx and send a DELETE request to the /api/users/[id] endpoint when clicked.
1// pages/dashboard.tsx (additional code)2consthandleDelete=async(id:number)=>{3const response =awaitfetch(`/api/users/${id}`,{4 method:'DELETE',5})67if(response.ok){8setUsers(users.filter((user)=> user.id !== id))9console.log('User deleted successfully')10}else{11console.error('Error deleting user')12}13}1415// In the return statement, next to each user:16<button
17 onClick={()=>handleDelete(user.id)}18 className="text-red-600 hover:text-red-800"19>20 Delete
21</button>22
Best Practices for Server Actions
Validation: Always validate the input data to ensure it meets the expected format and constraints before processing it.
Error Handling: Implement robust error handling to manage unexpected errors gracefully and provide informative responses to the client.
Security: Use authentication and authorization mechanisms to protect sensitive routes and data. Sanitize user inputs to prevent SQL injection and other attacks.
Logging: Add logging to track server-side operations and help with debugging and monitoring.
Conclusion
In this post, we have explored how to implement server actions in Next.js using API routes. We created routes for performing CRUD operations with Prisma, integrated them with our frontend, and followed best practices for server-side logic. In the next post, we’ll dive into user authentication and authorization with Supabase. Stay tuned!
By following this series, you'll gain a comprehensive understanding of how to leverage these powerful tools to build a modern, scalable SaaS application. Happy coding!
Let's Build Something Amazing Together
Ready to transform your digital landscape? Contact Codeks today to book a free consultation. Let's embark on a journey to innovation, excellence, and success together.