CORS issue when using Google Fonts
brandoncc opened this issue · comments
Here is my configuration:
WebFont.load({
active: function() {
const event = document.createEvent('Event');
event.initEvent('fonts-loaded', true, true);
document.dispatchEvent(event);
},
typekit: {
id: 'abc123'
},
google: {
families: ['Assistant:400,600,700', 'Sorts Mill Goudy:300,700:ital']
},
custom: {
families: ['Impact']
}
});
Unfortunately, I have a CORS error from the Google Fonts:
Access to XMLHttpRequest at 'https://fonts.googleapis.com/css?family=Assistant:400,600,700%7CSorts+Mill+Goudy:300,700&subset=ital' (redirected from 'http://fonts.googleapis.com/css?family=Assistant:400,600,700%7CSorts+Mill+Goudy:300,700&subset=ital') from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
This has been an issue for a very long time, and I'm hoping there is a solution. I opened this SO question a year ago.
My current machine is Brave on MacOS Big Sur.
Hey @brandoncc,
To me it looks like Light (300) and Bold (700) does not exist for Sorts Mill Goudy
It should just be:
google: {
families: ['Assistant:400,600,700', 'Sorts Mill Goudy:ital']
},
I had a slightly different problem (using this library in a WebView on a iOS device), but for me it worked to add these resources in the head of the html file:
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
To add some important context: This is definitely not a CORS issue. This happens when you use webfontloader to request a Google Font with a list of weights and a style, like italic/bold. For example, "Roboto:300,400,500:italic"
.
When this happens, Webfontloader has a bug that adds the style as a "subset", see the code here for context. So in this case, it would request Roboto with the subset "italic".
According to Google Fonts API documentation, the subset
field is meant for a character set like Latin or Greek, not a style of a font family. Google Fonts API doesn't accept a value like "italic" or "bold" for subset
, but instead of giving you a 406 code or some error message, it tells you that there's a CORS issue. That's a bug on their end.
The simple fix is to not include weights if you're requesting a style, as in Joemidi's answer.
But if you want both (a non-standard weight and a different style, e.g. Roboto 300 italic) then you can't use Webfontloader to do that. This workaround is fine for me, so I won't add a PR to fix the underlying bug, but I thought it was worth explaining.