How to preview localhost on your mobile phone

2022-12-103 min
How to preview localhost on your mobile phone

When creating web applications, we very often have to take care of mobile UI/UX. Regardless of whether you follow the "mobile first" principle or not, in most cases mobile design is important.

Maybe you think that checking mobile resolution on dev tools is good enough, but believe me, it's not the same as using real device.

I found out about it myself many times during my career, here you can read about one of my experiences.

So what we can do to test our applications better in regards to mobile devices? There are few ways, perhaps you can use Browserstack or the other app which let you test on real devices remotely, but there's a simple way to preview the application running on your PC localhost from your real mobile phone.

Serve the application

If you're using React CRA, Angular, Vue, or another framework that serves your application out of the box you have an easier job to do :) Just run it as you usually do and skip the rest of this section.

npm start // or whatever is your command to run the app

If you don't have a server, then you need to take care of running one. There are many tools you could use, but I will give you an example using http-server.

You can install it using "npx", "homebrew", or "npm" (more in docs). Run your terminal and paste the following command:

npm install --global http-server

Now you should open the project directory in your terminal and run the following command:

http-server

That's it, you should see the information about the running server. Please check the PORT, you will need it in the next step.

http-server

I suggest you to decrease cache time because otherwise, it might be hard to follow live changes.

http-server -c10 // cache set as 10 seconds

Preview the app on the mobile device

1. Network

You need to connect your mobile to the same network as your desktop.

2. Find your PC IP address

Windows:

1. Open the terminal
2. Run "ipconfig" command
3. "IPv4 Address" is what you're looking for

Mac:

1. Open the terminal
2. Run "ipconfig getifaddr en0"

Alternatively, you can use mac os interface to find the IP

1. Open the "System Preferences"
2. Go to "Network"
3. Click on your "WIFI network from the list"
4. You should see IP Address just under "Status: Connected"
5. If you can't see it --> Click on "Advanced"
6. Open "TCP/IP" tab
7. "IPv4 Address" is what you're looking for

Open localhost on your mobile device browser

If you already know your desktop IP, open the mobile browser and type the IP with the correct PORT in the address bar. For CRA it's ":3000", for an app running via "http-server" it's probably ":8080". Please check it first :)

192.xxx.x.xxx:xxxx // use your IP and PORT

That's all, you should be able to see your application running on your phone! Enjoy!