Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 i.e. 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?

like image 423
Ilja Avatar asked Jun 22 '16 12:06

Ilja


1 Answers

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.

like image 132
0xRm Avatar answered Oct 30 '22 23:10

0xRm