Proxying requests from React to External REST API

Viewed 66

I'm working on a website made with React, run with npm. The website currently uses a JS API run with the website code, but we're migrating to using an external REST API. Everything's configured correctly to run locally with a webpack dev server:

proxy: {
    '/apiv1': 'http://localhost:5000/', // in prod, run in the same container
    '/api': {
        target: 'http://localhost:8080/', // in prod, run separately on a different url (api.website.com)
        pathRewrite: { '^/api/': '' },
    },
},

In the console, I see errors complaining that some data is undefined (using the minified variable names, so difficult to track down--but almost certainly data from the API).

I checked if it was a CORS issue per this question, but I'm still having the same issue with CORS disabled completely.

I can successfully ping the api with a direct request, placed at the beginning of the base App's render method:

axios.get("https://api.website.com/")

I've tried to add the following to my package.json per this:

"homepage": ".",
"proxy": {
    "/api": {
      "target": "https://api.website.com",
      "pathRewrite": {
        "^/api": ""
      },
      "changeOrigin": true
    }
  },

In general -- how can I proxy requests for website.com/api/request to api.website.com/request in production? Is there something else I'm configuring incorrectly?

Please let me know if there's any more information I can add!

Edit: I've also tried configuring the proxy with http-proxy-middleware:

// src/setupProxy.js
const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function (app) {
    app.use(
        '/api',
        createProxyMiddleware({
            target: "https://api.website.com",
            pathRewrite: {
                "^/api": ""
            },
            changeOrigin: true,
        })
    );
};
1 Answers

Proxying api requests in production for React/Express app

In production we can't use (proxy).. instead we can set a variable in the frontend for the backend URL, and vise versa.

https://github.com/facebook/create-react-app/issues/1087#issuecomment-262611096

proxy is just that: a development feature. It is not meant for production.

These suggest that it's entirely impossible. Makes sense that the proxy option won't work, but I can't say I understand why there's no equivalent functionality for a production environment. It seems the best option for me is making all calls to the full domain instead of proxying.

If you're using nginx, the linked answers suggest using that to proxy the requests:

upstream backend-server {
  server api.example.com;
}

server {
  listen 80;
  server_name example.com;
  root /var/www/build;
  index index.html;

  location /api/ {
    proxy_pass http://backend-server;
  }

  location / {
    try_files $uri /index.html;
  }
}
Related