What Is a Nextjs Action?
When you hear the term Nextjs Action, think of a lightweight server‑side function that lives inside a Next.js route. It lets you handle data fetching, form submissions, or any custom logic without leaving the page’s component tree. By bundling the code with your Next.js app, actions keep the API surface small, reduce latency, and simplify deployment.
How Nextjs Actions Differ From Traditional APIs
Explaining the difference of a Nextjs Action from a classic REST endpoint helps developers decide when to use each pattern:
- Location: Actions are defined next to the page or component, while APIs live in /pages/api or a separate backend.
- Data Flow: Actions can be called directly from React event handlers, eliminating the need for extra fetch calls.
- Security: Because actions run in the same runtime as your page, they inherit the same session and authentication context.
A Full Tutorial and Breakdown of the New Nextjs Action API
Today we are making significant improvements to your development workflow with the NEW React & Next.js integration. Follow these steps to build the easiest contact form using a Nextjs Action.
Step 1 – Set Up a Fresh Next.js Project
- Run npx create-next-app@latest my-contact-app and choose the app router option.
- Navigate into the folder and install dependencies: npm install.
Step 2 – Create the Action File
Inside app/contact create a file named action.ts (or .js if you prefer JavaScript). This file exports a single async function:
export async function POST(request: Request) { const data = await request.json(); // Validate fields if (!data.email || !data.message) { return new Response('Missing fields', { status: 400 }); } // Simulate sending an email await sendEmail(data); return new Response('Message sent', { status: 200 }); }The function automatically becomes a Nextjs Action that can be invoked with a fetch call from the client side.
Step 3 – Build the Contact Form Component
In app/contact/page.tsx add a simple form that uses the action: