0
0
NextJSframework~5 mins

API routes vs server actions decision in NextJS

Choose your learning style9 modes available
Introduction

API routes and server actions both let your Next.js app talk to the server. Choosing the right one helps your app work better and be easier to build.

You want to handle data fetching or updates from the client with a clear API endpoint.
You need to share server logic between different parts of your app easily.
You want to keep server code close to your components for simpler code.
You want to avoid writing extra API endpoints for simple server tasks.
You want to use built-in Next.js features for server communication without extra setup.
Syntax
NextJS
API Route example:
// pages/api/hello.js
export default function handler(req, res) {
  res.status(200).json({ message: 'Hello from API route!' })
}

Server Action example:
'use server'
export async function addData(data) {
  // server logic here
  return 'Data added'
}

API routes live in the pages/api folder and act like normal API endpoints.

Server actions are functions marked with 'use server' and can be called directly from components.

Examples
This API route handles POST requests and returns success.
NextJS
// API route example
export default function handler(req, res) {
  if (req.method === 'POST') {
    res.status(200).json({ success: true })
  } else {
    res.status(405).end()
  }
}
This server action saves a user and returns a confirmation.
NextJS
'use server'
export async function saveUser(user) {
  // save user to database
  return 'User saved'
}
Sample Program

This example shows a server action greet called from a React component. When you click the button, it calls the server action and shows the greeting.

NextJS
// app/actions.js
'use server'
export async function greet(name) {
  return `Hello, ${name}!`
}

// app/page.jsx
'use client'
import { useState } from 'react'
import { greet } from './actions'

export default function Page() {
  const [message, setMessage] = useState('')

  async function handleClick() {
    const result = await greet('Friend')
    setMessage(result)
  }

  return (
    <main>
      <button onClick={handleClick}>Greet</button>
      <p>{message}</p>
    </main>
  )
}
OutputSuccess
Important Notes

Use API routes when you want a traditional REST or JSON API accessible from anywhere.

Use server actions to keep server logic close to components and simplify data handling.

Server actions require Next.js 14+ and App Router setup.

Summary

API routes create separate API endpoints for client-server communication.

Server actions let you call server code directly from components without extra endpoints.

Choose based on your app's needs: API routes for broad API use, server actions for simpler, integrated server calls.