DEV Community

Cover image for Firefox and Chrome resolve any localhost domain (*.localhost) to loopback address
Kamal Mustafa
Kamal Mustafa

Posted on

Firefox and Chrome resolve any localhost domain (*.localhost) to loopback address

I was reading this reddit's thread and this comment caught my interest:-

Chrome and Firefox also consider "*.localhost" as secure so you can develop multiple websites with different service workers. They automatically resolve to "localhost" so it's very handy.

I didn't know this and after trying myself on Firefox, that's turn out to be true. I checked my /etc/hosts to make sure I didn't have the name defined that and also checked via host command and dig as well. Both returned domain not found result.

host web01.localhost
Host web01.localhost not found: 3(NXDOMAIN)
Enter fullscreen mode Exit fullscreen mode

So it pretty sure coming from Firefox itself. Firefox also has this pretty handy dns lookup tools (accessible via about:networking#dns):-

Alt Text

I can't find much information about this so why not just look directly in the source code? After some googling, I guess the networking portion for Firefox is under the directory called netwerk and made my educated guess that the code could be in nsHostResolver.cpp. Then using browser's Find on page for "localhost", voila! The code looks like this:-

// Check if we have a localhost domain, if so hardcode to loopback
    if (IS_ADDR_TYPE(type) && IsLoopbackHostname(host)) {
      nsresult rv;
      RefPtr<nsHostRecord> result = InitLoopbackRecord(key, &rv);
      if (NS_WARN_IF(NS_FAILED(rv))) {
        return rv;
      aCallback->OnResolveHostComplete(this, result, NS_OK);
      return NS_OK;
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

k4ml profile image
Kamal Mustafa

Did some more digging (git blame) and turned out this was added 7 months ago.

The context of this commit also interesting as it allow the browser to trust .localhost as secure origin and you don't need https in local dev for stuff that require https before, such as service workers.