Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React with Express Private Routes

I've mainly been using server-side rendering solutions to pass data from the server to the client and render that in the browser.

Some major benefits to this include being able to get data and pass it to the client without exposing a route that is public. So being able to keep that data hidden and only expose it when I want. I know other applications such as Facebook have data that is able to be received ONLY by their applications (iOS, Android, web applications) for example timeline data is not a public route and is only able to be received by their own applications.

How can I achieve something like this using React? With server-side rendering I can lock down those functions/routes and only allow them to be called from the backend code and not expose them, I can also do things like check to make sure the user is logged in and such.

How can I achieve this with React?

like image 441
Charlie Fish Avatar asked Sep 16 '17 17:09

Charlie Fish


1 Answers

As I understand it, you want to restrict certain routes to logged in users.

For logging in with an identity provider like Facebook, the goto is passport.js. A question about using react/express/passport has been asked before on SO, eg here.

Edits in response to comments:

So, you have some functions that output data. If you render server side, those functions aren't exposed. But, if you expose them via an API... They are exposed. And since the JavaScript code gets sent to the client, you can't just put a secret in a header, because you have to send that secret to the client.

What I was saying above is, if you restrict those APIs to logged in users, then the problem is solved by OAuth and/or JWTs, a la this. JWTs coukd also work for you without login.

However, if what you want to do is leave the API open to requests from your app, whether or not the user is logged in, I don't know any perfect solution, just some tricks:

  • Use HTTPS
  • Set CORS policies to only allow your domain(s)
  • Use a package like Helmet

Another thing worth checking out that I haven't used, but looks good is Microgateway

like image 116
Sam H. Avatar answered Oct 21 '22 12:10

Sam H.