You can use a service worker to intercept and manipulate all requests towards the cdn of the MFEs.
service-worer.js
let authToken = '';
// This event listeners listens to the requests towards the login
// endpoint and stores that authToken at the corresponding variable.
self.addEventListener('fetch', function (event) {
if (event.request.url === 'https://auth-endpoint/login') {
event.respondWith(
fetch(event.request)
.then(function (response) {
var responseClone = response.clone();
responseClone.json().then(function (data) {
authToken = data.token;
});
return response;
})
);
}
});
// This requests listens to the requests towards the MFEs' endpoint
// and adds the custom headers needed fot the authorization
self.addEventListener('fetch', function (event) {
if (event.request.url.startsWith('https://remotes-endpoint/')) {
let url = new URL(event.request.url);
let headers = new Headers(event.request.headers);
headers.set('Content-Type', 'application/javascript');
headers.set('Authorization', authToken);
let newRequest = new Request(url, {
method: event.request.method,
headers,
mode: 'cors',
credentials: 'same-origin',
redirect: event.request.redirect
});
event.respondWith(fetch(newRequest));
}
});
You will need to regitser your service worker at your bootstrap.js
...
if ('serviceWorker' in navigator) {
window.addEventListener('load', function () {
navigator.serviceWorker.register('/service-worker.js')
.then(function (registration) {
console.log('Service Worker registration successful with scope: ', registration.scope);
}, function (err) {
console.log('Service Worker registration failed: ', err);
});
});
}
Add CopyPlugin at your webpack configuration
const CopyPlugin = require('copy-webpack-plugin');
const config = {
...
plugins: [
...
new CopyPlugin({
patterns: [
// adjust 'service-worker.js' if your file is somewhere else
{ from: 'service-worker.js', to: '' },
],
}),
]
}
module.exports = config;
You will also most probably need to remove the remotes from your module-federation configuration, as long as the authToken doesn't exist on mount of the consumer app until the user logs in. So the requests of the remotes will fail on mount. To resolve this you will need to load your remotes using Dynamic Remote Containers. There is a full implementation of this approach in this repo.
loadRemoteModule
so inside this method you could add the token in the header. But the problem is, once the initial remoteentry.js file got downloaded with authentication. The remoteentry.js file will further download one more js file from server, that I could not handle :( – Adis