Closed SaadBazaz closed 11 months ago
I think what you're asking is generally not possible, because the API endpoints are meant to handle raw request objects, whereas server actions are just plain functions that don't care in which format the arguments are provided. However, nothing prevents you from calling your server actions from within your REST API handlers, so your Next REST Framework handlers could look something like:
...
handler: async (req) => {
const jsonData = await req.json();
const res = await myServerAction(jsonData);
return NextResponse.json(res, {
status: 200
})
},
...
Additionally, you could abstract the example above to a single function where you could pass your server action as an argument and use that throughout your application.
That's exactly what I thought too. Ok I'll see if I can kill these two birds with one stone
I'm working on a project and I have an interesting proposition.
What if we could create Next APIs, and with the same functions, we could create Next Server Actions?
Benefit:
Right now my setup looks something like this:
As you can see,
createProject
is being repeated on both sides. If we could make the handler compatible with the REST API somehow, we could have one function for both.I'd prefer if there was just one "handler" with does both the Server Action and can be used for the Rest API.