0
0
NextJSframework~30 mins

Error handling in server actions in NextJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Error handling in server actions
📖 Scenario: You are building a Next.js app that lets users submit feedback through a form. The form sends data to a server action that saves the feedback. You want to handle errors gracefully if saving fails.
🎯 Goal: Create a server action that saves feedback data and handles errors by returning a clear message. Then connect it to a simple form component that calls this action.
📋 What You'll Learn
Create a server action function called saveFeedback that accepts a FormData object
Add a configuration variable simulateError to control if the save should fail
Use try...catch inside saveFeedback to handle errors and return an error message
Create a React functional component FeedbackForm that uses the saveFeedback server action on form submission
💡 Why This Matters
🌍 Real World
Handling errors in server actions is important for building reliable web apps that communicate with servers safely and inform users about issues.
💼 Career
Understanding server actions and error handling is essential for Next.js developers working on full-stack React applications.
Progress0 / 4 steps
1
Create the server action function
Create an async server action function called saveFeedback that accepts a parameter formData. Inside, extract the feedback text from formData using formData.get('feedback') and store it in a variable called feedbackText.
NextJS
Need a hint?

Use export async function saveFeedback(formData) to define the server action. Use formData.get('feedback') to get the feedback text.

2
Add error simulation configuration
Inside the saveFeedback function, create a constant called simulateError and set it to false. This will control if the save operation should simulate an error.
NextJS
Need a hint?

Declare const simulateError = false; inside the function to control error simulation.

3
Add error handling logic
Wrap the save logic inside a try...catch block. Inside try, if simulateError is true, throw a new Error with message 'Simulated save error'. Otherwise, simulate saving by returning { success: true, message: 'Feedback saved' }. In catch, return { success: false, message: error.message }.
NextJS
Need a hint?

Use try...catch to handle errors. Throw an error if simulateError is true. Return success or error objects accordingly.

4
Create the feedback form component
Create a React functional component called FeedbackForm. Inside, create a form with a textarea named feedback and a submit button. Use the saveFeedback server action as the form's action. Add an aria-label to the textarea with value 'Feedback input' for accessibility.
NextJS
Need a hint?

Create a form with action={saveFeedback}. Add a textarea with name="feedback" and aria-label="Feedback input". Add a submit button.