When building a Next.js app for mobile, I faced a common issue — testing the app on my phone while it’s running on localhost
on my development machine. Trying to access localhost
directly from my phone didn't work. Here's how I solved it using ngrok.
The Problem
When I tried accessing my localhost
from my mobile phone’s browser or app, it simply didn’t connect. Since localhost
is specific to your computer, devices on the same network, like your mobile phone, can’t access it directly. I needed a way to expose my development server to external devices.
The Solution: Using ngrok
I remembered using ngrok in a similar situation to expose my local development environment to the web. Here’s how I did it:
Step 1: Install ngrok
Since I was on a new laptop, ngrok wasn’t installed yet. If you’re in the same situation, you can easily install ngrok by heading to ngrok’s website and downloading it for your operating system.
Once installed, unzip the file and move ngrok
to your /usr/local/bin/
folder for global access on your terminal:
unzip /path/to/ngrok.zip
mv ngrok /usr/local/bin
// if you use Mac OS
brew install ngrok/ngrok/ngrok
Step 2: Create an ngrok Account and Get the Authtoken
When I tried running ngrok with:
ngrok http 8080
I got the error:
authentication failed: Usage of ngrok requires a verified account and authtoken.
Since this was a new laptop, I hadn’t set up my ngrok authentication. I logged into my ngrok account and retrieved my authtoken.
You can add your authtoken to ngrok with the following command:
ngrok authtoken YOUR_AUTHTOKEN
This authenticates your machine with your ngrok account.
Step 3: Run ngrok
Now, with the authtoken set up, I ran:
ngrok http 8080
If your Next.js app is running on a different port, just replace 8080
with the correct port number.
After running this command, ngrok provided me with a public URL, something like:
http://abc123.ngrok.io
This URL is a publicly accessible address that tunnels directly to my localhost
. I could now access my Next.js app from my mobile phone by opening this ngrok URL in my phone’s browser.
Conclusion
With ngrok set up, I could test my app on my mobile device while it was still running on my development machine. This method not only allows you to test mobile responsiveness but also enables testing how the app behaves on actual mobile hardware, with different network environments.
I hope this helps you quickly solve the problem of accessing localhost
from your mobile phone. With just a few steps, ngrok can save you a lot of time and effort during your development process.