Server Actions in Next.js: Replace Your API RoutesNext.js

Server Actions in Next.js: Replace Your API Routes

By Jeevan BhargavJun 13, 20261 min read29 Views

Featured Learning Resources

Boost your interview confidence. Practice coding layouts, review real-time feedback, and optimize your resume structure.

All Questions

Server Actions in Next.js: Replace Your API Routes

Server Actions are one of the most exciting features in modern Next.js. They let you call server-side functions directly from your UI.


Defining a Server Action

// app/actions/user.ts
'use server';

export async function createUser(formData: FormData) {
  const name = formData.get('name') as string;
  await db.user.create({ data: { name } });
}

Using it in a Form

import { createUser } from '../actions/user';

export default function CreateUserForm() {
  return (
    <form action={createUser}>
      <input name="name" placeholder="Your name" />
      <button type="submit">Create</button>
    </form>
  );
}

No API route needed!


Revalidating Data

'use server';
import { revalidatePath } from 'next/cache';

export async function deletePost(id: string) {
  await db.post.delete({ where: { id } });
  revalidatePath('/blog');
}

Final Thoughts

Server Actions simplify your codebase by removing the need for separate API routes for most CRUD operations.

Happy Coding!

Share this Resource

Spread the knowledge with other engineering candidates.

Was this card helpful?

Help us rank high-quality interview preparation materials.

Jeevan Bhargav

Written by Jeevan Bhargav

Creator of InterviewsAce.AI and Frontend Engineer.

Discussion (0)

Please log in to participate in technical discussions.

No comments yet. Start the discussion!