CodePark/ questions / Route handlers & middleware
START PRACTICINGPRACTICE
Frontend question · Next.js › Route handlers & middleware

When would you use a Route Handler instead of a Server Action?

Use a Route Handler when something outside your React UI calls you. Use a Server Action for mutations from your own UI.

Server Actions:

  • are for mutations that your own UI triggers
  • are tied to your React app
  • use POST only
  • return results and updated UI to the component that called them

Route Handlers (route.ts) are general HTTP endpoints. They use the Web Request and Response APIs. Use them for:

  • webhooks, for example from Stripe or a CMS
  • a public or mobile API
  • OAuth callbacks
  • responses that are not UI, such as RSS feeds, files or images

Route Handlers support any HTTP method, custom headers and status codes. GET responses can be cached.

To read data in a Server Component, you need neither. Call the data function directly. Don't fetch your own Route Handler from the server.

  • Server Actions handle mutations from your own UI and use POST only.
  • Route Handlers support any HTTP method and give full control of the response.
  • Use Route Handlers for webhooks, public APIs, feeds and files.
  • Don't fetch your own Route Handler from a Server Component.