Server actions run code on the server to keep data safe and private. Understanding security helps protect your app from bad users.
Server action security considerations in NextJS
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
NextJS
"use server" export async function myServerAction(data) { // server-side logic here return result; }
Server actions run only on the server, never in the browser.
Use async functions to handle asynchronous tasks like database calls.
Examples
NextJS
"use server" export async function addUser(name) { // Validate input if (!name) throw new Error('Name is required'); // Save user to database return await db.users.create({ name }); }
NextJS
"use server" export async function deleteUser(id) { // Check user permissions if (!userIsAdmin()) throw new Error('Not authorized'); // Delete user from database return await db.users.delete({ where: { id } }); }
Sample Program
This server action checks if the user is logged in by looking for an auth token cookie. It also validates the message length before saving. This keeps the app safe from unauthorized or bad data.
NextJS
import { cookies } from 'next/headers'; "use server" export async function secureServerAction(data) { // Check if user is authenticated via cookie const cookieStore = cookies(); const token = cookieStore.get('authToken'); if (!token) { throw new Error('User not authenticated'); } // Validate input if (!data.message || data.message.length > 100) { throw new Error('Invalid message'); } // Simulate saving message securely return `Message saved: ${data.message}`; }
Important Notes
Always validate and sanitize inputs on the server to avoid bad data or attacks.
Never trust data coming from the client; always check permissions and authentication.
Keep secret keys and tokens only on the server, never send them to the browser.
Summary
Server actions run only on the server to protect sensitive logic.
Always check user authentication and permissions inside server actions.
Validate all inputs to keep your app safe from bad data or attacks.
Practice
1. Why should server actions in Next.js always check user authentication before proceeding?
easy
Solution
Step 1: Understand server action purpose
Server actions run on the server to handle sensitive logic securely.Step 2: Importance of authentication check
Checking user authentication ensures only authorized users can access or modify protected data.Final Answer:
To ensure only authorized users can perform sensitive operations -> Option CQuick Check:
Authentication check = To ensure only authorized users can perform sensitive operations [OK]
Hint: Server actions protect sensitive logic by verifying users [OK]
Common Mistakes:
- Thinking authentication speeds up server response
- Confusing client-side speed with server security
- Believing authentication reduces bundle size
2. Which of the following is the correct way to define a server action in Next.js 14+?
easy
Solution
Step 1: Recognize server action syntax
Server actions are async functions exported to run on the server.Step 2: Identify correct export and async usage
export async function actionName() { /* server code */ } correctly exports an async function for server action.Final Answer:
export async function actionName() { /* server code */ } -> Option AQuick Check:
Async export function = export async function actionName() { /* server code */ } [OK]
Hint: Server actions are async exported functions [OK]
Common Mistakes:
- Using client component syntax for server actions
- Missing async keyword in server action
- Not exporting the function
3. Given this server action code snippet, what will happen if the input is not validated?
export async function updateUser(data) {
// No input validation
await db.user.update({ where: { id: data.id }, data });
return { success: true };
}medium
Solution
Step 1: Understand missing input validation
Without validation, any data sent by client is accepted as-is.Step 2: Consequences of no validation
Invalid or malicious data can corrupt database or cause security vulnerabilities.Final Answer:
The database may receive invalid or malicious data causing errors or security issues -> Option AQuick Check:
Missing validation = risk of bad data [OK]
Hint: No validation risks bad data in database [OK]
Common Mistakes:
- Assuming server rejects invalid data automatically
- Believing client validation is enough
- Expecting syntax errors from bad input
4. Identify the security issue in this server action code and how to fix it:
export async function deletePost(postId) {
await db.post.delete({ where: { id: postId } });
return { deleted: true };
}medium
Solution
Step 1: Check for authentication or permission validation
The code deletes a post without verifying if the user is allowed to do so.Step 2: Fix by adding user identity check
Before deleting, confirm the user is authenticated and authorized to delete the post.Final Answer:
Missing user authentication check; fix by verifying user identity before deleting -> Option DQuick Check:
Authentication missing = Missing user authentication check; fix by verifying user identity before deleting [OK]
Hint: Always check user permissions before data deletion [OK]
Common Mistakes:
- Ignoring authentication importance
- Confusing async keyword necessity
- Misunderstanding database method usage
5. You want to create a server action that updates user profile data only if the user is authenticated and the input is valid. Which approach best secures this action?
export async function updateProfile(user, data) {
// What should you do here?
}hard
Solution
Step 1: Verify user authentication inside server action
Ensure the user object is valid and authenticated before proceeding.Step 2: Validate all input data carefully
Check each data field to prevent invalid or malicious input before updating the database.Step 3: Update database only after passing checks
Perform the update securely after authentication and validation.Final Answer:
Check if user is authenticated, validate data fields, then update database -> Option BQuick Check:
Authentication + validation = secure update [OK]
Hint: Authenticate user and validate input before DB update [OK]
Common Mistakes:
- Skipping server-side validation
- Relying only on client validation
- Updating DB without authentication
