NextJS 13 API Routes: Better Than Expected!

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
listen when they introduced the new API rods in nexjs 13.2 I didn't like him I was like why did they do it this is totally unnecessary the syntax is different how the hell do I get access to the request body content how are they better why'd they do it right in this video we're going to take a look at the new API World handlers in the app directory how are they better and what changed let's get a really good understanding for the new API World handlers how they work and how they compare to the old ones because there are some differences and I think the new ones are doing some stuff way better than the old ones ever could first off the API routes that you know from Nexus 12 have been replaced with new API route handlers as Nexus 13.2 calls them essentially these are only available in the app directory if you opt in to use that which is not recommended for production yet however you totally can use that in that directory the way you initialize a new API Rod is by going into the API folder you can see here on the left hand side and then creating a new folder of what the API path should be called right so this would be slash API slash hello and then the route.ts is just for declaring the routes and does not count towards the API path so that wouldn't be slash route right it would just be slash API hello and then for each HTTP method we can export a function that has the corresponding name right so if we wanted to make a get request we would export a function called get if we wanted to make a post request and write the code to handle that post request for this API rotender the way we do that is by initializing a function that is called post and then any post request we make the slash API slash hello would be handled by that post request now there are some differences between these API routes between the old ones and the new ones syntactically but also in the Paradigm that you used to use them so what I want to show you is a little comparison first off of how the old ones compare to the new ones I think that makes a lot of sense so let's go into the app directory create a new folder called pages and inside of here we are going to create a new folder called API and that should go into source and not app so we have the app and the Pages directory at the same level and then the old way you used to declare an API route was under Pages slash API and then you would create a file with whatever the API Rod would actually be called so for example let's call this example Dot dot TS and then in here you'd declare the API Rod by saying const example or you usually just call this Handler the naming really doesn't matter it's going to be a function and we export that function as a default that's our API Handler right here and from next.js we get two parameters passed into this API road which is going to be the request of type next API request if you're working in typescript that's the types of your JavaScript you could just leave this whole thing out and then the response of type next API response and syntactically the new ones are way cleaner and let me show you why for example um the the only thing I think was easier in the old API roles was getting the body content in case of a for example post or patch request right you could just say cons body is equal to rectal body and we'd also want to import this type of course also from next and this is the way we get the body it's super simple right just rec.body and then we can access the body so for example let's just send back a rest dot status of 200 dot end and try making a request to the example API route I've already prepared a button to do that that makes a request to slash API and then do slash example let's make a post request so we get access to the body then as the request body we're going to send along a Json Dot stringify off let's just put an object in here saying hello and of type world right so let's start up the dev server and make a request to the old API wrote example.ts that we have just declared and also we want to log out the body just to see how we get access to that because that fundamentally changed in the new API rods there's a big difference in how we get access to the body content let's make a call and look into our console as to what happened and we can see the body content right here so all we need to do rack.body super simple if we try to do the same thing in the new API Rod let's have this side by side this on the left one is the new one on the right one is the old API rods let's make a post request to this route as well and then get access to the body content so we can say Khan's body is going to be equal to and we get access to the request object as well which is of type request by the way we don't need to import that type it's already built in it's a native browser API that's why we don't need to import it and then we can say rack.body right so just the exact same thing as with the old API route cones body is rect.body then let's log out the body and send back a new response I'm gonna get into the syntax differences here in the response in a second that just says okay and maybe you can guess what's about to happen maybe you can't let's change the button to the hello road so to the new API Rod this one right here and make the call again and now let's take a look at the body content oh what's that Josh you might ask the body is of type readable stream locked false State readable supports biop false that's super weird what the hell is that we don't want that right so the the way we access the body content has changed just a bit instead of doing rack.body we can do rec.json right and then convert that so when we make the call again let's see what happens okay and we still need to await that I was wondering why that happened we need to await the Json conversion because that's an asynchronous operation let's make the call again and now let's look into the console and as we can see the hello world object is right there so that's how we access the body content it's a bit different we need to await the rest or Json and then also you might have noticed that the way we send back responses has fundamentally changed in the new API rods here on the left side we just return a new response class and pass that a message and we can also if we wanted to pass it something like a status headers or a status text whereas with the old API rods we will do a rest dot status and then normally we'd have a DOT Json and in here we could pass whatever we wanted well if we wanted to send Json from the new API rods we would do that like this we could just do json.stringify and then send back an object of hello world just like we're requesting on the front end right so that's the syntax difference in the response right here and one thing that is way better in the new API rods is how we access the cookies and the headers it is way better so let's take a look at how we do that in the old Handler if you wanted to access the cookies we could say rack dot cookies right let's log them out console log rec.cookies in the old API route and let's make a request to the alt API rod with or button right let's make the call and now the cookies will be logged out to the console okay so we didn't pass any cookies to change that let's just create a cookie and then send that along the way we can do that is by going into the application tab under the dev tools and then let's cross just create a new cookie with a value of my cookie all right and then that will be sent Along on every request let's make the call again see what happens and now we can see the cookie my cookie but there's no easy way to access the cookies right so we could do something like that cookies and then dots and then cookie I guess if you're working in typescript that's not really cool right you you don't know if it exists and I think syntactically the new approach is cleaner so if we take a look at how we can access the cookie in the new API Rod that is rack dot cookie oh and by the way before we do that we can change the request to a next request that is what next slash server gives us as an extended type so we can easier handle this request so now we can say rec.cookies and then dot get and then here we can enter our cookie value so let's see what we call that we call it um just cookie so we could say rec.cookies.thead cookie and log that out right here so now let's make a request to the new API wrote Under slash hello let's enter it here go to our button make the request go back look into the console and it's undefined oh that's because I called it cookies and not cookie there we go let's make the call again look into our console now here we are name cookie value my cookie as you can see there's a name and the value property as compared to what we had in the old API world with just cookie my cookie I think the syntax is cleaner so for example we could access the name we could access the value in a types of way I think that makes a lot of sense and same goes for the headers right so there are multiple approaches to get the header I'm just going to show you the easiest one so we can just say in the same fashion as you got the cookies we can say rec.headers dot get and then just enter the name of the header for example the authorization header if that's what we wanted and then we could access the value or the name or whatever value um whatever header you want to access so I think syntactically this is pretty clean that's a big upgrade from the last API routes from the old ones what they have made super convenient in the new API Rod is redirecting the request so what we could do is if somebody made a let's get rid of a post for now let's just have the get request in here and if somebody made a get request to this API Rod we could redirect that request to anywhere we want and the way we do that is super simple we can do redirect import that from next slash navigation and literally just enter the URL that we want to redirect to for example this URL doesn't exist.com let's save that and next.js already knows because this is called unconditionally it will always happen it's kind of like a return right so this is unreachable code because we are returning with it redirect so let's make a request to our API route and verify that this redirect actually works so let's make a request so that API wrote a get request we can just use Curl for that to make a simple request and we are going to make a request to http localhost 3000 slash API slash hello or new API route let's press enter and what we expect to happen is to get back a 404 because we we are redirecting to some random URL and that's exactly what we get Curl 404 this page could not be found great so whereas if we redirect to a domain that exists that we know exists for example localhost 3000 that will definitely exist because we are literally hosting that in the background we can make another call request and this time we will get back a 200 response state is called 200 okay because that API Rod exists so by doing that we verified that the redirect works as we expected now one last example I want to cover is streaming if you wanted to do streaming in the old Nexus you would have to do the um The Edge runtime all right you would have to switch to the edge runtime meaning the syntax actually changed if you use the edge runtime by doing export const config is gonna be equal to an object and Export the runtime as expiry mental Dash Edge that means you opted in to the experimental Edge runtime meaning the way you send back responses also changed to the new syntax of the API rods instead of what we had previously and that allows you to do something called streaming a response and that has been streamlined no pun intended in the new API rods as well so I want to cover one example that they did in their documentation here where you create an iterator to stream function and then kind of mock a streamed response one example where that can come in handy for example would be an open AI API you can opt into streaming where you get back the chat gbt responses as you have the request open to the back end so let's copy that example in here we are creating an iterator to stream a timeout sleep that needs to be a number and then making a new text encoder and this essentially mocks the streaming right so we can get rid of the uh the old get request that we had save that and know what this code will do is it will mock a streaming response meaning every 200 milliseconds we are pretending to get back some HTML from a server um that we get back like this we're mocking a little delay and then we are putting that right here into the iterator that iterator can then be turned into a stream in the next line right here that we then send back to the client meaning we get back the response on the client as the server gets it meaning we get it in real time in the client if we put that in state and then display it right here the client would see something every 200 milliseconds instead of having to wait all the time for the entire API Rod answer to finish and then displaying it all at once making for a better user experience so I found that really cool the new syntax make that super simple and you can also switch between the runtimes in the new API rods if you're wondering how to do that you can export a const runtime and either that is node.js by default or you can also opt into something called Xperia mental Edge what I've just mentioned if that's what you want to do meaning your API rods will be closer to your end users with the trade-off being that you don't have access to all the apis there are because it's a different runtime right you don't have access to some apis that you have access to in the node.js environment and that's it that's the new API rods I like them honestly I didn't expect much of them at first I was really confused as to how to get access to the body content but now I actually enjoy working with them so that's going to be it for me thank you very much for watching and I wish you a lot of fun working with the new API routes if you build something cool let me know I'll see in the next one have a good one and bye bye
Info
Channel: Josh tried coding
Views: 69,711
Rating: undefined out of 5
Keywords: next js, next.js, next js tutorial, next js 13, next js typescript, nextjs, next.js 13, next 13, typescript, api, nextjs typescript, next.js tutorial, nextjs react, next js api, route handlers, route handler, next.js 13 tutorial, next js 13 tutorial, next js 13 api routes, next js 13 api
Id: vrR4MlB7nBI
Channel Id: undefined
Length: 15min 5sec (905 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.