Nextjs 14: Server actions vs Route handlers
Asked Answered
G

4

7

I'm new to nextjs and the new updates are a bit overwhelming for me. It may sound dumb, but my question is: when should I use Server Actions and when should I use Route Handlers. Could I use them both in the same project or I can only use one of them (more likely Server Actions).

I have a bit of experience with Server Actions and I worked on a project that is using Server Actions to query from database. However I never used Route Handlers in nextjs (but I understand how they work).

Grandee answered 2/1, 2024 at 20:21 Comment(0)
S
6

Short answer

Both Server Actions and Route Handlers allow to write server-side code that can be invoked from the client-side. Route Handlers are a low-level abstraction, they allow to write REST API Code:

export async function GET(request: Request) {
const { searchParams } = new URL(request.url)
const id = searchParams.get('id')
const res = await fetch(`http://www.example.com/product/${id}`, {
headers: {
  'Content-Type': 'application/json',
  'API-Key': process.env.DATA_API_KEY!,
},
 })
 const product = await res.json()

 return Response.json({ product })
}

While Server Actions are a high-level abstraction, and they are preferably used to mutate data on the server (such as creating or updating a specific resource on the server). Server Actions under the hood use the POST HTTP method, and they can be invoked only by this HTTP method. Route handlers are preferably used to fetch data. Here's an example of Server Actions, a function updateUser that is located in the file actions.ts:

 // use 'use server' directive to indicate it is a server action
'use server'

 export async function updateUser(userId, formData) {
// ...
 }

And the client component can invoke updateUser as following:

'use client'

import { updateUser } from './actions'

export function UserProfile({ userId }: { userId: string }) {

// using `bind` to send the arguments to the sever action `updateUser`

const updateUserWithId = updateUser.bind(null, userId)

 return (
<form action={updateUserWithId}>
  <input type="text" name="name" />
  <button type="submit">Update User Name</button>
</form>
)
}

You can check the official doc about Server Actions and about Route Handlers

This link that states shortly the difference between the two.

Long answer

You can check this Reddit thread

Sheets answered 15/3, 2024 at 13:41 Comment(0)
D
1

Shortly: Server Actions are the new way to go. Use them as long as it works out for you and if not than Route Handler.

Route Handler are mostly the same as the "api" dictionary in older Nextjs Versions. Here you still have to fetch the data client side, handle state's and so on. For experience developer this is boilerplate code.

Deferential answered 2/1, 2024 at 20:33 Comment(1)
The documentation notes a few other neat qualities of Router Handlers though. For example, you could let a third-party service webhook a route handler. Still though, I agree with your strategy: Use Server Actions something prevents you from doing that.Buddhism
E
1

I would recommend server action for small projects, like personal blogs and portfolio websites, but if you're working for big projects that would require a lot of backend computations I would recommend going for route-handler

Embolectomy answered 12/3, 2024 at 13:18 Comment(0)
S
0

The main purpose of Server Actions is to run server code in the client components.

Before Server Actions, we were defining our server code in the Route Handlers, then we use third party library such as swr to fetch and mutate the data.

Now, we can use Server Actions to run them on server and client components without depending on third party library.

Stevenage answered 9/8, 2024 at 12:12 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.