Why Use Server Actions?

I can see the benefit of the server component version. Colocated, no need to make an api endpoint in another file.
import { cookies } from 'next/headers'

// Server action defined inside a Server Component
export default function AddToCart({ productId }) {
async function addItem(data) {
'use server'

const cartId = cookies().get('cartId')?.value
await saveToDb({ cartId, data })
}

return (
<form action={addItem}>
<button type="submit">Add to Cart</button>
</form>
)
}
import { cookies } from 'next/headers'

// Server action defined inside a Server Component
export default function AddToCart({ productId }) {
async function addItem(data) {
'use server'

const cartId = cookies().get('cartId')?.value
await saveToDb({ cartId, data })
}

return (
<form action={addItem}>
<button type="submit">Add to Cart</button>
</form>
)
}
But isn't the client component version just another way of writing API endpoints?
'use server'

export async function addItem(data) {
const cartId = cookies().get('cartId')?.value
await saveToDb({ cartId, data })
}
'use server'

export async function addItem(data) {
const cartId = cookies().get('cartId')?.value
await saveToDb({ cartId, data })
}
Guess you can use it in form without javascript:
'use client'

import { addItem } from './actions.js'

// Server Action being called inside a Client Component
export default function AddToCart({ productId }) {
return (
<form action={addItem}>
<button type="submit">Add to Cart</button>
</form>
)
}
'use client'

import { addItem } from './actions.js'

// Server Action being called inside a Client Component
export default function AddToCart({ productId }) {
return (
<form action={addItem}>
<button type="submit">Add to Cart</button>
</form>
)
}
But using it this way feels sucky as there is no way (that I know of) to make it typesafe.
2 Replies
alan
alan16mo ago
I can't tell if this question is limited to this specific example or if it's being asked in general why server actions should be used if the latter, I see it as a great replacement for trpc if you're concerned about type safety and would prefer to limit the number of tools you use and are already using next with the app router
Luc Ledo
Luc LedoOP16mo ago
It's like a worst trpc, I really don't see the point of it yet.
Want results from more Discord servers?
Add your server