My answer will be useful for auth like JWT with token in header.
But if you understand principe - you can implement any reuse logic and implement any auth.
I have admin panel and divide to core and several modules.
I divide admin panel on 3 parts:
- Core: auth, Vues, Router
- Module1 - Employee (one of modules)
- Module2
My auth working like JWT auth (auth header added for each request).
I write header authorization to header and pass token with each request.
So task was get this token in module, when I make any requests from module. Without this logic I get 301 and redirected because requests doesn't have header.
For this I use axios interceptor for adding header for each request (in Core)
and User class to extract token from local storage on each request (User.getToken() - also in Core module)
You can implement cross authentication with module federation like in backend microservices.
Step that I take that solved task
- Create class for auth - User for example
- Create expose in host with User class | I mean Core module (I expose class CoreModule so I don't need to expose all staff separately) and inside this class I import User class
- CoreModule has method init which call User.init() - in this method I make all initial request or get token from ls
- Import CoreModule in Module1 (EmployeeModule) and call CoreModule.init() before request - for example on mount page hook (if you use React, Vue or Angular).
- If you want optimize and initialize it only once you can expose EmployeeModule (Module1) and import CoreModule there. Than you need to call initialize of EmployeeModule.init() that would have CoreModule.init(). I expose EmployeeModule to CoreModule and initialize it right before loading page async (in my case I import all modules to core and initialize them)
How it works
When you import User and init in your core host module - it create new instance and new import of this class will return link to new created class.
But if you import this class from remoteEntry.js - will be created new instance so you need to initialize it first. It depends on you when you initilize this and does you need it.
But if you want to use the same class in several modules you need to initialize before using because webpack bundle and remoteEntry.js doesn't share created class instances.
In result you will have User class in Core and module1, shared axios with intercept that uses User.getToken() and I hope it will work in your case :)
Thank you for reading and have a good day! :)
https://codesandbox.io/s/relaxed-bhaskara-tzlrj?file=/src/EmployeesModule.js
here example