I recently got a local XM Cloud instance running and started to configure the site. The kind front end architect had everything in the src solution arranged very nicely and all was working well in Storybook. After getting the first rendering completed and wanting to view it in Experience Editor, I discovered that the fonts were being blocked by a CORS issue. Here is the scenario.
In this folder, we have the global.scss file: src\sxastarter\src\styles\global.scss
The global.scss file imports the fonts file: @import ‘fonts’;
The fonts file is located here: src\sxastarter\src\styles\_fonts.scss
The font declarations:
The fonts live in this folder: src\sxastarter\src\assets\fonts
The XM Cloud Rendering Host
If you use the SXA Starter Kit for XM Cloud, out of the box, the hostnames will be as follows:
- CM Server: xmcloudcm.localhost
- Rendering Host: www.sxastarter.localhost
After the next build complete, and you view your pages in the Experience Editor, we were receiving the CORS Error. We knew it was cors by inspecting the network tab: fonts selection to see why they weren’t loading.
The Solve
To solve this issue, we added a cors.js next-config plugin.
- Go to this path: src\sxastarter\src\lib\next-config\plugins
- Create a new file called “cors.js”
- In that file, use this code below:
- In the “source” line, we are saying anything that has a path of “/_next/*, set the header to allow cross origin access, where the key “Access-Control-Allow-Origin” is set to “*”. This can be more restrictive if you like.
- Restart your rendering host in Docker to make this take affect. Your CM might not work after this restart, so you might need to restart the CM in Docker as well.
/**
* @param {import('next').NextConfig} nextConfig
*/
const cors = (nextConfig = {}) => {
return Object.assign({}, nextConfig, {
async headers() {
return [
{
// matching all API routes
source: "/_next/:path*",
headers: [
{ key: "Access-Control-Allow-Credentials", value: "true" },
{ key: "Access-Control-Allow-Origin", value: "*" }, // replace this your actual origin
{ key: "Access-Control-Allow-Methods", value: "GET,DELETE,PATCH,POST,PUT" },
{ key: "Access-Control-Allow-Headers", value: "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version" },
]
}
]
}
});
};
module.exports = cors;
Happy Xmclouding!