0% found this document useful (0 votes)
41 views12 pages

03.03. React How To Proxy To Backend Server - Bhargav Bachina - Medium

Uploaded by

Kevin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
41 views12 pages

03.03. React How To Proxy To Backend Server - Bhargav Bachina - Medium

Uploaded by

Kevin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 12
9722122, 11:19AM React —How To Proxy To Backend Server | by Bhargav Bachina | Bachina Labs | Medium Published in Bachina Labs Bhargav Bachina Jun 14,2020 - 6 min read + O Listen j Save React — How To Proxy To Backend Server Explaining how to configure a proxy for backend API calls with an example. Photo by Patrick Fore on Unsplash ‘There are so many ways we can develop and deploy React application. Mostly we are deploying React applications in serverless mode nowadays. We can store all the react assets or build in the $3 bucket for the static web hosting and call the API calls with CORS enabled. You can even use Azure static web app service to host the React application with Azure functions as a backend service. Whatever the deployment method we use we have to use proxy in the development environment. We often talk to backend servers in the development phase © What is proxying © es | Qe nitossImecium com/ob-utorials-anc-thoughtsreact-how-to-proxy-to-backend-server-55883900347 a3 9722122, 11:19AM ‘React — How To Prony To Backend Server| by Bhargav Bachina | Bachina Labs | Medium «Example Project + Proxy Setup with Create React App + Manual Proxy Setup + How To Proxy to Multiple APIs + Rewrite the Path URL ‘* Multiple app entries to one API endpoint + Summary * Conclusion What is proxying In general, A proxy or proxy server serves as a gateway between your app and the internet. It’s an intermediate server between client and servers by forwarding client requests to resources. In React, we often use this proxying in the development environment. React uses a create- react-app (webpack dev server) to serve the app in development mode. If we look at the following diagram, app Ul is running on port 3000, and the backend server is running on port 3080. All the calls start with /api will be redirected to the backend server and rest all fall back to the same port. In subsequent sections, we will see how we can accomplish this and other options as well. React Running on NodeJS Running on port 3000 port 3080 oreo) s Jail Meo lt | proxying all URLs start with /api -ntps:fmedium,comfob-tutorials-and-thoughts/reac-how-t-proxy-to-backend-server-5$880900347 23 9722/22, 1:13 AM React —How To Prony To Backend Server | by Bhargav Bachina | Bachina Labs | Medium Example Project Here is an example project with the Github link you can clone it and try it on your machine. // clone the project git clone https://github, com/bbachi /react-proxy-example.git // Run the API cd api pm install apm run dev // Run the React Ur cd todo-app npm install apm start Once you install all the dependencies, you can start both React app and node js server on 3000 and 3080 respectively. You can start the React app with these commands np start or react-scripts start and here is the React app running on 3000. React With NodeJS Create User FitNare Last Nome Fin Nae ast Hane nat React Ul running on port 3000 Let's start the server with this command apx run dev and test this API on port 3080. -ntps:fmedium,comfob-tutorials-and-thoughts/reac-how-t-proxy-to-backend-server-5$880900347 33 9722022, 11:19 AM < ca API Running on the port 3080 API running on port 3080 Proxy Setup with Create React App Setting up proxying into the backend server with Create React App is straight forward and easy. To tell the development server to proxy any unknown requests to your API server in development, add a oroxy field to your package.json Here is the package,json of the React App. Notice the line number 21. "proxy": “http: //Localhost: dependencies": { "gresting-Library/Jest-don’ Resting-Iibrary/react": "9.5. ‘avesting-library/user-event’ "bootstrap": "4.5.0", "react-bootstrap": "1.0.1", speact-dom": "936.23.2", react-seripts": "3.4.1 » scripts": start": “react-seripts start", buile": “react-seripts buile", test": “react-seripts test”, eject": "react-seripts eject" » proxy": “http://lecalhost:3080", » packagejson hosted with @ by GitHub -ntips:tmedium, comvob-tutarials-and-thoughtsireac-how-to-proxy-to-backend-server-55880900347 React — How To Proxy To Backend Server| by Bhargav Bachina | Bachina Labs | Medium ans. 9722022, 11:13AM ‘React — How To Prony To Backend Server| by Bhargav Bachina | Bachina Labs | Medium package,json With that setup, all the API calls from the React UI should work as below. eo * 00 oem) Create User 3 Users Sc If you change the port in the proxy value in the package.json proxying calls to the API will not work, Create React App will throw the error as below. Proxy error: Could not proxy request /api/user from locathost:3000 to http: //lecalhost:3090. See https: //node}s.org/apierrors.html#errors_conmon_system_errors for nore infornation (ECOWIRETUSED). Proxy error: Could not proxy request /api/user tron Locathost:3@00 to http: //Locathost:3090, See https: //node}s.org/api/errors.ntmlgerrors_conmon_system_errors for nore infornation (ECOWIRE*USED). Not able to proxy Manual Proxy Setup Sometimes this simple proxy setup is not flexible enough for you. For that, we have to do the manual setup. We need to install nttp-proxy-middieware in the React UI. npm install http-proxy-middleware —-save We need to add this file called setupProxy,js under the src folder of the React App. You do not need to import this file anywhere. It is automatically registered when you start the -ntps:fmedium,comfob-tutorials-and-thoughts/reac-how-t-proxy-to-backend-server-5$880900347 513 9722122, 11:19AM React — How To Proxy To Backend Server| by Bhargav Bachina | Bachina Labs | Medium development server. 1 const { ereateProxyitiddleware } = reauire( http-proxy-siddlenare'); 2 3 module.exports = function(app) ¢ 4 appruse 5 rapt, 6 createProxyiddleware({ 7 ‘argets *hetps//localhost:3080", 8 changeorigin: true, ne) » 5 no setupProxyjs hosted with @ by GitHub httpProxyis How To Proxy to Multiple APIs We have seen how we can proxy into one API from your React UL. This is not the case most of the time. Your React app might need to call multiple APIs to get the data. Let's see how we can do that. For example, if you look at the below diagram the Reac Ul is calling two APIs: api and api2. All the calls that start with /api should be redirected to User API and all the calls that start with the /api2 should be redirected to User API2. -ntips:tmedium, comvob-tutarials-and-thoughtsireac-how-to-proxy-to-backend-server-55880900347 63 9722122, 11:19AM React — How To Proxy To Backend Server| by Bhargav Bachina | Bachina Labs | Medium — React App /api Proxy proxy for multiple APIs We can implement this scenario with the setupProxy.js. I have added one more API with the context path api2 and we need to add one more middleware entry as shown in the setupProxy,js file. . 1) package.json u () package-lock,json J5_serye u v api2 {) package-lock.json +S serverjs is ~ my-app > node_modules another api called api2 added 2 const { createProxyitiddleware } = require(‘http-proxy-nicdleware’ ); rmodule.exports ~ funetion(app) ( 4 app.use( s “raps, 6 createProxyhiddleware({ 7 arget: ‘http://localhost:3@80", /tips:tmedium,comvob-tutorials-and-thoughtsireact-how-to-proxy-to-backend-server-55880900347 m3 9722122, 11:19 AM a ° 2 n 2 2 u y 8 oH » ‘React — How To Prony To Backend Server| by Bhargav Bachina | Bachina Labs | Medium cchangeOrigin: true, app.use( % h “M api’, createProxyhiddleware({ » ‘target ‘*hetp://localhost:3070", cchangeOrigin: true, setupProxys hosted with @ by GitHub In the api2 API we have the same functionality but running on a different port 3070. Here is Multiple Entries the server.js file from api2. 18 n 2 2 Fa 6 const express = require( express"); const path = require(*path')s const app = express(), bodyParser = require(*body-parser"); port = 3070; /] place holder for the data const users = Ef ‘FirstName: "from APE v2", lastNare: ‘email: n “from RPL va “From APT v2", app.use(bodyParser.json())s app.use(express. static(path. join(_dienane, *../ay-app/buile"))); app.gev(*/apiz/users', (req, res) => { console, log(*api/users called!") res.json(users); Ds ‘app.post(’/apiasuser", (req, res) => £ Ds users. push(user)s "eq. body.users console. log("Adding user: 2 user); res.json(*user addedd"); app. ae Ds “14 (reayres) 4 res.send("chI>APr Running on the port ${port}")s -ntps:fmedium,comfob-tutorials-and-thoughts/reac-how-to-proxy-to-backend-server-5$880900347 ans 9722122, 11:19AM 33 app.listen(port, () => React — How To Proxy To Backend Server| by Bhargav Bachina | Bachina Labs | Medium 4 console. log("Server listening on the port: :${port}'); 3 Os serverjs hosted with @ by GitHub serveris Let’s test these two APIs from the React application. © bcanos:soogepizuses P< sttane: "adfedé*, Kiestiamo: ‘odiede setupProxyjs in action Rewrite the Path URL Whenever there is a change in the URLs, we often rewrite the path of the backend server endpoints. We can do that with the pathaewrite Let’s understand the pathRewrite option. For instance, our backend URL /api/settings is changed to /api/app/ssttings and we want to test in development before it goes to production. We can achieve this with the option pathRewrite like below. /tips:tmedium,comvob-tutarials-and-thoughtsireact-how-t-proxy-to-backend-server-55880900347 ons 9722122, 11:19AM const { createProxytiddleware } = require(*http-proxy-middleware'); Imodule.exports = funetion(app) { app.use( “paps createProxytiddleware({ ‘target: ‘hetp://localhost:3080", ‘changeOrigin: true, pathRewrite: { “*yapi/settings': '/api/app/settings” » % setupProxyjs hosted with @ by GitHub proxySetupjs Multiple app entries to one API endpoint Sometimes we have multiple modules with services in our app. We might have a scenario where multiple entries or services will call the same API endpoint. React — How To Proxy To Backend Server| by Bhargav Bachina | Bachina Labs | Medium For example, we have two paths that are needed to be redirected to the same endpoint. This is possible with the following setup. const { createProxyMiddleware } = racuire(‘http-proxy-niddleware"); module.exports = function(app) ( app-use( [yapit"/api2"), createProxyiiddleware({ target: ‘http://localhost:3280", changeOrigin: true, pathRewrite: { *afapi2": “/api', // rewrite path » » dB h setupProxys hosted with @ by GitHub setupProxyjs -ntips:tmedium, comvob-tutarials-and-thoughtsireac-how-to-proxy-to-backend-server-55880900347 s0n3 9722122, 11:19AM React — How To Proxy To Backend Server| by Bhargav Bachina | Bachina Labs | Medium Now if you hit both URLs in the browser http://localhost:3000/api/users and http://localhost:3000/api2/users both will be redirected to the same API. fe « . > 6 | Gea : “a Htewtaane: “udlude", semtaane: 0" Firstnone: tate", ntts ebet gna coe fonakae “abotgeal cos” Multiple app entries to one API endpoint Summary + In React, the create-react-app proxy is used mostly in the development environment to facilitate the communication between server and UI. * We need to have a backend server and UI running on different ports. + The proxy entry should be added to the package,json file that is redirected to API calls based on the URL. + We need to make sure the React App and Backends are running on different ports for successful communication. « Ifthe normal proxy is not flexible enough for you, you can customize it with the setupProxy,js file under the src folder of the React UI. -ntips:tmedium, comvob-tutarials-and-thoughtsireac-how-to-proxy-to-backend-server-55880900347 wns 9722122, 11:19AM React —How To Proxy To Backend Server | by Bhargav Bachina | Bachina Labs | Medium ‘We need to install http-proxy-middleware for the customized setup. We can rewrite the path with the option pathRew ite. We can proxy multiple entries to one backend API with it as well We can proxy multiple entries to multiple backends as well with multiple entries in the middleware. Conclusion This is a really good feature for the development phase. If you are working on the React application this feature really speeds up your development. Sign up for BB Tutorials & Thoughts By Bachina Labs Tutorials Ranging from Beginner guides to advanced on Frontend, Backend, Blockchain, Docker, kB, DevOps, Cloud Al, ML. Thank you for subscribing and let me knowf you want me cover anything? Take a look, & Getthis newsletter Ci About Helo Terms Pri eeu reeset fee nitossImecium com/ob-utorials-anc-thoughtsreact-how-to-proxy-to-backend-server-55883900347 23

You might also like