This documentation is for a legacy version of Next.js Supabase Lite. For the latest version, please visit the Next.js Supabase Turbo documentation

API Routes vs Server Actions

API routes and Server actions can be used for similar use cases. This guide will help you understand the differences between the two.

API Routes and Server Actions can indeed be used in similar ways: ultimately, they both allow you to write server-side code that can be called from the client-side. However, let's look at the use-cases for each of them to understand the differences.

TLDR

Use API Routes when fetching data, and Server Actions when performing actions/mutations.

API Routes

API Routes are more generic and a lower-level abstraction than Server Actions. They are a way to write server-side code that can be called from the client-side. They are a great way to expose a REST API, or to write server-side code that can be called from the client-side.

The downside of API Routes is that they need to be called using the Fetch API, which you can use directly, or through a library such as React Query or SWR. This kit uses SWR.

Generally speaking, API Routes should be preferred when fetching data - rather than performing actions/mutations.

Server Actions

Unlike API Routes, Server Actions are a higher-level abstraction. They are a way to write server-side code that can be called from the client-side as POST requests.

They are particularly useful when you want to perform actions/mutations on the server-side, such as creating a new user, or updating a user's profile.

Thanks to utilities such as revalidatePath and revalidateTag, you can also use Server Actions to invalidate the cache of a specific page or tag (used with fetch).


Subscribe to our Newsletter
Get the latest updates about React, Remix, Next.js, Firebase, Supabase and Tailwind CSS