I was building a microfrontend application using reactJS with two main components:
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.
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,
},
});