DEV Community

Cover image for Day 57 of #100DayOfCode — Understanding Server Actions vs API Routes & MongoDB in Next.js
M Saad Ahmad
M Saad Ahmad

Posted on

Day 57 of #100DayOfCode — Understanding Server Actions vs API Routes & MongoDB in Next.js

API routing in Next.js enables developers to create backend endpoints directly within their applications, allowing for request handling, data processing, and API exposure. However, as apps become more complex, especially with UI interactions like form submissions, API routes can become repetitive and cluttered.

That's where Server Actions offer a streamlined solution by enabling server-side logic execution directly from components, removing the need for a separate API layer. This keeps your code simpler and easier to maintain by placing logic closer to its usage.

Today, for Day 57, the goal was to understand what server actions is and how we can connect to MongoDB using both API routing and server actions


What Are Server Actions in Next.js?

Server Actions are a new feature in Next.js that allow you to run server-side code directly from your components without creating a separate API endpoint.

They are defined using the "use server" directive and are typically used inside React Server Components or triggered via forms.

Key Idea:

Instead of calling an API route, you call a server function directly.

Example: Simple Server Action

// app/actions.js
"use server";

export async function createUser(formData) {
  const name = formData.get("name");

  // Simulate saving to database
  console.log("User created:", name);

  return { success: true };
}
Enter fullscreen mode Exit fullscreen mode
// app/page.js
import { createUser } from "./actions";

export default function Page() {
  return (
    <form action={createUser}>
      <input type="text" name="name" placeholder="Enter name" />
      <button type="submit">Submit</button>
    </form>
  );
}
Enter fullscreen mode Exit fullscreen mode

No API route. No fetch. Just direct server execution.


Server Actions vs API Routes in Next.js

Here’s how they compare:

Feature Server Actions API Routes
Setup Inline in components Separate endpoint files
Network Request Not required Required (fetch/axios)
Use Case UI-driven mutations Public or external APIs
Performance Faster (no HTTP overhead) Slightly slower (HTTP roundtrip)
Reusability Limited to app Can be used anywhere (frontend/backend)
Security Runs on server by default Needs manual handling

When to Use What?

Use Server Actions When:

  • Handling form submissions
  • Performing simple mutations (create/update/delete)
  • Working tightly with UI components
  • You don’t need a public API

Example: Submitting a contact form or saving user preferences.


Use API Routes When:

  • Building a public API
  • Integrating with third-party services
  • Handling complex backend logic
  • You need endpoints accessible from mobile apps or external clients

Example: Payment processing, webhook handling, or external integrations.


Connecting MongoDB with Next.js

Connecting MongoDB with Next.js allows you to build full-stack applications where your frontend and database work seamlessly together. Whether you use Server Actions or API Routes, Next.js makes it straightforward to establish a database connection, perform CRUD operations, and manage data efficiently—all within the same project structure.


MongoDB with Server Actions

You can directly connect to MongoDB inside a Server Action since it runs on the server.

💻 Example:

// lib/mongodb.js
import mongoose from "mongoose";

export async function connectDB() {
  if (mongoose.connections[0].readyState) return;

  await mongoose.connect(process.env.MONGODB_URI);
}
Enter fullscreen mode Exit fullscreen mode
// app/actions.js
"use server";

import { connectDB } from "../lib/mongodb";
import User from "../models/User";

export async function createUser(formData) {
  await connectDB();

  const name = formData.get("name");

  await User.create({ name });

  return { success: true };
}
Enter fullscreen mode Exit fullscreen mode

This is clean and avoids unnecessary API layers.


MongoDB with API Routes

Here, you define a traditional API endpoint and connect to MongoDB inside it.

💻 Example:

// pages/api/users.js
import { connectDB } from "../../lib/mongodb";
import User from "../../models/User";

export default async function handler(req, res) {
  await connectDB();

  if (req.method === "POST") {
    const { name } = req.body;

    const user = await User.create({ name });

    return res.status(201).json(user);
  }

  res.status(405).json({ message: "Method not allowed" });
}
Enter fullscreen mode Exit fullscreen mode
// frontend usage
async function createUser() {
  await fetch("/api/users", {
    method: "POST",
    body: JSON.stringify({ name: "Ali" }),
    headers: {
      "Content-Type": "application/json",
    },
  });
}
Enter fullscreen mode Exit fullscreen mode

This approach is more flexible and reusable across platforms.


Conclusion

Server Actions and API Routes both solve similar problems but in different ways.

  • Server Actions simplify development by eliminating the need for API endpoints in many cases, making your code more direct and efficient.
  • API Routes remain essential when you need flexibility, external access, or more complex backend logic.

When working with MongoDB:

  • Use Server Actions for tight UI + database interactions.
  • Use API Routes when building scalable, reusable backend services.

Understanding and mastering both approaches gives us the flexibility to build modern, performant full-stack apps with Next.js

Thanks for reading. Feel free to share your thoughts!

Top comments (0)