originjs / vite-plugin-federation

Module Federation for vite & rollup

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Enable CORS by including credentials when fetching Remotes on other Domains

pganster opened this issue · comments

Is your feature request related to a problem? Please describe.

Currently, it is impossible to fetch a remoteEntry.js from a remote that is hosted on a different authenticated domain than the host as the Cookie of the different domain is not included.

Generally in Javascript, one can use the credentials: 'include' option, to fetch a file from a different authenticated domain via the Fetch API, see here. Similarly, a script from another authenticated domain can be included, by setting crossorigin="use-credentials" to a <script /> tag, see here.

Describe the solution you'd like

I'd love to see a property added to Remote that enables that script to be fetched from a different domain with credentials. For example

federation({
      name: 'my-app',
      remotes: {
        'remote-app': {
          external: 'https://my-remote-host.test/remoteEntry.js',
          credentials: 'include' // or cors: true ?
        },
      }
// (...)
)

Describe alternatives you've considered

As soon as you include a <script /> tag with crossorigin="use-credentials" in the <head />, all subsequent imports will also include the credentials when fetching that script, no matter if they have crossorigin set or not.

By building upon this behavior, we've built the following workaround, which includes a script tag, and afterwards resolves the promise, so that the federation plugin can do it's work by importing the URL, where that request in turn will then include the credentials.

federation({
      name: 'my-app',
      remotes: {
        'remote-app': {
          external: `new Promise(${loadRemoteEntry.toString()})`,
          externalType: 'promise',
        },
     }
// (...)
);

function loadRemoteEntry(resolve: (url: string) => void) {
  const url = 'https://my-remote-host.test/remoteEntry.js';
  const script = document.createElement('script')
  const onFinish = () => {
    resolve(url);
    document.head.removeChild(script);
  }
  script.src = url;
  script.type = 'module';
  script.crossOrigin = 'use-credentials';
  script.onload = onFinish;
  script.onerror = onFinish;
  document.head.appendChild(script);
}

But of course, this should be the job of the federation plugin, so I'm hoping a feature like this will be included.

use the below server configuration in vite. Run the app in preview mode to get the remoteEntry file generated for testing in local
server:{
port: 5174,
cors: {
origin: "*",
methods: ["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"],
allowedHeaders: ["X-Requested-With", "content-type", "Authorization"],

},

},