Next.js Route Handlers | API Routes in Nextjs 13

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] hello and welcome I'm Dave today we're exploring the new route handlers for building API routes in next js13 and I'll provide links to all resources in the description below I'll also provide a link for you to join my Discord server where you can discuss web development with other students and you can ask questions that I can answer and receive help from other viewers too I look forward to seeing you there I've got Visual Studio code open in a terminal window as well and we're going to create a new application to explore the route handlers in nexjs13 today so I'll go ahead and enter in npx create next app at latest I'm going to name this one next07 just to add to my series you can name it whatever you want to typescript yes eslint yes Source directory we're going to say yes here and this is a change from what I've done before and I know I've had a few comments where I've created some confusion you can use Source directory with the new app directory I have just emphasized that app directory in the past however everything is going to be inside the source directory and after that it will be the same so you'll see what I mean if you look at the file tree after we create this project I'll go ahead and take the default there as well it will create this new project and we'll get started with NYX js13 route handlers I'm in the next JS beta docs and as we see here under API routes it says API routes have been replaced by Route handlers in next.js 13.2 so the old API routes are still supported in the Pages directory and of course that no longer exists when you install a nexjs 13.2 project however it says they recommend using route handlers with the app directory instead so that's what we're going to look at let's go ahead and click on Route handlers and as we bring this up I think this example can be just a little confusing so I want to talk about it here it talks about route handlers and we create route Dot TS or JS if you prefer but we create those files inside of the app directory but what it doesn't show is an API directory here but typically we're still going to create an API directory to put those in you don't have to though so I'm not saying you have to it's just that normally we would do that to organize but we're going to have that API directory inside the app directory and that's what you get when you start an example next JS project anyway and there is a note here about the route handlers as well they have these good to know notes throughout the beta docs and they are good to know so it says route handlers are only available inside the app directory so you're not going to try to create one of these new route handlers outside of the app directory at all again when we look at the example project there is already an API directory inside the app directory so now I'm back inside the new example project in Visual Studio code and notice we have this Source directory since I said yes to the source directory this time and when we we open it up inside we have an app directory right away so everything that you see here now is inside the app directory which is inside the source directory and that's the difference and one of the things we have is an API directory that's already provided and notice it has a new directory named hello so this is the slash API slash hello route so let's look at this route Note in this example get request we notice it's a get request right here they give the request object here and the type however you don't really need that so we can just remove it and this route will be statically evaluated and not dynamically and we'll talk about what dynamic routes are here in just a moment as well but this means there's essentially no variation in the request or the information that we depend on from those incoming requests it's always going to respond in the same way and without that information it can be statically evaluated now to try this out we're going to need to go ahead and start our project so I will go ahead and open the terminal and then I'm going to say npm run Dev but we're not going to need to bring up the front end example page or anything like that I'm just going to keep it running here and this is a back end API endpoint just like if you were to create a rest API essentially so we can test this out with something like Postman or if you have the extension installed thunderclient and I have that right here as you see in my activity bar if you don't go to extensions and then search for under client I think is it one word or two it's two words so if you search for that you can find this thunderclient extension and install it you can see I already have it installed here and so I'm going to close out of that but if you use that that's what I'm using today so now that we've started our project let's go ahead and create a new request and here it has the thunderclan.com welcome we don't want that we're going to just have HTTP on our Local Host instead of https and then two slashes localhost Port 3000 and then we're at API slash hello and that should be sent to that hello endpoint that we have right here if we look back in the file tree we're at API hello and then the route dot TS essentially fills the same role for an API that the page.tsx does when we're looking at different page routes but you cannot have a route.ts in the same directory as a page.tsx you don't want to have a route and a page in the same directory so now let's go ahead and run this with ThunderClan I'm going to send the request here and we'll see the response we get back I'll drag this up we're not sending any parameters in the URL either so we send this and we get hello comma next JS exclamation mark right there and that's what we were expecting to receive because you can see how this endpoint sends that response now we're back in the beta docs and I'm going to scroll down just a little bit here on the same page where we were looking at Route handlers and we see static route handlers and that's exactly what we were just working with there they are statically evaluated when using a git method and we don't really need that request object in there so that's why we removed that just as we see with the example it's not in here so that's what we want but what if we want to send Json back notice they're using a next response and the reason we're going to use that we'll scroll down just a little bit further a typescript warning here in the betadocs although response.json is valid we're going to have an issue with it with typescript so for now we need to use nextresponse dot Json and they've extended the response type they've also done that with request but we don't need that at this point so let's go ahead and now put a Json response in our hello endpoint and we'll need to use this next response as we do it back in vs code let's go ahead and import our next response at the top so I'll say import curly braces and next response and that comes from next slash server after that we can go ahead and use that response instead of the response we have here so we'll just copy that and paste it in but then we're going to say dot Json and now let's send a Json object so what we want is curly brace and then I'm going to send message in quotes and then our response message here would be hello nextjs and then another curly brace and you can see I've still got a red squiggly because I need to remove the new keyword at that point so let's save this everything looks good let's go back to our ThunderClan request tab here and we'll send another request to that endpoint and now we get our Json response here okay I think we've learned enough about our example hello route that we can create our own new route now so let's select the API directory here and then inside the API directory we're going to create another new directory so instead of hello let's call this one Echo and let's create an endpoint that Echoes whatever it receives or it echoes the parameters that it receives at that end point and we weren't sending any parameters with this request so that will be something new as well so now let's create a new file inside of this Echo directory and we'll call this route.ts as well so you can see it follows the pattern just like we did with our pages and always creating page.tsx files so I'm going to start by importing that next response once again and after that we'll go ahead and type RFC to get a export default function here and I'm going to make this an async function as well so I need to put that in and then I'm going to rename this and it's going to be get once again for this route and actually it doesn't even need the default for a route so we can just go with export async function and get now we want to go ahead and put in the request objects so we're going to say request in lowercase and that's going to be a type it is the request type the request object here and now we want to Echo any of the parameters that might be sent in the URL for a get request so to do that we want to get the search params we're going to destructure those so we'll say search params and that's going to equal a new URL and inside of this will pass in the request dot URL so now we've defined the search params that we are receiving and when we look at what type the search params are you can see they are URL search params and you could look that up on mdn as well to learn more about that but what we can do is use a git method so if I say const name equals search params.get and then pass in name it's going to return the value for name if that search param exists now I'm going to copy this down and do one more and here I'll call this instrument so we're going to get the name param and the instrument param if they exist after that we want to return those so let's go ahead and create this response I'll get rid of the div that we have here and instead we'll have next response dot Json and then we'll pass this object here that is name and instrument so let's test this out now and go back to our new request and instead of the hello route we're going to go to the echo route now we can add parameters here in thunderclient below but you'll see them get added to the URL to see how that's created as well so let's go ahead and add the parameter here and the first one was name so I'll put Dave and notice it's being added up here so the first one you would have the question mark the name equals Dave now let's add another one I'll need to drag this down I'll have instrument equals guitar so then there's the Ampersand and then you put the next param and have that equal the value so now we're sending both of these params in the URL and that's how they would be received with a get request so let's go ahead and send this and see if it works yes they were echoed back to us name and instrument now the downside here is this isn't flexible it has to be name and instrument it's not going to Echo any other params it's only expecting those two when we look at the route we created so now let's modify this so it will Echo any param we send so I'm going to leave these individual lines that we're no longer going to use and just comment them out so you could see them inside of the source code for this lesson and I'll copy that down so I can comment one out as well and now let's go ahead and get the search param values in a different way so I'm just going to Define I need cons there we go obj for object I'm just going to define a basic object here and I'm going to use object dot entries and then inside of object oh I said entries it needs to be ROM entries pardon me and then inside of that I'm going to have my search params and I'm going to call the entries method to get those values so now we've got an object that has those entries okay so now our response needs to be different as well instead of this object here with name and instrument it's just going to be whatever the object is now this will Echo any params that are received and just to verify that works let's go back to our request and let's change these this could be nickname and this could be Hobby and now let's go ahead and send these and yes it's echoed instantly nickname and hobby so any params we send we could change this once again to last name and let's change the value also so here I'll put gray and over here we could do something else like code equals often there we go and and it still works so it's going to Echo any params that are sent and we're back in the beta docs once again and now we're looking at Dynamic route handlers says route handlers are evaluated dynamically when you're using the request object with the git method so that's part of why we removed it before remember when we saw this request in the request type with our get request just for that hello example and we didn't need that so we removed it so it would become statically evaluated however with the request object get methods are dynamically evaluated uh any of the other HTTP methods so post put delete options Etc any of the other methods are going to be dynamically evaluated and then also when you're using Dynamic functions that use cookies and headers and they give some examples so I thought about what could be just a good example of something you would frequently use one of these other methods for like like post and I think it would be to evaluate some form data so let's go back to vs code where I have a form ready to go okay we're back in vs code and you can see I am not in the API directory that's underneath app which once again I should remind you you don't have to create an API directory it just seems like that's the best way to organize it and that's the example the next JS gives us of course when they create the hello route that your example project usually comes with when you do the install however here we're in the app directory and now we're back to pages so I have a feedback route that has a page and then a thank you route that has a page and on the feedback route is where we have a feedback form now this is a react form I've got other tutorials on my channel that go about creating forms in react if you're interested in that and the change event handlers all of those things I assume you've already done some of that if you're at this next JS level of the series so I'm just providing this form you can look at it in the course resources but once they fill out the form then they would be routed to the thank you page of course but it is going to submit here in the handle submit it's going to send this to our feedback route that is at API slash feedback so that's the route we now need to create so let's go ahead and go into the API directory create a new directory named feedback and inside of this feedback directory will create a new file and it will be a route.ts file let's once again start by importing the next response that we're going to use and after that import let's create a type so our type will be feedback we'll set this equal to a type that has an optional name which would be a string and now I'm going to use shift alt in the down arrow twice because we'll also have an email that is optionally there and we'll have a message as well so this is our feedback type it will have a name email and message all coming from our form and they might be undefined now we're going to require them in the form so I'm actually being just a little safe here in saying that they might be undefined but we'll go with that and now we'll say export async function and this will be a post request that we're going to receive it will still have the request object though and we can just use the standard request instead of the next request but that is also available to us from next.js now let's define the data that we're going to receive and it's going to be of the type feedback we'll set this equal to a weight request.json now this is different if you're used to working with say a framework like Express and it took me just a little bit to get used to it as well because I'm used to getting things from the request.body so this all you need to do is call Json here on the request itself so just a little different now let's go ahead and log to the console now remember this is on the server side here this is our back end so when we log to the console this will show up in the terminal window that would be the console for the server so we'll log this data after that we can get the name email and message we're destructuring now from that data once we have that let's go ahead and well we don't really need to log anything else here I guess we've got it all above so we you could log any one of these just to confirm you're getting a value if you want to then let's go ahead and return our next response dot Json and this will have the name email and message that is being sent back now of course at this point you could process the form data you could save it in a database you could do anything you want with it we're just going to respond again kind of echoing that same information just to show how this post request is received and how it works and how you can get the data out of it okay I need to open a terminal window and restart the server here after I added Tailwind to the project with that form I added so I'm going to go ahead and type npm run Dev if you don't have yours running go ahead and start it as well once we do that we're going to now go to our localhost 3000 in the browser with control on a click and then we want to go to our feedback page so we need to go to that feedback route that we created and here is our form I'm going to open up the console here too because I put a couple of console log statements in that as well so now we could just put Dave I could have Dave at davegray dot codes and then I can just say hey there and now it's ready to submit I submit and yes we got our thank you for your feedback page but we also have the object here in the page.tsx so this was logged in the front end and then we have what is received this is also in the page.tsx but it's received it's the result from the request after we get the request back so that's that Json that's sent now let's go back to vs code and we'll look at the terminal and see what we got there as well and you can see here we had the data logged as well so this is the console log message that is inside of our route here for our feedback as well so now we close this out you can see where we logged that data so that's how the post request works with the form and of course you can look in the course resources and look over that form on the front end part for react as well that is a client side page by the way because it's interactive so at the very top you need use client as any page needs to be that has that user interaction so pointing that out as well but back here in the API we created this post route now and this is also how put and delete and the other methods would work besides git so I wanted to make sure to show you both get and post remember to keep striving for Progress over Perfection and a little progress every day will go a very long way please give this video a like if it's helped you and thank you for watching and subscribing you're helping my channel grow have a great day and let's write more code together very soon
Info
Channel: Dave Gray
Views: 27,859
Rating: undefined out of 5
Keywords: next.js 13 route handlers, next.js, next.js route handlers, next.js 13, next.js routes, next.js api routes, nextjs, api routes in next.js, next.js 13 api routes, next.js api, create an api with next.js, api routes in next.js 13, route handlers in next.js, route handlers in next.js 13, route handlers vs api routes, route handler params, nextresponse, get parameters next.js, get params next.js, post parameters next.js, post params next.js, api routes, api route handlers, next js
Id: xirQ7AMyTM8
Channel Id: undefined
Length: 20min 43sec (1243 seconds)
Published: Fri Mar 31 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.