DEV Community

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

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

Kamal Mustafa
Python/Django Developer at GetOTP (otp.dev), fast and simple to integrate OTP API with ready made UI
・1 min read

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;
      }
      MOZ_ASSERT(result);
      aCallback->OnResolveHostComplete(this, result, NS_OK);
      return NS_OK;
    }
Enter fullscreen mode Exit fullscreen mode

https://github.com/mozilla/gecko-dev/blob/master/netwerk/dns/nsHostResolver.cpp#L1031

Discussion (1)

Collapse
k4ml profile image
Kamal Mustafa Author

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

github.com/mozilla/gecko-dev/commi...

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.