Local Development With Subdomains on WSL2

I’m writing a webapp that loads content based on the subdomain. Doing this locally is problematic because you can’t use a subdomain with http://localhos:8080.

I’m using WSL2 on Windows 10 and can therefore leverage the hosts file, usually found in C:\Windows\System32\drivers\etc\hosts. By adding these lines to it I can create a domain with two subdomains locally and point them both at my WSL instances IP address:

1
2
172.19.38.94     test-site.mysite.local
172.19.38.94     no-site.mysite.local

After making any changes to the hosts file it is important to flush the DNS cache by running the following in Powershell:

1
ipconfig /flushdns

When visiting those URLs in my browser, and by adding the port, I can see my webapp running on WSL.

In javascript I can read the subdomain with the following:

1
String(window.location.host).split(`.`)[0]