reactjsdeploymentvitemicro-frontendwebpack-module-federation

CORS Issues in Microfrontends deployement with Vite and Module Federation


I was building a microfrontend application using reactJS with two main components:

  1. A header application deployed on Netlify or any server
  2. A main application that consumed the header as a remote module

import path from "path";
import react from "@vitejs/plugin-react";
import { defineConfig } from "vite";
import federation from "@originjs/vite-plugin-federation";
export default defineConfig({
 plugins: [
 react(),
 federation({
 name: "MainApp",
 filename: "mainApp.js",
 remotes: {
 header: "https://headerapp.netlify.app/assets/header.js",
 },
 shared: ["react", "react-router-dom"],
 }),
 ],
 build: {
 target: "esnext",
 minify: false,
 cssCodeSplit: false,
 },
 preview: {
 port: 3003,
 },
 resolve: {
 alias: {
 "@": path.resolve(__dirname, "./src"),
 },
 },
});

This error prevented the main application from loading the remote header module, effectively breaking the microfrontend architecture.

After deploying the microfrontend repos to a live URL, Everything should be working perfectly as in the local development environment. However, we encounter this frustrating CORS error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://headerapp.netlify.app/assets/header.js. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 200.

Solution

  • All we needed to do is to add a server configuration option for disabling CORS to the main application’s vite.config.js file

    export default defineConfig({
     // … other configurations
     server: {
     cors: false,
     },
    });
    

    Here’s the complete vite.config.js file for the main application with this change:

    
    import path from "path";
    import react from "@vitejs/plugin-react";
    import { defineConfig } from "vite";
    import federation from "@originjs/vite-plugin-federation";
    export default defineConfig({
      plugins: [
        react(),
        federation({
          name: "MainApp",
          filename: "mainApp.js",
          remotes: {
            header: "https://headerapp.netlify.app/assets/header.js",
          },
          shared: ["react", "react-router-dom"],
        }),
      ],
      build: {
        target: "esnext",
        minify: false,
        cssCodeSplit: false,
      },
      preview: {
        port: 3003,
      },
      resolve: {
        alias: {
          "@": path.resolve(__dirname, "./src"),
        },
      },
      server: {
        cors: false,
      },
    });