Cross-Origin Resource Sharing (CORS)
According to Cross-Origin Resource Sharing (CORS) MDN article:
Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources.
In a nutshell, CORS headers
instructs browsers and remote services whether they're allowed to load a
specific content or not. This check usually happens with
an OPTIONS
HTTP preflight request.
Access to font at 'https://example.com/public/fonts/my-font.priority.xxxx.woff2' from origin 'https://other.example.org' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Configuring CORS in Front-Commerce
In Front-Commerce, the content of this header can be controlled by creating a new configuration provider.
See the Adding a configuration provider guide to learn how to register it in your application.
Example Configuration
Here is an example allowing browsers to load your pages from
webcache.googleusercontent.com
and other.example.org
domains:
export default () => {
return {
name: "cors",
values: Promise.resolve({
cors: {
// This value is the one transmitted to the cors() middleware
// see https://www.npmjs.com/package/cors#configuration-options for details
origin: {
googleCache: "webcache.googleusercontent.com",
otherSite: "other.example.org",
},
},
}),
};
};
Adding the Configuration to Your Project
And add it to your front-commerce.config.ts
file:
import { defineConfig } from "@front-commerce/core/config";
import appCSPProvider from "./app/config/cspProvider";
import appCorsConfigProvider from "./app/config/appCorsConfigProvider";
export default defineConfig({
// ...
configuration: {
providers: [appCSPProvider(), appCorsConfigProvider()],
},
// ...
});
Testing Your Configuration
You can test headers returned from a specific origin by using the Origin
HTTP
header. Example:
curl -sI http://localhost:4000/ \
-H "Origin:webcache.googleusercontent.com" \
| grep -i access-control-allow-origin
It should return Access-Control-Allow-Origin: webcache.googleusercontent.com
.
If you don't see this header, it means that the CORS configuration is not
correctly set up.