[ngrok | Angular] External Access to your Local Test Environment

Sometimes you have to test your local hosted API or website with multiple different devices. They may be on the same network and you can open your local ports in some way to get it working but most of the time it's a messy solution.

Tech Stack

  • Angular
  • ASP.NET Web API
  • ngrok

Starting Situation

I started my angular solution with ng serve and the website is running on localhost:4200
My ASP.NET Web API is running on localhost:7097

ngrok Setup

The setup is easy, just go to their website, create an account and follow their setup & installation.
On step 3 of their setup change the port from 80 to 4200.
Now you should see a forwarding address in the ngrok window - try it on any device which is connected to the internet. You should see your local angular website!

Optional ngrok Config

You can create a config yml file for the ngrok.exe. I'm using the following config:

version: "2"
authtoken: <insertToken>

tunnels:
  test:
    addr: localhost:4200
    host_header: rewrite
    proto: http

Start ngrok with the following command:

ngrok.exe start --config=ngrok.yml test

Angular Setup

The website should open but your backend calls will fail because they point to localhost. We are able to fix this with the built in angular proxy.
Add a JSON file to your frontend solution and call it something like proxy.conf.json - I'm adding it to the root folder. Add the following content:

{
  "/api/**": {
    "target": "https://localhost:7097",
    "secure": false,
    "pathRewrite": {
      "^/api": ""
    }
  }
}

With this config, every request to localhost:4200/api/<method> will be rewritten to localhost:7097/<method>. So don't forget to change your backend url config from https://localhost:7097 to ./api !

Finally add the proxy config to your angular.json config to automatically use it when you are running ng serve.

"serve": {
    "builder": "@angular-devkit/build-angular:dev-server",
    "options": {
         "proxyConfig": "proxy.conf.json"
     }
}

If you have further questions about this topic or need help with a problem in general, please write a comment or simply contact me at yesreply@georghoeller.dev :)