Reputation: 755
I'm having trouble understanding what Next.js 13 Server Actions are. I'm not getting it.
Is it just basically a way to run API calls in a server component to get or post data before sending the finished code to the client side?
Is that all a Server Action is? A way to use APIs on the server instead of the client?
Couldn't you already do this before Server Actions though?
What are Server Actions and how do they work theoretically? Please explain as if I'm a 6th grader just learning how to code.
Thank you.
Upvotes: 0
Views: 1551
Reputation: 56
"same same, but different"
Diferences
Server actions are basically an obscure implementation of an api route, though not the same.
With a regular http api you will make a fetch and get a response, you will have a clearly defined api endpoint, e.g http://domain/api/endpoint
. Your endpoint could be configured to receive different request types like, get, post, etc. Within NextJS calling them will be done with either the fetch api or another library like axios. You will have to pass all the request type, authentication, headers, data, etc. required by the api route.
Server actions differ firstly by the fact that they have no clearly defined route. You can organize them in some folder structure in your project or you can have them inline in your components (you can check documentation for specifics how to do that). Next difference comes from how you call them, i.e. you simply do it as if it was any other function. Your server action might have a request parameters so you pass them like myAction(data). You do not need libraries or api to assist.
How are they actually accessed?
Regardless of which one you use, your client will make a fetch request. Here the main difference is that an api route will make the fetch with a specified type (GET, POST, etc.), while a server action will do a POST request.
3rd party access - i.e. Postman, cURL, or if you want someone else to access them from their application. Here things get a little tricky. Regular http api routes should be accessible from any source (depending on network setting, firewall, etc.) by simply passing the route (http://domain/api/endpoint
) and passing the credentials, body, type, etc. Server actions on the other hand are not supposed to be accessed outside of the NextJS project. Although more complicated, up to NextJS 14.2, the server action can be accessed with a POST request carrying the correct cookies, data and headers too.(This might not be the case in future releases of NextJS)
Examples:
// API Route (fetch)
import {
NextResponse
} from "next/server";
export async function GET() {
return new NextResponse(JSON.stringify({
data: "Great Success!"
}), {
status: 200,
});
}
// Server Action
"use server";
// This action is not gated by the user role, so it is accessible to anyone
export const exampleOpen = async() => {
return {
data: "Great success!"
};
};
How to read the response
You will have to await the response, then if matches your requirement (usually response.ok or response.status === 200) you will extract the data from the response (e.g. response.json > data).
You will await the response of the function and then extract it from the response.data
Would be happy to see if anyone knows of any other caveats.
Upvotes: 1
Reputation: 49571
server action is still an api call to the server. You do not create an api route, instead next.js creates for you. when you submit the form, the browser will collect the form inputs as a little packet of data and send it off in a post request to server via POST request. when you execute a server action, add a break point on chrome tools and you will catch the code:
from there this is fetchServerAction
async function fetchServerAction(state, param) {
let { actionId, actionArgs } = param;
const body = await encodeReply(actionArgs);
const res = await fetch("", {
method: "POST",
headers: {
Accept: _approuterheaders.RSC_CONTENT_TYPE_HEADER,
[_approuterheaders.ACTION]: actionId,
[_approuterheaders.NEXT_ROUTER_STATE_TREE]: encodeURIComponent(
JSON.stringify(state.tree)
),
...(process.env.__NEXT_ACTIONS_DEPLOYMENT_ID &&
process.env.NEXT_DEPLOYMENT_ID
? {
"x-deployment-id": process.env.NEXT_DEPLOYMENT_ID,
}
: {}),
...(state.nextUrl
? {
[_approuterheaders.NEXT_URL]: state.nextUrl,
}
: {}),
},
body,
});
....
}
as you see, browser makes a POST request using fetch
without passing any URL
Upvotes: 1
Reputation: 755
I learned Server Actions are a way to run functions on the server that you don't want to be run on your client side.
The best example of this I can think of is analytics. Instead of running analytics API calls on the client side, which would slow down the UI, you can can run analytics API calls on the server.
This video helped me understand everything better than any other video I've watched: https://youtu.be/hD11c2mrq6Q
Upvotes: 0