How to Fix CORS Policy Errors When Making Fetch API Requests from a Next.JS Application

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey guys John here with a quick video about an issue I ran into a little while ago that I think some of you might benefit from the issue is related to Coors which stands for cross origin resource sharing essentially this is a programming issue that rears its heads in some cases when a program is trying to fetch data from a resource in a location other than its own in other words when a script at domainx.com is trying to make a fetch request to domain y.com a course error is likely to occur this happens for security reasons it's meant to give browsers the ability to prevent scripts that aren't from a same origin to access data on a particular server unless that server allows data fetch in from that origin but that's a subject that's outside the scope of this video in this video I want to touch on a way to get around the issue of course when you have no control over the server you're making a request to to quickly show your course error at work let's go over a very basic and simple example I have a blank next JS app here and I'm going to try to make a fetch request to google.com now this video is about a way to get around the course issue in the next JS app so I'm going to assume that you're familiar enough with JavaScript and xjs so on declare URL which is going to be google.com then uh proceed with my patch API on the fetch URL let's let's put the fetch API inside an async function that way we can use async await so let's do const fetch data equal async like so and then we declare the fetch API like so then we'll turn the response object into Text data that we can use a new constant or sorry const data equals weight response dot text and then let's log the data to console so we can see the results and lastly let's run our function fetch data like so now let's run a server that's on localhost 3000 let's start a console so we can see our results known as The Local Host co-host 3000 and as you can see we have an error and it is a course error because it says that access to fetch from origin has been blocked by chorus policy what this is saying is that our origin which in this case is my local computer here at Local Host 3000. is not allowed to fetch data from google.com because Google is of course not specifically allowing my local house 3000 to access the requested resource now there are servers which don't have cores enabled where we don't run into this issue for example instead of google.com I'm gonna fetch data from a site called Json placeholder this is a site that gives users some ready-made endpoints to use for data fetching which makes it very useful for testing so if I go here to Json placeholder site and scroll down to the resources section and click here on users for instance this is the data that is returned to us when we make a request to this URL right here so I'll use this URL instead of google.com in my app to show you that this server right here does not doesn't have cores enabled so I'm going to click here same thing now this server this endpoint returns a Json so I'll just change that to Json hit save and now if we go back to the app right here and refresh we see that there's no course error and that the server returned to us the Json the same as this right here however in most cases there will be a cause problem that you'll have to deal with and let me just change this here to google.com then just text now the chorus is a browser issue and only happens when the request is made from the front end of an application which is the case here and a way to fix this is to make it so that the request is made from the back end of the application rather than the front end a way to do that is to use what index.js is known as a get static props function this is a function that runs at build time and always runs on a server on the back end of the app and never on the client the front end of the app which makes it perfect for bypassing the course issue and we can use git static props in this case because the requests we're making doesn't require input from a user beforehand in fact in this case get static props is the way to go even without the course problem because it allows for the pre-rendering of the page which makes the page both SEO friendly and fast loading I will however cover a case in this video which does require user input and in which we can't use to get static props as a remedy of course so hang tight so to use the get static props function we need to export it like so export cost get static props and this is an async function put that on there so now we can create our fetch request inside of this function now let's get rid of the fetch we have down here let's move it up inside of the get static props let's move to URL as well and now we no longer need to have the fetch API inside of this async function right here because get static props itself is async and the way it works is to pass the data to our component down here all we have to do is return a props property so like so and then we'll say props and then give that the value of an object I'm going to call it Google data but you're free to give it whichever name you'd like and then I'm gonna give that the value of data and now this props can be passed to our component down here all we have to do is come down here and then to bring in Google data like so and now we can we can do whatever we'd like with with the data that was passed to us to us from get static props but for our purposes we'll just log it to the console down here save and let's go to our app here and then refresh that and as you can see we no longer get the chorus error and instead we get dhtml behind the Google home page and if we needed to we could parse this HTML right here and make any use of it that we'd like so this worked and we were able to get around the course issue by using the get static props but what if this were a case where we couldn't use the get static props function like a case where the user had to enter some input into the app first and then the app would fetch data based on that input that is a case where we couldn't use get static props so as an example I have a Shopify custom app that I'm building using next and in it there are a couple of instances where I ran in the course and I'll go over one of them in this video so this page was made so that the user can create a draft order by simply inputting a product ID and if we look at the script for the page right here we see that the page is set up so that after the user hits the submit button right here called create in this case the get data function is triggered which is right up here right here the function takes in the form data D that passes the value of the the product ID to it which will be used in the fetch API all the variables here what controls what appears on the page and when They Don't Really factor in the course issue that we are currently addressing so we have our fetch method right here it's a post method this is the Shopify post request body for creating a draft order here we build our fetch API options we have the methods the headers headers contain the API token that's required by Shopify it is an environment variable for security reasons we have the content type application Json and then we have the post requests the body of the post request here we have the URL or the endpoint that we need for this request the shop name is also used in an environment variable it's defined up here the token is up here and now that we have all the data we need we go ahead and execute the fetch API then we turn the response into a into Json data that we can use now for our purposes we'll just console log the results that's all we're concerned with we'll just cancel this final right there so when we go ahead and run the script I'm going to put product or variant idn and hit the create button we get the dreaded course message and a crashed program as you can see access to fetch from origin has been blocked by course policy this again is happening because we're running our fetch requests from the client side or front end of our app and in this case we can't use the get static props function like before because we have to wait until the page has first rendered for the user to put in the variant ID or the product ID at which point the app will be able to create draft order for the particular product that the user chose so to get around the course problem in this case we make the request via the back end of our app in next JS we can do that by using API route API routes is everything that is in inside this folder API folder inside of pages everything inside of this folder is treated as an API endpoint and not a page these are server-side scripts only and therefore do not trigger course so all we have to do is create an API route and use it to run our fetch API so let's do that I'll create a file inside the API folder and I'll call it handle draft that Js we'll do Advanced Handler equals async give it a request and a response now I'm making this an async function so that we can use a weight on our fetch API later on now inside of here I will declare a method which will be post will need our fetch API options we can just copy those from the front end page right here we'll need to Define our app token which is an environment variable we can copy that from the front end page and we might as well copy the shop environment variable too because we're going to need it in the fetch URL and we'll copy both of these the body of the options will be the same but we'll copy it from here you can put it here foreign ID will come from the front end as we'll see in a few then our fetch uh let's do fetch URL and that is going to be the same as we used previously here in this page we'll copy that we'll put it here so now on the front end of the app we want to make a fetch request to this API route that we just created handle draft so our fetch URL in the front page will be forward slash API forward slash and then handle graft we don't need to put the dot js on there next takes care of that for us the post body objects will not only consist of the varying ID from the user input we don't really need to declare it separately we'll just include it directly in the options object we'll say variant ID and then we'll give that the value of variant ID we can get rid of the post body object right here don't need that anymore don't need a semicolon there and this pretty much should be should be in as far as the front page in the API route we'll need to extract the variant ID from the post request we'll do that by setting our variant ID equal to the request body and then the variant ID key now these can be the same can be called the same they won't conflict now we can make they request to Shopify like so constant response is a weight patch URL and the options then we'll turn the response object into Json data that we can work with wait response dot dot Json and then we'll just return the data back to the front end like so now let's let's add in a try catch statement right here will do try and then we'll catch any errors down here so we'll take these move them inside here and what we'll do is we'll return a success object with the data if no errors otherwise we will return an error object with an error message we'll save that and let's give it a try let's run the app now and see what happens so I'll put my ID in there and hit create now let me clear the console so that we can see what's going on what the results are before we do that let me just fix this right here this there needs to be a return right there okay let's not forget to export this to export default Handler like so hit save and now let's give it a try I'll put in my ID right there and hit create and unlike before we get no course error and our task was executed and that's it that's a way to get around the course issue when you don't control the resource server I hope this was helpful and I'll see you in the next one
Info
Channel: Blue Sphere
Views: 19,075
Rating: undefined out of 5
Keywords: next.js, nextjs, reactjs, react, javascript, cors
Id: o5WQn0U4SFU
Channel Id: undefined
Length: 19min 55sec (1195 seconds)
Published: Wed Dec 14 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.