简体   繁体   中英

Hiding api url in react/redux application (proxy)

I am concerned about security of my react/redux application as my api url is exposed to the public inside bundled app.js file. I've been researching this and some developers proxy it somehow ie instead of using my api url I can use api/ whenever I perform calls with libraries like axios or superagent and it gets proxied to my api url, but this way users can only see api/ on their side.

I'm trying to figure this out, I assume this is set up within express config?

You have a valid concern.

Typically you would have your clientside code make calls to, say, /api, and in express (or whatever server you use) create a route for "/api" that proxies that request to the actual api url.

This way you can obscure any sensitive information from the client. For example authentication tokens, api keys, etc.

In express you could do something like this:

app.use('/api', (req, res) => {
  const method = req.method.toLowerCase();
  const headers = req.headers;
  const url = 'your_actual_api_url';

  // Proxy request
  const proxyRequest = req.pipe(
    request({
      url
      headers,
      method,
    })
  );

  const data = [];
  proxyRequest.on('data', (chunk) => {
    data.push(chunk);
  });

  proxyRequest.on('end', () => {
    const { response } = proxyRequest;
    const buf = Buffer.concat(data).toString();
    res.status(response.statusCode).send(buf);
  });
});

This example is a bit more elaborate that is has to be, but it will probably work for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM