Search code examples
reactjslocal-storage

How can I use two react applications in single project


In my project I have created two different react applications let's say app1 running on http://localhost:3000 for web and login and app2 running on http://localhost:3001 for service. Now after login in app1 I want to redirect to app2(http//:localhost:3001) with access and refresh token. The back-end is Django.

I tried using localStorage and that will be different for both the applications.


Solution

  • There are different ways to do this in React applications. First of all, you have to treat them as different application since they are in different client instances. You can simply create a function like redirectToApp2WithToken and put the below code with some other modifications as you need. You have to do this in your app1 in order to redirect to your app2.

    const search = {
       token: yourToken,
       ... // All the other token related props 
    };
      
    const redirectApp2 = `http//:localhost:3001/redirect? 
    ${queryString.stringify(search, { arrayFormat: 'repeat' })}`;
    
    window.location.replace(redirectApp2);
    

    By the way, that queryString is a npm library that you can use in these types of query string related things. You can install it like this.

    import queryString from 'qs';
    

    After configuring you app1, you may have to go to app2 and create another route called /redirect. In that redirect page you have to implement a logic to validate and store that token coming from the query parameters. Then you have to redirect to the correct route like home or dashboard. Also, you can use localStorage to keep the tokens if you want. That won't be a big issue but you have to make sure you always have the refreshed token.