1

I need to grab from my backend a JWT token as early as possible. Where's the right place to make my API call from so that I handle this early in the life cycle of my React/Readux app?

Sam
  • 19,814
  • 35
  • 141
  • 272
  • Do you mean you need to login the user ? Because for that you can store the JWT in the localStorage. The normal way would be to do the request in the app.js where you initialise your app. – Hamza Baig Jan 06 '18 at 16:48
  • I don't think `app.js` is the earliest point. I'm using middleware in the app and as I step through the code, a lot is happening before I get to `app.js`. Some of my middleware need this `JWT Token` during their initialization process. That's why I'm trying to figure out where to handle this. It really needs to happen at the very beginning. – Sam Jan 06 '18 at 17:18

2 Answers2

0

You can add a function to your routes.js that will make an API call to get the token. Then you can call this function upon entry to your app(via react-router onEnter attribute).

This should work if you are using react-router < v4, otherwise this post can help.

...
function requireToken(){
  // Make API call to get token
};

export default(
  <Router history={browserHistory}>
    <Route path="login" component={LoginPage} />
    <Route path="/" component={App} onEnter={requireToken}>
      <Route path="/dashboard" component={Dashboard} />
      ...
    </Route>
  </Router>
)
grizzthedj
  • 5,879
  • 14
  • 37
  • 53
  • What about in `configureStore()` function which I think gets executed even before the `routes`? I tried it and it works. Just want to see if that's a bad place to do it. I don't think it will have harmful effects but not sure if the code would be elegant. – Sam Jan 07 '18 at 04:09
0

I have the feeling that there is something slightly wrong in how you approach react and redux. Your app should render just fine even without the token. If you have as you say a store (or maybe a reducer) depending on that token this is not ok. I’ll suggest to rethink the bootstrapping and make it so it doesn’t require external data. This will improve the UX, and the developer experience because will let you think in one-direction.

Krasimir
  • 12,605
  • 3
  • 34
  • 52
  • The token is not necessary for the app or the store. The whole app requires users to be authenticated. Therefore, when the user requests data from the backend API through the app, I need to know who the user is and that he’s authorized to request the data he’s requesting. The purpose of putting it in configureStore is to handle the token as early as possible. – Sam Jan 07 '18 at 07:21
  • It is clear why you need the token but why not render first and then trigger the logic for checking if the user is authenticated. You may even provide a loading screen or something. How’s your login screen rendered. – Krasimir Jan 07 '18 at 07:25
  • The login is not handled by my React client. – Sam Jan 07 '18 at 18:07