Setup an API Proxy in Create React App

Andy Van Slaars
InstructorAndy Van Slaars

Share this video with your friends

Send Tweet
Published 2 years ago
Updated a year ago

For development, we'll be using a separate server address to reach our REST endpoints. In a production build, this will likely be a different address, and in many cases, our UI will be served from the same domain as our services. We can keep our code clean and still prepare for the differences between dev and prod, by using an API proxy and a relative path to our REST endpoints. In this lesson, we'll configure a proxy for create-react-app and refactor our code to use a relative API path.

Instructor: [0:00] For development purposes, we're using this GUID server for our API. Odds are if we built this and tried to put it in production, our API calls would be made against the same domain that our UI is served from. Let's set up a proxy so we can use relative URLs in our code, and nothing has to change between a dead build and a production build.

[0:17] I'm going to start by grabbing the base of this URL, so up to the end, to the .me. I'm going to cut it from here. I'm going to make this a relative URL. I'll save that.

[0:29] At this point, this should break our API call because that relative URL doesn't exist. We're not going to get anything back here, and if we look at the DevTools, we'll see that we're getting an error, because we're getting back HTML file for our API call because the webpack-dev-server is just going to serve back our index file when it doesn't know where to go.

[0:51] Let's come back over here. In my files, I'm going to find my package.json. In the root of my package.json, we'll come down here to the bottom. I'm going to add in a proxy key because is this JSON that needs to be quoted. My proxy value is going to be that URL from Glitch.

[1:13] I'll save this. Then in the terminal, I'm going to stop the application. I'm going to have to start it again. I want to make sure it picks up that proxy setting.

[1:26] When it rebuilds, we'll see that it successfully made our API call and everything's rendering as expected.