Server Actions: NextJS 13.4's Best New Feature

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
versel announced a whole bunch of things last week for their service but also for next JS now next js13.4 takes nexjs app router from beta into release which is great so app router is Now the default for our applications it also adds server actions which are a great way of building back end for front-end apis really easily in our application no longer would we have to use API routes now we can just use these server actions embedded right in our components they are really cool this video is going to dig into them it's going to show you how to do them give you some advice on when to use them and how to use them safely let's get right into it foreign so to start off we're going to use MPX create next app at the latest and then we're going to call our project next.js 13 server actions of course all this code is available to you on GitHub there's a link to that in the description right down below let's hit enter and see how we go of course we want to use typescript we want to use eslint we want to use Tailwind CSS we want to use the source directory and this is the new fun part with the release now we've gone from App router being an experimental thing to just being the recommended way to do our application so now the app directory that we've all been messing around with for a while now is now the default standard so let's hit yes and then just to make sure that we're using the right import Alias I'll make sure that it's at slash and there we go all right now I'll bring that up in vs code and I'll run the server in development mode okay it looks good we got our next js13 server running let's go and experiment with our first server action which relates to how we handle form post let's get right into the code so for our first example let's go take out all this boilerplate and to start off we're going to create a very very simple to-do list so let's start by just creating some locally stored to Do's on our server so now we got our array of to-do's let's go and format them so we can see them and let's just put one in there to start so we can see it let's go take a look at our page looks good so we got our learn react now let's go and create a form where we can submit to add items to that to-do list so down here I'm going to create a form tag and then into that I'm going to add an input for the text call it to do and give it some nice Tailwind styling and then we'll add a submit button that will submit that form again with some nice Tailwind styling let's go take a look and yeah there you go so let's say we have hay let's hit add and it does nothing so how do we go and add that to do to the to-do list to do that we're going to create a server action so let's go back over to our code and up here in the body of the component we're going to create a new asynchronous function called add to do and it is going to take form data as its argument so that would be the form data coming out of that form now to declare a server action all we need to do is put use server inside of this function and that says that it is a server action now in order to add that to do to our to do list up here we've got to go and first get that data out of the form data here so let's go and bring that in so to do that we just do data.get that is a form data object method and we course that to a string now I've got the to do string and we just push that to do onto the list of to-do's now all we need to do is connect this add to do server action to the form to do that we just say action equals and then give it that add to do let's try it out okay so it blew up and the reason is because we don't have server actions enabled it is still an experimental feature so let's go and add that go over here to our next JS config and we'll add on experimental and into their server actions and say that it's true okay looks pretty good let's give it a try so I'm gonna add hello and to do and hit refresh and there we go it's added how cool is that but of course we don't want to have to hit refresh in order to see the new data is there a way that we can do that page invalidation and revalidation automatically absolutely let's go back into the code and add in a revalidate path down here that will essentially refresh the page let's bring in revalidate path from the cache and Save all right let's try it out okay awesome how easy is that so of course I can hit refresh a bunch of times on the server and we will always get the same list of to-do's and in fact I can go over to another browser let's say Safari and now we'll see the exact same list of to-do's why we are talking to the same server and the server has that list of to-do's in memory now it's important to know that these are not session specific to Do's we only have the one list of to do so no matter who you are where in the world you're coming from you're always going to get this list of to do so it's important when you do these server actions to understand the context do you want this to be a session specific thing do you want this to be a global thing and make sure that you implement your code appropriately so it's unlikely that you're going to be using memory to store data like I have here more likely this ad to do is going to be calling out to a database or some key value store to actually store the data long term don't store anything in memory because you're probably going to have multiple servers running simultaneously and the memory is not going to be synchronized between all of them so that's number one you're probably gonna be calling out to some service here the second important thing to know is that you're actually creating an API when you create one of these server actions if you had API routes in the past and you added a lot of security to those endpoints you're going to want to do the same kind of thing here because let's go take a look over in the server you can see they're actually making a call to the server anytime that we hit this form post so let's type in somebody hello again bring up the network inspector hit add to do and we can see that we are actually making that request to the server so you're going to want to make sure that that API endpoint is as secure as any other API endpoint that you're going to publish on your server so we're going to try out a few more variations when it comes to server actions let's go and take each one and put it into its own directory so you'll have them in the GitHub repository of course linked to in the description right down below we'll call this one form post so go and take the contents here go create a new directory under Source app called form post and into there create a new file called page.tsx now I'm just going to remove the contents from the home page and we'll add a link for our first example and go over to our home page click on our form post and there we go same example as before awesome now before I move on I do want to show one really cool thing so let me go bring up the console again [Music] I'm going to hit command shift p and then type in JavaScript I'll disable JavaScript and then hit refresh now we can't load anything so let's try this again let's go goodbye here hit add to do and it still works we have a react app that works without actually having any JavaScript running on the page let me prove it so I'll go over here into Visual Studio code go into our layout and I'll add a no script tag to our layout no script tags are only shown if there's no JavaScript so let's go back into our Arc hit refresh and we can see JavaScript is disabled so 100 we now have a react app that can work without JavaScript on the front end this is actually really cool I don't think we've ever had this in next.js specifically so awesome now let's re-enable JavaScript because we're not crazy but what happens if that form post takes a little while we want to be able to for example disable the add to do button if the form post hasn't completed yet so to do that we're going to use a new experimental hook called use form status let's go over into our code so I'm gonna go take our existing example copy it and then we're going to create a new directory called form post with status create a new file in there called page.dsx bring in our old code and I'll link it up in our page all right looks good let's go take a look at our code the first thing we want to do to simulate a slow service is to actually slow down our server action so let's go and add a little three second delay in there to say hey it's going to take a while to actually add your to-do so let's hit save and ignore Arc hit hello hit add to do and we can see one two three hello so we want to disable the add to do while it's waiting so let's go back into our code so what we want to do is disable this add to do button that means we actually have to run some JavaScript on the client which means that this to do button actually has to be client component so let's go bring that into a an add button component looking good so far so let's go and make that a client component that way we can use a hook and the hook is experimental use form status which we will Alias to use form status now when you invoke that you get an object back and one of those object elements is pending true if it's going and false if it's not going so let's disable it if it's bending and now that we have our add button let's go bring that into our page and just replace our existing button with that button we'll do hello again hit add to do and now we can see that it's grayed out until it comes back nice super clean another way to monitor this API transaction is to use transitions now transitions came along with react 18. we haven't really gotten all that much use out of them yet at least I haven't but I think they're really cool in this case and they start us along the path of using server action is not as form post but as just something you would call on the server like a function directly so let's go and create a transitions version of this and we'll start on that journey of getting to where we make an imperative call to our server action so I'm going to go back into our home page and then create another route for with transition and then I'll copy our form poses status and create our Forum post with transition all right let's go take a look at our foreign place with a transition now to get your transitions we need to change how we're talking to our server action here we are posting to our server action using a form instead we want to just call the server action as we would in the other functions so let's migrate add to do first to do that we're just going to get the to do as a string and then just add it to our list so we can get rid of our form data stuff now we can see from the red squiggly that the add to do action is no longer compatible with forms so let's just go and take this form and turn it into a div so now how is ADD button actually going to call add to do well it's going to go and get add to do as a prop so let's go and add that to add button and then we're just going to call add to do with the text but how do we get the text since we don't actually have the input here so what I recommend we're going to do is we're going to go and take this input and add it to the add button so let's go just take out all of that div and add it into here now this component also controls this text input so in order to get the value of that text input we need to have some connection to it we could use use state for that or we could use a ref so let's just use a ref make it real easy and we can get rid of this use form status stuff since we're no longer using a form and then we'll create a to-do ref and just connect it to that input so now down here in our button let's not worry about disabled for the moment let's just create an on click Handler that will then handle clicking on that button and calling add to do and then we can get rid of type submit on the button okay looks pretty good so we'll go to form post with transition and I will try hello hit add to do and yes there you go three seconds and that's actually really cool let's go take a look at the code and see what's happening so we're getting this and to do function from page that function just happens to be a server function and then whenever we invoke it it automatically runs on the server as opposed on the client updates the server State and then we do that revalidate path to refresh the page of course I think in this case it should be slash Forum post with transition but it still works interesting now it works but we want to do what we did before which is where we gray out the button when the transaction is in flight so how do we do that well that is when we use transitions so let's go back over to our add button bring in use transition then we call that use transition and we get back start transition and then we wrap our add to do in that we make it an async function and now we have pending back because we got that from the transition so let's go and re-enable are disabled and try this again nice now there's two ways that I can think of using these server actions of course I'd love to hear from you in the comments about how you are going to use them but the other way that I can think about using the server actions as opposed to what we're doing here which is mutating the state of the server it's just to do things like searching as an example so for our last example I'm going to just create a Pokemon search example and you'll have that as a way to see how you might do some kind of dynamic searching that has to be run off of the server on the client so let's go and create this search example so go back to the home page and I'll create one more example we'll call this Pokemon search I'll create a new directory for that and into there I'll create a new file called page.tsx I'll create our Pokemon search component and then return a simple page wrapper so let's go and start with our server function we'll create a new function called search it'll take a search string we'll Define it as a server function by using use server just as we have before and you know what just to prove that it's actually on the server I'm going to put in a console log there saying that we're searching for something and then we're going to make a call onto our Pokemon API this is the list endpoint so if we go and bring this up in the browser you can see that we just got a ton of Pokemon in here in fact 1281 where each Pokemon just has a name and a URL classic rest style API now this Pokemon data now has an array of all those results so let's go and filter that to just what we want coming out of our search so we're just going to use a to lowercase on the name and see if it includes our search to lowercase then we're going to grab out only the name if we want to return an array of names and we're going to take the top 50 names that match that criteria so that's going to be the output of our search function is going to be just a promise to a string of names now we're going to invoke This Server action using JavaScript off the client so we need to have a client component to do that so let's create a new client component called Pokemon list and it will be a client component and let's return a nice little template out of there and we'll start off with the Pokemon names because that was what we're going to get at the end of that search so let's go and create some state to hold Pokemon names so now let's go bring that into our page and then invoke it down in here and now we want to give it that search action so it can actually go and make the search of course it doesn't know what a search action is so let's go and Define that property so now we want to invoke that the first time we want to invoke it is when the component first mounts so let's go and use a use effect for that we use an empty dependency array because we only want it to run once and then we're going to call that search with an empty search ring and then just set the names to whatever comes back off of the request now this is we haven't listed search as a dependency search is never going to change so it's okay to just add it let's just add it and get eslint off our back and let's try it out all right so that's actually made the request let's go back over to visual studio code take a look down here and we can see that we actually did hit the server we're searching for nothing in this case and that is called from a post to slash Pokemon search that in turn makes a call to the Pokemon API again on the server and it is a cache Miss because this is the first time we've ever done that so no problem all right let's go back over into here and add in a search field to do that we need to create some state so we'll create some State called search string now let's create some UI for our search box we want to have a search input and we want to have a search button so we'll use a flex to actually put those side by side and then into there we will part our search field and then we'll have a search button then when you click it we'll call the on click and we'll call it search so we need an on click let's go back over here and have an on click all it's going to do is just set the Pokemon names with whatever we get back from the search how easy is that all right let's try it out let's try and bulb hit search and there you go now let's go back to vs code and take a look at our console and we can see that we're doing something really cool here we're getting a cash hit each time we do the server action so let's go back here and take a look at our server action we are making this call to our Pokey API this is being cached because this fetch because it is overridden by next.js is a cached fetch so we are only ever going to make that fetch call to this endpoint once now if we were to go and give it different queries or change that value then it would miss until it got the same value again and then I would hit in this case we're giving it the same value over and over and over again therefore we're always going to hit and that's why the response is so fast now notice that this server action is not doing the same thing as the other server actions did where we revalidate the path that's because nothing is changing on the server we're not mutating the state of the server all we're doing is just returning some data out of here just as we normally would any other function so we don't have to do that path revalidation now if you're more interested in this style of use case for Server actions you might want to check out Theo's z-act it is a Zod slash server action Fusion which allows you to do validated and type safe apis using this mechanism so you basically say this particular action is going to take these particular inputs and it makes sure that the inputs are valid coming into it so when it comes to securing your apis this is actually a really good way to go okay I hope this gets you excited about all of the possibilities of client and server interaction that we get with next js13.4 server actions let me know in the comments right down below of course a link to this code is in the description in the meantime if you like the video do me a favor and hit that like button that's the way that the YouTube algorithm gets to like and share my videos and of course I would love a subscribe if you want to see more videos just like this one
Info
Channel: Jack Herrington
Views: 42,362
Rating: undefined out of 5
Keywords: next 13, nextjs 13, next.js 13, next js 13, nextjs react 18, mui nextjs, vite nextjs, nextjs, next js, next.js, nextjs react, nextjs typescript, next js typescript, nextjs npm, react 18, vite, react, reactjs, react.js, react app, nextjs redux, redux next js ssr, next js 13 ssr, nextjs ssr, react 18 ssr, react ssr, next js server actions, next server actions, next 13 server actions, server actions next js, server actions nextjs 13, server actions, nextjs 13.4
Id: czvSZqnpTHs
Channel Id: undefined
Length: 21min 40sec (1300 seconds)
Published: Thu May 11 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.