Code and Life

Programming, electronics and other cool tech stuff

Supported by

Supported by Picotech

Fixing MIME type errors when using Golang net/http FileServer

Today as I was finishing my Go+SvelteKit article, I ran into frustrating Chrome error message:

Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/plain". Strict MIME type checking is enforced for module scripts per HTML spec.

Don't you just love Chrome? It knows what it needs to do (load a JavaScript module), but utterly refuses to do that because of a wrong MIME type. This happened with a client-side SvelteKit application, when it tried to open some part of the .js code.

At the time of writing, it seemed I could not find the answer easily to this one, but there actually seems to be a StackOverflow solution discussing this. But to help others hitting the same issue:

The problem on my Windows install was likely that Windows 10 registry did not contain a MIME type definition for .js files. Informing user how to tweak registry to get your program working is not ideal, but thankfully you can augment the mime types:

import "mime"

func main() {
	// Windows may be missing this
	mime.AddExtensionType(".js", "application/javascript")

    // And then you create the FileServer like you normally would
	http.Handle("/", http.FileServer(http.Dir("static")))
}

After adding the mime fix, remember to force reload Chrome page (hold Control key down while you press refresh), otherwise the problem persists as Chrome does not really bother reloading the offending files.