Skip to content

What are Server Actions

Key idea:

Server Actions — a Next.js App Router feature (stable since Next 14, 2023): async functions on the server callable directly from React components (form or button). No need to write API routes. Marked with a "use server" directive. Progressive enhancement: work without JS via native form submission. Replaces the API-route + client-side fetch pattern for mutations.

Below: details, example, related terms, FAQ.

Check your site's speed →

Details

  • Directive: "use server" at the top of an async function
  • Form: <form action={submitAction}> — works without JS
  • Optimistic UI: useOptimistic hook for instant feedback
  • Revalidation: revalidatePath() / revalidateTag() — invalidates cache
  • Security: always re-validate session + authorization inside the action (don't rely on page guard)

Example

"use server";
export async function createPost(formData) {
  const session = await auth();
  if (!session) throw new Error('Unauthorized');
  await db.post.create({ data: { title: formData.get('title') } });
  revalidatePath('/posts');
}

Related Terms

Understanding Server Actions in Next.js

Server Actions are a powerful feature introduced in Next.js 14, allowing developers to create asynchronous functions on the server that can be invoked directly from React components. This eliminates the need to create separate API routes for handling data mutations, streamlining the development process.

To define a Server Action, you simply create an asynchronous function in a component file and annotate it with the "use server" directive. This directive indicates that the function should run on the server rather than the client. For example:

async function handleSubmit(data) { /* processing logic */ }

By using Server Actions, developers can leverage progressive enhancement techniques, as these actions will function even if JavaScript is disabled in the user's browser, thanks to native form submissions.

Server Actions also enhance performance by reducing the amount of client-side code, leading to faster load times and improved user experiences. Since the server handles the logic, it can be optimized for speed and efficiency.

Practical Examples of Implementing Server Actions

Implementing Server Actions in Next.js involves a few straightforward steps. Below are practical examples that demonstrate how to set up and utilize Server Actions in your application.

1. **Define a Server Action:** Create a new file, for example, app/actions.js, and define your Server Action:

export async function saveData(formData) { const response = await fetch('/api/save', { method: 'POST', body: formData }); return response.json(); }

2. **Use the Action in a Component:** In your component, you can call this action directly:

import { saveData } from './actions';

3. **Form Implementation:** Create a form that utilizes the Server Action:

<form action={saveData} method="POST"> <input type="text" name="data" /> <button type="submit">Submit</button> </form>

This setup allows you to submit the form directly to the Server Action, providing a seamless experience. The action can handle data processing and responding without needing to manage API routes.

Benefits of Using Server Actions Over API Routes

Server Actions present several advantages over traditional API routes in Next.js applications. Understanding these benefits can help developers make informed decisions regarding architecture and performance optimizations.

  • Simplicity: Server Actions simplify the codebase by removing the need for separate API routes. Instead of routing requests through a RESTful API, functions can be directly invoked from the component.
  • Improved Performance: By reducing the overhead associated with API calls and client-side fetching, Server Actions can lead to faster response times and a more responsive user experience.
  • Progressive Enhancement: Since Server Actions can work without JavaScript, they enhance accessibility and usability for users with JavaScript disabled or on slower connections.
  • Less Boilerplate: Developers can avoid writing repetitive code associated with defining and managing API routes, allowing them to focus on business logic and functionality.
  • Better Error Handling: Server Actions can handle errors more gracefully by providing server-side validation and feedback before reaching the client.

In summary, Server Actions offer a modern approach to handling server-side logic in Next.js applications, making them a preferred choice for many developers looking to enhance their workflow and application performance.

PerformanceOverall speed score 0-100
Core Web VitalsLCP, FID, CLS — Google metrics
Page SizeSize of HTML, CSS, JS, images
RecommendationsSpecific tips for improvement

Why teams trust us

Lighthouse
analysis engine
CWV
Core Web Vitals
4
Lighthouse categories
Precise
recommendations

How it works

1

Enter page URL

2

Lighthouse analyzes

3

Get CWV scores & tips

Why Does Site Speed Matter?

Page load speed directly impacts conversion, SEO rankings, and user satisfaction. Google uses Core Web Vitals as a ranking factor. Every extra second of load time cancost up to 7% in conversions.

Lighthouse Analysis

Google Lighthouse-based analysis: Performance, Accessibility, Best Practices, SEO.

Core Web Vitals

LCP (rendering), FID (interactivity), CLS (visual stability) — key Google metrics.

Resource Analysis

Breakdown by type: HTML, CSS, JavaScript, images, fonts. Size, request count, blocking resources.

Actionable Advice

Specific recommendations with savings estimates: image compression, caching, minification, etc.

Mobile vs Desktop

Mobile
  • Tested on Moto G Power emulation (slow CPU)
  • Network: 4G (1.6 Mbps, 150ms RTT)
  • Stricter speed scoring
  • Google indexes mobile-first
  • Priority for SEO optimization
Desktop
  • High CPU performance
  • Fast connection without throttling
  • Scores typically 20-40 points higher
  • Important for B2B and corporate sites
  • Use for baseline comparisons

Who uses this

SEO

Core Web Vitals for rankings

Developers

performance optimization

Marketers

speed = conversions

DevOps

performance regression

Common Mistakes

Unoptimized imagesImages can be up to 70% of page weight. Use WebP/AVIF and lazy loading.
Render-blocking JS in &lt;head&gt;Scripts without async/defer block rendering. Move to end or add attribute.
No static asset cachingWithout Cache-Control, the browser reloads CSS/JS on every visit.
Too many HTTP requestsEach request adds latency. Bundle files, use sprites, or inline critical CSS.
Missing compression (gzip/brotli)Compression reduces text resource size by 60-80%. Enable brotli on the server.

Best Practices

Optimize imagesWebP for photos, SVG for icons. loading="lazy" for images below the fold.
Enable brotli compressionBrotli is 15-20% more efficient than gzip. Configure in nginx: brotli on;
Set up cachingStatic: Cache-Control: max-age=31536000, immutable. HTML: max-age=0, s-maxage=60.
Preload critical resources<link rel="preload"> for fonts and CSS. Reduces LCP by 200-500ms.
Test regularlySpeed degrades over time. Check after each deploy and monthly.

Get more with a free account

Speed check history, competitor comparison and PageSpeed monitoring.

Sign up free

Learn more

Frequently Asked Questions

Server Actions vs API routes?

Server Actions — short-lived, called from a component, type-safe, RPC-like. API routes — public endpoints for external clients.

Are they safe?

You must re-validate auth + input inside the action. Next.js adds CSRF protection automatically. Always check ownership (IDOR).

Do they work without JavaScript?

Yes! If form action is a Server Action, submit works via native form POST without JS. Progressive enhancement.

Try the live tool that powered this guide

Free plan — 10 monitors, checks every 5 min, no card required. Upgrade for 1-minute interval and multi-region monitoring.