Let's say I have a Next.js Application. Which is working properly. The application is currently accessible through http://localhost:4000
or http://somehostname.local:4000
here, I have set
127.0.0.1 somehostname.local
in my hosts file.
But, I want this Next.js application to only be accessible from http://somehostname.local:4000
only, in my local environment.
How would I do it?
I can't figure out why you need to block localhost when serving locally? I'd love to hear your rationale.
You won't be able to achieve this with the default config since the default config is the same as using
npm run dev -H localhost
and localhost will by default resolve to 127.0.0.1 so localhost and somehostname.local are essentially the same alias in your scenario. In theory you could remove the localhost alias, but that breaks lots of things and is highly not recommended.
However you can achieve what you want with a firewall and using your local IP. This is kind of hacky and will break if your network or IP changes, but it's technically possible.
Alias somehostname.local to your local IP address in your hosts file:
xxx.xxx.xxx.xxx somehostname.local
Then run the next server on your alias with
npm run dev -H somehostname.local
or add it to your scripts or config file.
This will make the next app available on the local network so set your firewall to block lan access to port 4000 and allow local access:
iptables -A INPUT -p tcp --dport 4000 -s xxx.xxx.xxx.xxx -j ACCEPT
iptables -A INPUT -p tcp --dport 4000 -j DROP
This will serve on http://somehostname.local:4000 but not on http://localhost:4000.
I still can't imagine a scenario where blocking localhost is important, and since this solution breaks when your local IP changes it seems like a poor approach. I suppose you could script automatic updates of the firewall rules and hosts file, but why?