0
0
NextJSframework~5 mins

Server action security considerations in NextJS

Choose your learning style9 modes available
Introduction

Server actions run code on the server to keep data safe and private. Understanding security helps protect your app from bad users.

When you want to keep user data safe and not expose it to the browser.
When handling sensitive operations like payments or user authentication.
When you want to prevent users from changing data they shouldn't.
When you need to validate inputs before saving to a database.
When you want to avoid exposing secret keys or tokens in client code.
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
This server action checks the input and saves a new user safely on the server.
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 });
}
This server action ensures only admins can delete users, protecting data.
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}`;
}
OutputSuccess
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.