Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Server Action Database Mutations in Next.js
📖 Scenario: You are building a simple Next.js app to manage a list of books. You want to add new books to a database using server actions. This helps keep your app fast and secure by running database changes on the server.
🎯 Goal: Build a Next.js server action that adds a new book to a database. You will create the initial data structure, configure a helper variable, write the server action to insert the book, and complete the component to use this action.
📋 What You'll Learn
Create a simple in-memory array to act as the database
Add a configuration variable for the default book genre
Write a server action function to add a book to the array
Complete a React component that uses the server action to add a book
💡 Why This Matters
🌍 Real World
Server actions in Next.js let you safely update databases without exposing logic to the browser. This pattern is common in modern web apps for security and performance.
💼 Career
Understanding server actions and database mutations is essential for Next.js developers working on full-stack applications, enabling them to build secure and efficient data-driven features.
Progress0 / 4 steps
1
Create the initial book database array
Create a constant called books that is an empty array to hold book objects.
NextJS
Hint
Use export const books = [] to create an empty array that can hold books.
2
Add a default genre configuration
Create a constant called defaultGenre and set it to the string "Fiction".
NextJS
Hint
Use export const defaultGenre = "Fiction" to set the default genre.
3
Write the server action to add a book
Create an async function called addBook that takes a parameter title. Inside, push an object with title and genre set to defaultGenre into the books array.
NextJS
Hint
Define addBook as an async function that pushes a new book object to books.
4
Complete the React component to use the server action
Create a default exported React functional component called AddBookForm. Inside, create a form with an input named title and a submit button. Use the addBook server action as the form's action handler.
NextJS
Hint
Use a form with action={addBook} and an input named title. Add a submit button.
Practice
(1/5)
1. What is the main purpose of using server actions for database mutations in Next.js?
easy
A. To run client-side animations after data changes
B. To securely update data on the server without exposing logic to the client
C. To fetch data from an external API on the client
D. To style components dynamically based on user input
Solution
Step 1: Understand server actions role
Server actions run on the server and handle data changes securely.
Step 2: Identify the security benefit
They keep mutation logic hidden from the client, preventing misuse.
Final Answer:
To securely update data on the server without exposing logic to the client -> Option B
Quick Check:
Server actions = secure server-side mutations [OK]
Hint: Server actions run on server to keep data safe [OK]
Common Mistakes:
Thinking server actions run on the client
Confusing server actions with client-side fetching
Believing server actions handle UI styling
2. Which of the following is the correct way to declare a server action function in Next.js?
easy
A. export async function addUser() { 'use server'; /* mutation code */ }
B. export async function addUser() { useServer(); /* mutation code */ }
C. export async function addUser() { /* mutation code */ } 'use server';
D. 'use server'; export async function addUser() { /* mutation code */ }
Solution
Step 1: Identify correct 'use server' placement
The 'use server' directive must be the first statement inside the function file or function scope.
Step 2: Check syntax correctness
'use server'; export async function addUser() { /* mutation code */ } places 'use server' at the top before the function, which is correct syntax.
Final Answer:
'use server'; export async function addUser() { /* mutation code */ } -> Option D
Quick Check:
'use server' directive must be at top [OK]
Hint: Put 'use server' at the top before function export [OK]
Common Mistakes:
Placing 'use server' inside function body after code
Using a function call like useServer() instead of directive
Putting 'use server' after function declaration
3. Given this server action code, what will be the result after calling await addUser({ name: 'Alice' }) if the database is empty?
'use server';
async function addUser(user) {
await db.users.create({ data: user });
return await db.users.count();
}
medium
A. Returns 1 because one user is added
B. Returns undefined because no return statement
C. Throws an error because 'use server' is misplaced
D. Returns 0 because count is called before creation
Solution
Step 1: Analyze database mutation
The function creates a user in the database with given data.
Step 2: Check return value
After creation, it returns the count of users, which should be 1.
Final Answer:
Returns 1 because one user is added -> Option A
Quick Check:
Created one user, count = 1 [OK]
Hint: Create then count means count reflects new data [OK]
Common Mistakes:
Assuming count runs before creation completes
Confusing 'use server' placement causing error
Missing return statement in function
4. Identify the error in this server action code snippet:
'use server';
export async function updateUser(id, data) {
await db.users.update({ where: { id }, data });
}
medium
A. Missing semicolon after 'use server' directive
B. Missing export keyword
C. Incorrect object structure in update call
D. No error, code is correct
Solution
Step 1: Check 'use server' directive syntax
The 'use server'; directive is correctly placed at the top of the module.
Step 2: Analyze update method parameters
The update method expects an object with 'where' and 'data' keys, but here 'data' is outside the object, causing syntax error.
Final Answer:
Incorrect object structure in update call -> Option C
Hint: Check object keys carefully in db update calls [OK]
Common Mistakes:
Assuming missing semicolon causes error
Forgetting to wrap data inside update object
Missing export keyword (actually present)
5. You want to create a server action that deletes a user only if they have no active orders. Which approach correctly combines server action and database mutation logic?