CORS - Configure hugo server to include Access-Control-Allow-Origin

I have a site I’m testing locally that uses giscus for comments with a custom theme. Gicus places comments in an iframe with an origin of giscus.app. My custom theme is a resource in my Hugo site (/res/comments.css in this case). When I deploy my site this works fine. When I test my site locally with hugo server I receive a CORS error.

If I’m understanding correctly, the request to load the stylesheet comes from an origin of giscus.app. The Hugo server returns the stylesheet without Access-Control-Allow-Origin in the header. The browser then refuses the response. Github Pages on the other hand serve the stylesheet with Access-Control-Allow-Origin: * and that’s why it works when deployed.

How can I configure the Hugo server to include the Access-Control-Allow-Origin header?

For context, in case it helps:

The script that loads giscus

<script src="https://giscus.app/client.js"
	data-repo="..."
	data-repo-id="..."
	data-category="..."
	data-category-id="..."
	data-mapping="pathname"
	data-strict="1"
	data-reactions-enabled="1"
	data-emit-metadata="0"
	data-input-position="bottom"
	{{- with partial "resource" "res/comments.css" }}
	data-theme="{{ .Permalink }}"
	{{- end }}
	data-lang="en"
	data-loading="lazy"
	crossorigin="anonymous"
	async>
</script>

The relevant HTML that gets generated

<iframe
	class="giscus-frame"
	title="Comments"
	scrolling="no"
	allow="clipboard-write"
	src="https://giscus.app/en/widget?..."
	loading="lazy"
	style="height: 1257px;">

<html dir="ltr" lang="en">
	<head>
		<link rel="stylesheet" href="http://localhost:1313/res/comments.css" crossorigin="anonymous" id="giscus-theme">

The error message:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:1313/res/comments.css. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 200.

Request headers:

GET /res/comments.css HTTP/1.1
Host: localhost:1313
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:132.0) Gecko/20100101 Firefox/132.0
Accept: text/css,*/*;q=0.1
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br, zstd
Origin: https://giscus.app
DNT: 1
Sec-GPC: 1
Connection: keep-alive
Sec-Fetch-Dest: style
Sec-Fetch-Mode: cors
Sec-Fetch-Site: cross-site
Priority: u=2
Pragma: no-cache
Cache-Control: no-cache

Response headers:

HTTP/1.1 200 OK
Accept-Ranges: bytes
Cache-Control: no-store, no-cache, must-revalidate, max-age=0
Content-Length: 4531
Content-Type: text/css; charset=utf-8
Last-Modified: Thu, 14 Nov 2024 01:51:54 GMT
Pragma: no-cache
Date: Thu, 14 Nov 2024 02:33:39 GMT

https://gohugo.io/getting-started/configuration/#configure-server

2 Likes

Switch to https on localhost. Much easier.

Thanks, I was searching for the particular header and completely missed that.

1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.