Mastering API Routes in Next.js: The Ultimate Guide

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
okay guys so in this video Let's see that how do we handle API routes inside the app router that is the new way of handling API routes in xjs so let's go to our next JS application so it is a very basic or like a bootstrapped Nexus application using the create next app package let me simply start the application in the background so now to Define API routes what we need to do like it's a convention to create a folder called API inside your app router and then inside here we can Define any route like if you simply want to go to forward slash API we want to get something we can define a route by creating a file here called route.psx simply like this and from inside this file we can export in a couple of functions here and that is the get post put patch and delete so let me show you in the documentation so like so we have these functions that is get post put patch and delete which we can export and like hidden options which you can export from our router TSX file so what I'll do do I'll go to my app.s route.asx file and I simply export in a function called export async async function called get and then let me come back to the params in a moment and then what we need to do we need to return something from this thing here we do not need to do it the old way that is response dot Json or something like that we need to return here next response that is coming from next server thing here so we need to return nextresponse dot Json whatever you want to send so let's say that name is like Mafia so let's save this and now to hit this API route what I need to do I need to go to either Postman or something else but what I prefer I use this extension inside vs code called rest client so it allows me to make HTTP request to my routes here so here what you need to do we created a file called rest.http and to make a get request to my API route I'll simply write a local host Port 3000 forward slash API because inside the API folder we have the route.sx file so if you simply send a request here we see that we should be getting any response back and we get back this response here that is name is Mafia so this get function and like before jumping into the parameters that are present inside is get function we can in a similar way we can export in a function called post here simply like this and we can do whatever we want to do with this API route so this would be a post route this would be a get route and in a similar way we can create like put patch and delete and hidden options route but I am simply limiting myself to get in post routes so if you go to our rest client again and if we try to make a post request to that route so let me make in a post request to this endpoint that is API so I would I would get the same thing here or maybe I have not saved in the file here so this file might not have been saved so if I make in a post request we see that we are getting back this message here that his name is Mafia so now let's talk about what is present inside this request handlers that is inside these handlers that is get and post so here we have two things we have the request object here that has the the type of this request object object is the same type as the web request API so we can pass in request here and then we have the context here and by default this context only contains the params so let me simply call it params here and let it be of any type so now this request has been extended by next team so we can use instead of this request we can simply use in next request here because it extends the default web request API to contain some more uh parameters like the cookies URL search parameters and so on and so forth so now let's say that we want to handle this post route so let me copy this piece of code and let me paste it here so let's say we want to pass in some data here to this post route or post endpoint so let me go to my restaurant risk client here and let me pass in content type would be application Json and we want to pass in some things some values here so let's say name would be passed in as uh Mafia methyl and then the age would be let's say two so we need to get these values inside our API route that is forward slash API so how do we do that because if I simply make in a request you don't see anything but if we go to a route.jsx file so we can go here and we can simply get in the request Body by doing const body equal to request dot body we cannot do so it would right away give us an error so if we simply log in console.log body Watch What Happens so if I open my terminal here and let me make a request here so let me make another request here we see that we are getting a readable Stream So to get back the Json body here what we need to do we need to Simply extract it from the request.json thing so we can say request.json and we can simply await it and then we can simply log in the body so if I save this or instead of returning name of here let me simply return back the body itself that is the incoming body so let's save this and let's go here and let's make a request here we see that this time we get back the same body that we have we have posted here so let's go back to our route.jsx route.jsx file so now let's see that how do we handle the search parameters inside the route so if we go to our rest client here and instead of only API let's say that we pass a name here to be let's say truly and let's say we pass in the age here to be let's say 25 so how do we get these values that is the URL search parameters inside our API route so it is pretty simple to do so let's go to our route.sx file and here from the request we can say const search params equal to request dot next URL and this next URL is because we have used in the next request here if we have simply used the web request API by simply using request we would not be getting this next URL here and here we can simply say dot search param params like this and let's say let's let's simply write like right away take in the name here so search for Ms dot get and we have passed in the name thing here and in the similar way we have also passed in the H here so let me simply get in the H URL search parameter and finally let me simply response back with the name and each thing here so name and each by getting it from the URL search parameters so let me save this and let me go to my us client here so let me make an up request here and actually this should be should be here like in a get request because we are handling it inside the get request so let me make a request here we see that we are getting back these values here so you do not need to send these values back to the client but I'm just showing you that how how we handle the URL search parameters here so now let's say we want to handle some kind of of a slug here so let's say we have a route here like this so so we have a route called HD or let me copy it so let me copy it oh we have a route called API forward slash blog forward slack some slug so how do we get this some slug inside our route here so typically to handle these kinds of routes what we need to do we need to create in a folder here inside the API folder called blog like this and inside this block folder we need to create in a dynamic route segment that would be slug like this and then inside this folder inside the slug folder we need to create a file called route dot TSX and inside this route.txx file we can export in a function called export async function call gate and then we have the request which would be of type of next request and then we have the prems the type would be any and then we can get in the dynamic value of the slug using these params object here so we can say const equal to params dot slug like this and for Simplicity let me also log it inside the console that is what is constrained inside the params here and finally let me simply return something that is written next response dot Json and let me simply return slug like this so now let's go to our risk line and now let me make in a request here so we see that we are getting back some slug here and if I open my terminal we see that uh all right so let me make a request again once again so let me make a request so we see that we are getting this value here called slug some Slug and this slug some slug comes from this from this thing here so from this param thing here so this is what is contained inside the params here so now if I go here res dot HTTP and if I write here comments forward slash comment ID so how do we handle this so if I make in a request here so let me make a request here we see that we are getting an error here that is the route is not found so to do this or to handle this what we need we can do inside the slug folder we can create in a new folder called comments and then inside this folder we can call in a comment ID maybe something like this that is the ID of the comment comment ID Dot and inside this comment ID what we can do we can create a new file called route dot TSX and inside this route.tsx file so let me open it here so let me minimize it so let me open it here so we can paste what is contained here so let me copy it and let me paste it so if we save this and if we try to handle this route or handle or hit this route let's see what happens so if I make it like make a request here we see that we are getting some response back and in the parameters we see that we are getting slug some Slug and comment ID is comment ID which we have passed here like the structure of this path is like relevant to this folder structure here so therefore inside the parameters we are getting the whole value of these Dynamic parameters so instead of like responding it with slug only let me response or send back the response at parameters so let me remove this so let's save this and let's try to hit this route once again so we see that we are getting both the dynamic parameters present inside our URL by using these this params object here inside this thing here so now let me go back to my index route or the forward slash index API route that is this route so now let me show you a couple of more things so let's say that we want to handle some kind of authorization headers inside our request so let's try to use this route let's keep it very simple so we want to pass this route an authorization header with a better token let's say so Bearer and some JWT token something like this so how do we get this authorization header inside our route that is this A6 file so let's go back to our route.sx file so what we can do let me comment out this stuff from here or let me delete it so what we can do we can simply say const alt header equal to request dot headers dot get and here we can simply pass an authorization and for Simplicity let me simply send back the auth header so typically you should validate this header and if the header is valid valid then you can like proceed ahead with the request otherwise you can simply response it no you can throw in an error like four or four or three or something like that so let me go to rest.http and let me simply send a request here we see that we are getting this auth header Bearer some JWT token which means that we are able to extract extract this authorization header inside our route.jsx file by doing request.headers.get now in a similar way we can also handle cookies so let's say that your front end sends in some kind of cookie so let me pass in a cookie called Foo equal to bar and we want to get this cookie with the name of Foo and value of bar inside our backend code that is inside our route so it is pretty simple to do again so we can simply say const cookie equal to request dot cookies dot get and we know that we want to get a cookie with the name of Foo so we can simply get it like this and then if we simply log in the cookie so console.log cookie uh let's simply send it back again because it is more clear so let me simply send it back so cookie or otherwise we can also log in the name that is the name of the cookie and the cookie dot value and this is an optional thing here cookie because this might fail because if you have not passed in the correct name or even if the cookie does not exist from the request so it might fail so therefore it is an optional value here so let me save this and let's go to our restaurant HTTP and let's make a request here we see that we are getting back the cookie and in the terminal we see that we are getting the whole of the cookie as well as the cookie name and the cookie value here so this is how we can handle cookies so now let's see one more thing about these API routes and that is using uh that is the revaluation of the API routes so let me simply like comment out all of this and you want to hit this index route for the API so for now let me pass in an empty object pack so let's say we want to get data from an external API which has some limitations about that about the number of requests you send to that EPA because it's a third party API so what we can do we can cash in the request and that that fetch request to that third party API would not be uh would not be triggered on each and every request on your server so let's see we have a response here so const response equal to a weight and we are using fetch here and we call this API endpoint that is the GitHub search users API endpoint so if we simply send back this response or let me get in the user here so const user equal to await response dot Json and then we simply send back in the user here or whatever data it is so if I save this and if you go back to our risk client we see that we get back this data here that is the total count which is coming from the GitHub API and we see that we are getting something in terminal so let me minimize the terminal size here so we see that we here have cache Miss but what we can do we can cache this fetch request that is that is this request so that is this request can be cached by simply passing in a parameter here called Next and here we can pass and revalidate to be 10 that is the result of the switch request would be cached by next.js so that whenever a new request comes to this get in point in our case that would be forward slash API whenever a request comes to that get in point this the cast result of this switch fetch fetch call would be used inside the response here and after 10 seconds this request would be again revalidated so if I go to my rest.http and here we see that initially we had cache Miss but watch what happens if I simply send a request again so if I send a request we see first time cache Miss but if I again send a send back we see that we are getting cash hit which means that initially there was no data for this request that is for this uh endpoint but the next time when I hit this route we are sending back the data of this fetch endpoint API endpoint and we are getting cache it here so if we send again we see that we are getting cash it so if we send again we see that we are getting cache it so this is how we can or we can like uh cache the data using the fetch fetch API using the third party apis and in a similar way if you are not using fetch then maybe I'm not sure you can you export in a constant here called revalidate equal to 10. so in that case like your API calls to your database may be also cached so guys that's all about this video and this is how easy it is to handle all the HTTP verbs inside your API routes though it is not mandatory to use API folder here you can simply create in a new folder called whatever folder here let's say that blog or let's say user and you can also create in a file here called route dot TSX and here also we can export in that function called the get function so let me copy this function from here and let me paste it here and let me remove all this stuff from here and let me simply res dot Json user equal to one two three and let me import next uh request and next response so let's save this so what we can do we can we do not need to use forward slash API always we can directly hit that user's endpoint or that user endpoint so let me show it to you so let me remove all this stuff from here and if we hit user we should be getting a backup response user one two three but now since it is not inside the API folder so you might be tempted to use a ph.tsx file here so page dot TSX simply like this and let me open it on the left side so page.tsx and here if we export in a function called uh user page simply like this so this is a server component because it is inside the page.tsx file but watch what happens if I hit this endpoint so if I when go to this end point we see that we are getting an error here and that is because we cannot have a page.tsx file and a route.tsx file at the same level inside any directory so either you are going to have the page.tsx file or otherwise you are going to have route.tsx file so therefore it is always a better idea to Simply Nest your folders inside the API folder because like you are not going to use the API endpoint for any other thing apart from the apis so guys that's all about this video so if you like the video do hit the like button and if you haven't subscribed to the channel do it the Subscribe button so thank you bye bye Tata take care and have a good day and have a great day
Info
Channel: Mafia Codes
Views: 1,888
Rating: undefined out of 5
Keywords: mafiacodes, nextjs api routes, api routes in nextjs, api routes, nextjs app router, app routing in nextjs, how to add api routes in nextjs
Id: 7HarHG4zvh8
Channel Id: undefined
Length: 20min 32sec (1232 seconds)
Published: Thu May 25 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.