I stumbled upon a CORS error while trying to fetch a font from Google.
I currently have an express.js server serving html files for puppeteer bots. I need to authenticate users sending requests to this server by using a custom header field. However, when the html file fetches a font from Google, it uses that custom header and the request fails with the following error:
Access to font at 'http://fonts.gstatic.com/s/allura/v18/9oRPNYsQpS4zjuA_iwgW.woff2' from origin 'http://localhost:5000' has been blocked by CORS policy: Request header field test-token is not allowed by Access-Control-Allow-Headers in preflight response.
I replicated the issue in a much smaller script below:
const puppeteer = require('puppeteer');
const express = require('express');
const app = express();
//middleware
app.use((req,res,next)=>{
//verify token
if(req.header("test-token") === "foobarbaz") return next();
})
app.use(express.static("public"));
app.listen(5000);
(async()=>{
const browser = await puppeteer.launch({
ignoreHTTPSErrors:true,
headless:true,
});
const page = await browser.newPage();
//for debug purposes
page.on("console",console.log);
page.setExtraHTTPHeaders({
"test-token":"foobarbaz"
})
await page.goto("http://localhost:5000/index.html");
const content = await page.content();
console.log(content);
})()
My sample HTML file with web fonts loaded:
<html>
<head>
<link rel="preconnect" href="//fonts.googleapis.com">
<link rel="preconnect" href="//fonts.gstatic.com" crossorigin>
<link href="//fonts.googleapis.com/css2?family=Allura&family=Bebas+Neue&family=Bree+Serif&family=Twinkle+Star&display=swap" rel="stylesheet">
<style>
body{
font-family: 'Allura', cursive;
}
</style>
</head>
<body>
Hello world
</body>
</html>
I tried somehow removing the custom header on express.js request but with no luck, like this:
app.use((req,res,next)=>{
//verify token
if(req.header("test-token") === "foobarbaz"){
res.removeHeader("text-token");
next();
}
})
How do I authenticate users on this custom header but then remove it from further requests that html might do (in this case, to load external webfonts)?
Instead of page.setExtraHTTPHeaders, consider using page.setRequestInterception in order to set the extra header only for requests to your server, not to Google servers.