### Install and Start Sample Node.js App Source: https://github.com/ngrok/ngrok-docs/blob/main/integrations/webhooks/amazon-sns-webhooks.mdx Commands to clone the sample repository, install dependencies, and launch the local server. ```bash git clone https://github.com/ngrok/ngrok-webhook-nodejs-sample.git cd ngrok-webhook-nodejs-sample npm install ``` ```bash npm start ``` -------------------------------- ### Install and start ngrok service Source: https://github.com/ngrok/ngrok-docs/blob/main/guides/device-gateway/linux.mdx Commands to install the ngrok service and start it on the operating system. ```bash ngrok service install --config $HOME/.config/ngrok/ngrok.yml ``` ```bash ngrok service start ``` -------------------------------- ### Install Go ngrok SDK Source: https://github.com/ngrok/ngrok-docs/blob/main/snippets/guides/agent-sdks-content.mdx Install the Go SDK using 'go get'. ```sh go get golang.ngrok.com/ngrok/v2 ``` -------------------------------- ### AI Gateway Configuration Example Source: https://github.com/ngrok/ngrok-docs/blob/main/ai-gateway/guides/model-selection-strategies.mdx A complete configuration example demonstrating provider setup and model selection strategies. ```yaml on_http_request: - type: ai-gateway config: providers: - id: "openai" metadata: cost_per_1k_input: 0.03 - id: "anthropic" - id: "google" model_selection: strategy: # Prefer fast, reliable OpenAI models - "ai.models.filter(m, m.provider_id == 'openai' && m.metrics.global.error_rate.total < 0.01)" # Fall back to any fast model - "ai.models.filter(m, m.metrics.global.latency.upstream_ms_p95 < 2000)" # Fall back to any model - "ai.models" ``` -------------------------------- ### Install ngrok Authtoken Source: https://context7.com/ngrok/ngrok-docs/llms.txt Installs the authtoken, which is required for first-time setup of the ngrok agent. ```bash # Install authtoken (required for first-time setup) ngrok config add-authtoken YOUR_AUTHTOKEN ``` -------------------------------- ### Install ngrok as a background service Source: https://github.com/ngrok/ngrok-docs/blob/main/guides/device-gateway/agent.mdx Install and start the ngrok agent as a persistent background service using native OS tooling. ```bash ngrok service install --config /etc/ngrok.yml ngrok service start ``` -------------------------------- ### Install the sample Node.js app Source: https://github.com/ngrok/ngrok-docs/blob/main/integrations/webhooks/airship-webhooks.mdx Clone the repository and install dependencies for the sample application. ```bash git clone https://github.com/ngrok/ngrok-webhook-nodejs-sample.git cd ngrok-webhook-nodejs-sample npm install ``` -------------------------------- ### Start ngrok Agent with Configuration Source: https://github.com/ngrok/ngrok-docs/blob/main/guides/site-to-site-connectivity/quickstart.mdx Start the ngrok agent using either the default ngrok.yml configuration file or a specified path. The --all flag starts all configured endpoints. ```bash ngrok start --all ``` ```bash ngrok start --config /path/to/ngrok.yml --all ``` -------------------------------- ### Ready Condition Examples Source: https://github.com/ngrok/ngrok-docs/blob/main/k8s/crds/cloudendpoint.mdx Examples showing the Ready condition in both active and failed states. ```yaml conditions: - type: Ready status: "True" reason: CloudEndpointActive message: "Cloud endpoint is active" lastTransitionTime: "2025-10-29T00:39:16Z" observedGeneration: 1 ``` ```yaml conditions: - type: Ready status: "False" reason: CloudEndpointCreationFailed message: | Failed to create Cloud Endpoint: HTTP 400: The provided Cloud Endpoint was invalid because pooling was set to disabled when another endpoint exists for this url. [ERR_NGROK_18017] Operation ID: op_34ic9T376GyGAXQ4sIRn7F0xUYP lastTransitionTime: "2025-10-29T00:39:15Z" observedGeneration: 2 ``` -------------------------------- ### Rust SDK Example for Branded Domain Source: https://github.com/ngrok/ngrok-docs/blob/main/snippets/universal-gateway/shared/http-end-source.mdx Configure and start an agent endpoint on a branded domain using the Rust SDK. Ensure the domain is set up in your ngrok dashboard. ```rust use ngrok::config::SessionBuilder; use ngrok::session::Session; #[tokio::main] async fn main() -> Result<(), Box> { let session = SessionBuilder::default().connect().await?; // Start a TCP tunnel on the reserved domain "app.example.com" let listener = session.tcp_listen(80).await?; let url = listener.url(); println!("tcp tunnel listening on: {}", url); // ... server logic ... Ok(()) } ``` -------------------------------- ### Basic Example: Closing Connection Source: https://github.com/ngrok/ngrok-docs/blob/main/traffic-policy/actions/close-connection.mdx A step-by-step guide to setting up an endpoint with ngrok and applying a traffic policy to close connections based on a URL path. ```APIDOC ## Basic Example: Closing Connection This example demonstrates how to configure and use the `close-connection` action. ### Steps 1. **Save the Traffic Policy to a file (`policy.yml`):** ```yaml on_http_request: - name: "Immediately close connection" expressions: - req.url.path.startsWith("/dc") actions: - type: close-connection ``` 2. **Start the endpoint with the Traffic Policy:** ```bash ngrok http 8080 --url hotdog.ngrok.app --traffic-policy-file ./policy.yml ``` 3. **Send a request to the endpoint:** ```bash curl http://hotdog.ngrok.app/dc ``` **Expected Output:** ``` curl: (16) Error in the HTTP2 framing layer ``` This output indicates that the connection was successfully closed by the action. ``` -------------------------------- ### Start ngrok with Traffic Policy Source: https://github.com/ngrok/ngrok-docs/blob/main/integrations/webhooks/instagram-webhooks.mdx Run ngrok with the `--traffic-policy-file` option to apply the specified policy. This example forwards traffic to port 3000. ```bash ngrok http 3000 --traffic-policy-file instagram_policy.yml ``` -------------------------------- ### Serve files on Windows using Agent CLI Source: https://github.com/ngrok/ngrok-docs/blob/main/snippets/universal-gateway/shared/http-end-source.mdx Use the Agent CLI to serve files on Windows. No specific setup is required beyond having the agent installed. ```bash ngrok agent run --config=/path/to/agent.yaml ``` -------------------------------- ### Complete Examples Source: https://github.com/ngrok/ngrok-docs/blob/main/ai-gateway/reference/cel-functions.mdx Illustrative examples demonstrating advanced model selection strategies. ```APIDOC ## Complete Examples ### Provider Priority with Performance Filtering This example shows how to prioritize models from a specific provider (OpenAI) with good performance metrics, falling back to another provider (Anthropic), and finally to any available model. ```yaml model_selection: strategy: # Prefer OpenAI with good metrics - "ai.models.filter(m, m.provider_id == 'openai' && m.metrics.global.error_rate.total < 0.01)" # Fall back to Anthropic - "ai.models.filter(m, m.provider_id == 'anthropic')" # Fall back to any model - "ai.models" ``` ### Cost-Optimized Selection This example demonstrates selecting models based on cost, prioritizing the cheapest models first and then falling back to any available model. ```yaml model_selection: strategy: # Cheapest models first - "ai.models.underCost('text.input', 0.5).sortBy('price')" # Fall back to any model - "ai.models" ``` ``` -------------------------------- ### Install OpenAI SDK Source: https://github.com/ngrok/ngrok-docs/blob/main/ai-gateway/sdks/openai.mdx Install the required OpenAI SDK package for your environment. ```bash pip install openai ``` ```bash npm install openai ``` -------------------------------- ### Start the sample app Source: https://github.com/ngrok/ngrok-docs/blob/main/integrations/webhooks/airship-webhooks.mdx Launch the local server on port 3000. ```bash npm start ``` -------------------------------- ### Initialize Go Module and Install SDK Source: https://github.com/ngrok/ngrok-docs/blob/main/getting-started/go.mdx Commands to create a new Go module, navigate into it, and install the ngrok Go SDK. Ensure you are in the project directory. ```bash mkdir ngrok-go-demo cd ngrok-go-demo go mod init ngrok-go-demo go get golang.ngrok.com/ngrok/v2 ``` -------------------------------- ### Install ngrok SDK Source: https://github.com/ngrok/ngrok-docs/blob/main/getting-started/rust.mdx Commands to set up the demo project and add the ngrok dependency. ```bash mkdir ngrok-rust-demo cd ngrok-rust-demo cargo init cargo add ngrok ``` -------------------------------- ### Clone Demo Repository Source: https://github.com/ngrok/ngrok-docs/blob/main/integrations/guides/linode-gslb_edges.mdx Download the example API deployment files to the local VM. ```bash git clone https://github.com/joelhans/ngrok-vps-gslb-demo cd ngrok-vps-gslb-demo ``` -------------------------------- ### Start Internal Agent Endpoint Source: https://github.com/ngrok/ngrok-docs/blob/main/snippets/traffic-policy/actions/http-request/examples/3-query-params.mdx Starts an ngrok agent to forward HTTP traffic to an internal endpoint. This is a prerequisite for the policy examples. ```bash ngrok http https://httpbin.org --host-header rewrite --url https://httpbin.internal ``` -------------------------------- ### Clone the Online Boutique repository Source: https://github.com/ngrok/ngrok-docs/blob/main/integrations/kubernetes-ingress/azure-ad-k8s.mdx Download the example application manifests to your local machine. ```bash git clone https://github.com/GoogleCloudPlatform/microservices-demo cd microservices-demo ``` -------------------------------- ### Example Kubernetes Events Output Source: https://github.com/ngrok/ngrok-docs/blob/main/k8s/guides/troubleshooting.mdx An example of the output from `kubectl get events`. This shows various events related to pod scheduling, scaling, creation, and updates of ngrok resources. ```text LAST SEEN TYPE REASON OBJECT MESSAGE 3m24s Normal Scheduled pod/ngrok-operator-manager-657c5b69d7-f7vvg Successfully assigned ngrok-operator/ngrok-operator-manager-657c5b69d7-f7vvg to k3d-ngrok-operator-server-0 3m25s Normal ScalingReplicaSet deployment/ngrok-operator-manager Scaled up replica set ngrok-operator-manager-657c5b69d7 to 1 3m25s Normal SuccessfulCreate replicaset/ngrok-operator-manager-657c5b69d7 Created pod: ngrok-operator-manager-657c5b69d7-f7vvg 3m24s Normal Started pod/ngrok-operator-manager-657c5b69d7-f7vvg Started container ngrok-operator 3m24s Normal Created pod/ngrok-operator-manager-657c5b69d7-f7vvg Created container ngrok-operator 3m24s Normal Pulled pod/ngrok-operator-manager-657c5b69d7-f7vvg Container image "docker.io/ngrok/ngrok-operator:0.15.0" already present on machine 3m15s Normal ScalingReplicaSet deployment/ngrok-operator-manager Scaled down replica set ngrok-operator-manager-74b76d8f6d to 0 from 1 3m15s Normal SuccessfulDelete replicaset/ngrok-operator-manager-74b76d8f6d Deleted pod: ngrok-operator-manager-74b76d8f6d-2679x 3m15s Normal Killing pod/ngrok-operator-manager-74b76d8f6d-2679x Stopping container ngrok-operator 2m55s Normal Updating boundendpoint/ngrok-22680758-eb09-576e-a7ac-dc3728458dfc Updating BoundEndpoint/ngrok-22680758-eb09-576e-a7ac-dc3728458dfc 2m55s Normal Updated boundendpoint/ngrok-012050e0-8f06-560c-953e-c9d675d41305 Updated BoundEndpoint/ngrok-012050e0-8f06-560c-953e-c9d675d41305 2m55s Normal Updated boundendpoint/ngrok-22680758-eb09-576e-a7ac-dc3728458dfc Updated BoundEndpoint/ngrok-22680758-eb09-576e-a7ac-dc3728458dfc 2m55s Normal Status boundendpoint/ngrok-22680758-eb09-576e-a7ac-dc3728458dfc Successfully reconciled status 2m55s Normal Updated boundendpoint/ngrok-22680758-eb09-576e-a7ac-dc3728458dfc Updated Services 2m55s Normal Updated service/ngrok-22680758-eb09-576e-a7ac-dc3728458dfc Updated Upstream Service 2m55s Normal Updating boundendpoint/ngrok-012050e0-8f06-560c-953e-c9d675d41305 Updating BoundEndpoint/ngrok-012050e0-8f06-560c-953e-c9d675d41305 2m55s Normal LeaderElection lease/ngrok-operator-leader ngrok-operator-manager-657c5b69d7-f7vvg_72fb437b-38ad-444c-a9d8-d37349f2f677 became leader 2m55s Normal Status boundendpoint/ngrok-012050e0-8f06-560c-953e-c9d675d41305 Successfully reconciled status 2m55s Normal Updated boundendpoint/ngrok-012050e0-8f06-560c-953e-c9d675d41305 Updated Services 2m55s Normal Updated service/ngrok-012050e0-8f06-560c-953e-c9d675d41305 Updated Upstream Service 2m55s Normal Updating kubernetesoperator/ngrok-operator Updating KubernetesOperator/ngrok-operator 2m55s Normal Status kubernetesoperator/ngrok-operator Successfully reconciled status 2m55s Normal Updated kubernetesoperator/ngrok-operator Updated KubernetesOperator/ngrok-operator ``` -------------------------------- ### Configure a custom provider Source: https://github.com/ngrok/ngrok-docs/blob/main/ai-gateway/guides/configuring-providers.mdx Example setup for connecting to self-hosted models like Ollama. ```yaml providers: - id: "ollama-internal" base_url: "https://ollama.internal" api_keys: - value: ${secrets.get('ollama', 'key')} models: - id: "llama3" - id: "mistral" - id: "codellama" ``` -------------------------------- ### Example Custom JSON Response Source: https://github.com/ngrok/ngrok-docs/blob/main/snippets/traffic-policy/actions/custom-response/examples/http-json-single-interpolation.mdx This is an example of the HTTP response received when the custom response configuration is active and a request matches the specified path. It includes the 'content-type' header and a JSON body with the connection start time. ```http HTTP/2 200 OK content-type: application/json { "connection-start": "2024-06-24T15:30:00Z" } ``` -------------------------------- ### GET /endpoints with Filter Source: https://github.com/ngrok/ngrok-docs/blob/main/api/api-filtering.mdx This example demonstrates how to fetch a list of endpoints, filtering by type using a CEL expression. ```APIDOC ## GET /endpoints?filter=obj.type == "cloud" || obj.type == "agent" ### Description Fetches a list of endpoints, filtering to include only those of type "cloud" or "agent". ### Method GET ### Endpoint /endpoints ### Query Parameters - **filter** (string) - Required - A CEL expression used to filter the results. For example: `obj.type == "cloud" || obj.type == "agent"`. ### Request Example ```http GET /endpoints?filter=obj.type == "cloud" || obj.type == "agent" ``` ### Response #### Success Response (200) - **list** (array) - A list of endpoint objects matching the filter criteria. #### Response Example ```json { "endpoints": [ { "id": "ep_123", "region": "us", "type": "cloud", "created_at": "2023-01-01T12:00:00Z", "public_url": "https://example.com" } ] } ``` ``` -------------------------------- ### Get OpenAI Provider Source: https://github.com/ngrok/ngrok-docs/blob/main/ai-gateway/reference/cel-functions.mdx Retrieve the 'openai' provider object for further operations. No specific setup is required if the 'ai' library is initialized. ```yaml ai.providers.get('openai') ``` -------------------------------- ### Example Accept-Encoding header Source: https://github.com/ngrok/ngrok-docs/blob/main/traffic-policy/actions/compress-response.mdx This example demonstrates how compression is negotiated based on the Accept-Encoding header, respecting q-values. The algorithm with the highest q-value is selected if supported. ```bash Accept-Encoding: gzip;q=1.0, br; q=0.5, *;q=0 ``` -------------------------------- ### Start Sample Node.js App Source: https://github.com/ngrok/ngrok-docs/blob/main/integrations/webhooks/facebook-messenger-webhooks.mdx Start the sample Node.js application. This app will listen for incoming requests on port 3000. ```bash npm run startFacebook ``` -------------------------------- ### Get Raw Content-Type Header Source: https://github.com/ngrok/ngrok-docs/blob/main/snippets/traffic-policy/variables/res.mdx Retrieve the entire Content-Type header as a raw string. This example checks if it matches 'application/json; charset=utf-8'. ```yaml expressions: - "res.content_type.raw == 'application/json; charset=utf-8'" ``` ```json { "expressions": [ "res.content_type.raw == 'application/json; charset=utf-8'" ] } ``` -------------------------------- ### Auth0 JWT Validation Integration Source: https://github.com/ngrok/ngrok-docs/blob/main/integrations/jwt-validation/auth0.mdx This example demonstrates the integration setup for JWT validation with Auth0. Ensure you have the necessary Auth0 configuration details. ```javascript import { natsort } from "@ngrok/ngrok"; export const handler = natsort(async (event) => { // event.request.headers.authorization is the JWT token // event.request.headers.authorization.startsWith("Bearer ") // event.request.headers.authorization.substring(7) // You can optionally verify the token against Auth0's public keys // For more details, see: https://auth0.com/docs/quickstart/backend/nodejs/01-calling-an-api // If the token is valid, return the event unchanged. // If the token is invalid, return an error response. // For example: // return new Response("Unauthorized", { // status: 401, // headers: { // "Content-Type": "text/plain", // }, // }); return event; }); ``` -------------------------------- ### Start a minikube cluster Source: https://github.com/ngrok/ngrok-docs/blob/main/integrations/kubernetes-ingress/azure-ad-k8s.mdx Initialize a local Kubernetes cluster named online-boutique. ```bash minikube start -p online-boutique ``` -------------------------------- ### Compress API Responses for Paths Starting with /api/ (JSON) Source: https://github.com/ngrok/ngrok-docs/blob/main/snippets/traffic-policy/actions/compress-response/examples/compressing-api-responses-based-on-url-path.mdx This JSON configuration achieves the same response compression for paths starting with '/api/' as the YAML example. It specifies the `compress-response` action with a list of supported compression algorithms. This is an alternative format for defining Traffic Policies. ```json { "on_http_response": [ { "expressions": [ "req.url.path.startsWith('/api/')" ], "actions": [ { "type": "compress-response", "config": { "algorithms": [ "gzip", "br", "deflate", "compress" ] } } ] } ] } ``` -------------------------------- ### Install ngrok Operator (Simple Method) Source: https://github.com/ngrok/ngrok-docs/blob/main/getting-started/kubernetes/_install.mdx Use this command for a quick installation where credentials are provided directly via environment variables. ```bash helm install ngrok-operator ngrok/ngrok-operator \ --namespace ngrok-operator \ --create-namespace \ --set credentials.apiKey=$NGROK_API_KEY \ --set credentials.authtoken=$NGROK_AUTHTOKEN ``` -------------------------------- ### Start Agent Endpoint with Google OAuth Source: https://github.com/ngrok/ngrok-docs/blob/main/getting-started/javascript.mdx Use this snippet to start an Agent Endpoint that forwards traffic from a reserved domain to your local service. It secures the endpoint with Google OAuth authentication. Ensure you have `dotenv` and `@ngrok/ngrok` installed and your NGROK_AUTHTOKEN and NGROK_DOMAIN environment variables are set. ```javascript require('dotenv').config(); const ngrok = require('@ngrok/ngrok'); (async function() { const listener = await ngrok.forward({ // The port your app is running on. addr: 8080, authtoken: process.env.NGROK_AUTHTOKEN, domain: process.env.NGROK_DOMAIN, // Secure your endpoint with a Traffic Policy. // This could also be a path to a Traffic Policy file. traffic_policy: '{"on_http_request": [{"actions": [{"type": "oauth","config": {"provider": "google"}}]}]}' }); // Output ngrok URL to console console.log(`Ingress established at ${listener.url()}`); })(); // Keep the process alive process.stdin.resume(); ``` -------------------------------- ### Initialize Rust Project Source: https://github.com/ngrok/ngrok-docs/blob/main/getting-started/rust.mdx Commands to create a new directory and initialize a Rust project. ```bash mkdir ngrok-rust-server cd ngrok-rust-server ``` ```bash cargo init ``` -------------------------------- ### Install Operator with Simple Credentials Source: https://github.com/ngrok/ngrok-docs/blob/main/getting-started/kubernetes/_install-bindings.mdx Use this command for a quick installation where credentials are passed directly to Helm. Ensure NGROK_API_KEY and NGROK_AUTHTOKEN environment variables are set. ```bash helm install ngrok-operator ngrok/ngrok-operator \ --namespace ngrok-operator \ --create-namespace \ --set credentials.apiKey=$NGROK_API_KEY \ --set credentials.authtoken=$NGROK_AUTHTOKEN \ --set bindings.enabled=true ``` -------------------------------- ### Configure LinkedIn OAuth in JSON Source: https://github.com/ngrok/ngrok-docs/blob/main/snippets/traffic-policy/actions/oauth/examples/custom-linkedin-example.mdx This JSON configuration achieves the same OAuth setup as the YAML example. It's useful for environments where JSON is preferred for configuration. ```json { "on_http_request": [ { "actions": [ { "type": "oauth", "config": { "provider": "linkedin", "client_id": "{your app's oauth client id}", "client_secret": "{your app's oauth client secret}", "scopes": [ "r_emailaddress", "r_liteprofile" ] } } ] } ] } ``` -------------------------------- ### Start Sample Node.js App Source: https://github.com/ngrok/ngrok-docs/blob/main/integrations/webhooks/okta-webhooks.mdx Start the sample Node.js application. It runs on port 3000 by default and logs request headers and body. ```bash npm run startOkta ``` -------------------------------- ### Full ngrok Agent Configuration v2 Example Source: https://github.com/ngrok/ngrok-docs/blob/main/agent/config/v2.mdx A comprehensive template for the ngrok agent configuration file. Uncomment specific lines to activate desired settings. ```yaml # ngrok Configuration File v2 # https://ngrok.com/docs/agent/config/ # ###################################################################### # # Agent Configuration # # ###################################################################### # ---------------------------------------------------------------------- # | Authtoken (required) | # ---------------------------------------------------------------------- # Specifies the authentication token (authtoken) used to connect to the # ngrok service. # # (1) You can get your default authtoken through the dashboard: # https://dashboard.ngrok.com/get-started/your-authtoken # # (2) You can view and generate authtokens through the dashboard # https://dashboard.ngrok.com/tunnels/authtokens #authtoken: 4nq9771bPxe8ctg7LKr_2ClH7Y15Zqe4bWLWF9p # ---------------------------------------------------------------------- # | API Key | # ---------------------------------------------------------------------- # The ngrok API key used to connect to the ngrok API. # # (!) This is only needed when using the ngrok api command and should # not be confused with the authtoken. # # (1) You can obtain and manage your API Keys through the dashboard: # https://dashboard.ngrok.com/api-keys #api_key: 24yRd5U3DestCQapJrrVHLOqiAC_7RviwRqpd3wc9dKLujQZN # ---------------------------------------------------------------------- # | Connect Timeout | # ---------------------------------------------------------------------- # How long to wait when establishing an agent session connection to the # ngrok service. # # Accepts duration, the default is 10s #connect_timeout: 30s # ---------------------------------------------------------------------- # | Console UI | # ---------------------------------------------------------------------- # Enable or disable the console UI in the terminal. # # Options: # true - Enable the console UI. # false - Disable the console UI, use structured log format. # iftty - (Default) Enable UI only if standard out is a TTY. #console_ui: iftty # ---------------------------------------------------------------------- # | Console UI Color | # ---------------------------------------------------------------------- # Sets the console UI background color in the terminal. # # To use a color other than black, set to `transparent` and adjust your # terminal's background. #console_ui_color: transparent # ---------------------------------------------------------------------- # | CRL No Verify | # ---------------------------------------------------------------------- # Skip Certificate Revocation List (CRL) verification if set to true. # # Accepts a boolean. Default is `false`. #crl_noverify: false # ---------------------------------------------------------------------- # | DNS Resolver IPs | # ---------------------------------------------------------------------- # List of DNS servers for resolving tunnel session DNS. # # Defaults to using the local system DNS servers. #dns_resolver_ips: # - 1.1.1.1 # - 8.8.8.8 # ---------------------------------------------------------------------- # | Heartbeat Interval | # ---------------------------------------------------------------------- # How often the ngrok agent should heartbeat to the ngrok servers defined # as a duration. # # Accepts a duration (for example, 10s, 1m). The default value is `10s`. #heartbeat_interval: 1m # ---------------------------------------------------------------------- # | Heartbeat Tolerance | # ---------------------------------------------------------------------- # This setting defines the maximum duration to wait for a heartbeat # response from the server before reconnecting the agent tunnel session. # # Accepts a duration (for example, 10s, 1m). The default value is `15s`. #heartbeat_tolerance: 5s # ---------------------------------------------------------------------- # | Inspect DB Size | # ---------------------------------------------------------------------- ``` -------------------------------- ### Conditional Redirect with Phase Expressions Source: https://github.com/ngrok/ngrok-docs/blob/main/traffic-policy/actions/redirect.mdx Implement redirects based on specific conditions evaluated during the 'on_http_request' phase. This example redirects only if the request path starts with '/api/v1/'. ```yaml on_http_request: - expressions: - req.url.path.startsWith('/api/v1/') actions: - type: redirect config: from: /api/v1/ to: /api/v2/ ``` -------------------------------- ### Example Request with JWT Source: https://github.com/ngrok/ngrok-docs/blob/main/snippets/traffic-policy/actions/jwt-validation/examples/basic-example.mdx This bash command demonstrates how to send a GET request to an ngrok-tunneled API endpoint with a valid JWT in the Authorization header, prefixed with 'Bearer '. ```bash $ curl --request GET \ --url http://example-api.ngrok.app/ \ --header 'authorization: Bearer ' ``` -------------------------------- ### Install HashiCups Sample App Source: https://github.com/ngrok/ngrok-docs/blob/main/integrations/kubernetes-ingress/consul-k8s.mdx Deploy the HashiCups sample application, including its services and deployments, into the 'consul' namespace. ```bash kubectl apply -f learn-consul-kubernetes/service-mesh/deploy/hashicups -n consul ``` -------------------------------- ### Start vLLM Server Source: https://github.com/ngrok/ngrok-docs/blob/main/ai-gateway/custom-providers/vllm.mdx Start the vLLM OpenAI-compatible server. Verify it is running by checking the available models. ```bash vllm serve meta-llama/Llama-3.2-8B-Instruct ``` ```bash curl http://localhost:8000/v1/models ``` -------------------------------- ### Tunnel Creation Response (Default Policies) Source: https://github.com/ngrok/ngrok-docs/blob/main/guides/device-gateway/sdk.mdx This is an example of a successful response when starting a tunnel with default policies. Note that the 'policy' field is null in this initial response. ```json { "url": "https://device123.sitea.configurable-domain.com", "protocol": "http", "forwards_to": "localhost:8001", "domain": "agent.sitea.configurable-domain.com", "policy": null } ``` -------------------------------- ### Get ngrok Agent Status Source: https://github.com/ngrok/ngrok-docs/blob/main/agent/api.mdx This command-line example shows how to fetch the current status and metrics of a running ngrok agent. It requires the agent to be running locally. ```sh curl http://localhost:4040/api/status ``` -------------------------------- ### Clone and Install Sample Node.js App Source: https://github.com/ngrok/ngrok-docs/blob/main/integrations/webhooks/github-webhooks.mdx Clone the sample Node.js webhook application from GitHub and install its dependencies. ```bash git clone https://github.com/ngrok/ngrok-webhook-nodejs-sample.git cd ngrok/ngrok-webhook-nodejs-sample npm install ``` -------------------------------- ### Start ngrok agent Source: https://github.com/ngrok/ngrok-docs/blob/main/errors/err_ngrok_3200.mdx Initializes the ngrok agent to expose a local port. ```bash ngrok http [port] ``` -------------------------------- ### Start ngrok Service Source: https://github.com/ngrok/ngrok-docs/blob/main/guides/device-gateway/raspbian.mdx Starts the ngrok service, ensuring it launches automatically on system startup. You might need to run this with sudo. ```bash ngrok service start ``` -------------------------------- ### Tunnel Creation Response (Custom Policies) Source: https://github.com/ngrok/ngrok-docs/blob/main/guides/device-gateway/sdk.mdx This is an example of a successful response when starting a tunnel with custom policies embedded in the request. The 'policy' field now reflects the specified configurations. ```json { "url": "https://device123.sitea.configurable-domain.com", "protocol": "http", "forwards_to": "localhost:8001", "domain": "device123.sitea.configurable-domain.com", "policy": { "on_http_request": [], "on_http_response": [ { "expressions": [], "name": "Add headers to requests", "actions": [ { "type": "add-headers", "config": { "headers": { "is-ngrok": "444" } } } ] } ] } } ``` -------------------------------- ### Start Containerized Deployment Source: https://github.com/ngrok/ngrok-docs/blob/main/integrations/guides/linode-gslb_edges.mdx Launch the API and ngrok agent containers using Docker Compose. ```bash HOSTNAME=$(hostname -f) docker compose up -d ``` -------------------------------- ### Rust SDK Example for Wildcard Domain Source: https://github.com/ngrok/ngrok-docs/blob/main/snippets/universal-gateway/shared/http-end-source.mdx Configure and start a wildcard endpoint using the Rust SDK. This enables the endpoint to accept traffic for any subdomain matching the wildcard pattern. ```rust use ngrok::config::SessionBuilder; use ngrok::session::Session; #[tokio::main] async fn main() -> Result<(), Box> { let session = SessionBuilder::default().connect().await?; // Start a TCP tunnel on the wildcard domain "*.example.com" let listener = session.tcp_listen(80).await?; let url = listener.url(); println!("tcp tunnel listening on: {}", url); // ... server logic ... Ok(()) } ``` -------------------------------- ### Create Basic Go HTTP Server Source: https://github.com/ngrok/ngrok-docs/blob/main/getting-started/go.mdx Use this code to set up a minimal Go HTTP server that listens on port 8080. This is useful if you don't have an existing application to expose. ```go package main import ( "fmt" "net/http" ) func handler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello from Go HTTP Server!") } func main() { http.HandleFunc("/", handler) fmt.Println("Starting server at http://localhost:8080") err := http.ListenAndServe(":8080", nil) if err != nil { fmt.Println("Server failed:", err) } } ``` -------------------------------- ### Add ngrok Credentials to .env File Source: https://github.com/ngrok/ngrok-docs/blob/main/getting-started/go.mdx Example content for the .env file, showing where to place your ngrok authentication token and reserved domain. Replace placeholders with your actual credentials. ```text NGROK_AUTHTOKEN=your_actual_auth_token_here NGROK_DOMAIN=your_actual_domain_here ``` -------------------------------- ### Example Request to Trigger Policy Source: https://github.com/ngrok/ngrok-docs/blob/main/traffic-policy/actions/add-headers.mdx This curl command sends a GET request to a specific path, designed to match the policy's expressions and trigger the addition of custom headers. ```bash $ curl -i https://httpbin.ngrok.app/status/200 ``` -------------------------------- ### Start a local Kubernetes cluster with minikube Source: https://github.com/ngrok/ngrok-docs/blob/main/integrations/kubernetes-ingress/vcluster-k8s.mdx Use this command to create a new local Kubernetes cluster profile named 'dc1' with 4096MB of memory. Ensure minikube is installed and configured. ```bash minikube start --profile dc1 --memory 4096 ``` -------------------------------- ### GitHub Actions Workflow for Deploying Previews Source: https://github.com/ngrok/ngrok-docs/blob/main/universal-gateway/examples/ephemeral-workloads.mdx This workflow automates the build and deployment of preview URLs for pull requests. It installs ngrok, starts the application, and creates a tunnel to an internal agent endpoint. ```yaml name: Deploy Preview on: pull_request: types: [opened, synchronize, reopened] jobs: preview: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Build and start app run: | # Build your app npm install && npm run build # Start your app in the background npm run start & sleep 5 - name: Install ngrok run: | curl -sSL https://ngrok-agent.s3.amazonaws.com/ngrok.asc \ | sudo tee /etc/apt/trusted.gpg.d/ngrok.asc >/dev/null echo "deb https://ngrok-agent.s3.amazonaws.com buster main" \ | sudo tee /etc/apt/sources.list.d/ngrok.list sudo apt update && sudo apt install ngrok - name: Start ngrok tunnel env: NGROK_AUTHTOKEN: ${{ secrets.NGROK_AUTHTOKEN }} run: | ngrok config add-authtoken $NGROK_AUTHTOKEN ngrok http 3000 --url https://pr-${{ github.event.pull_request.number }}.internal & sleep 5 - name: Run tests against preview run: | curl -sSf https://pr-${{ github.event.pull_request.number }}.preview.example.com - name: Comment preview URL uses: actions/github-script@v7 with: script: | github.rest.issues.createComment({ issue_number: context.issue.number, owner: context.repo.owner, repo: context.repo.repo, body: `🚀 Deploy preview available at: https://pr-${{ github.event.pull_request.number }}.preview.example.com` }) ``` -------------------------------- ### Start Sample Python ngrok Agent Source: https://github.com/ngrok/ngrok-docs/blob/main/guides/device-gateway/sdk.mdx Run this command to start the custom ngrok agent application built with the Python SDK. ```python python agent.py ``` -------------------------------- ### Mosquitto Server Output Source: https://github.com/ngrok/ngrok-docs/blob/main/integrations/guides/mqtt.mdx Example output showing the Mosquitto server initialization and listener status. ```bash 1734408888: mosquitto version 2.0.20 starting 1734408888: Using default config. 1734408888: Starting in local only mode. Connections will only be possible from clients running on this machine. 1734408888: Create a configuration file which defines a listener to allow remote access. 1734408888: For more details see https://mosquitto.org/documentation/authentication-methods/ 1734408888: Opening ipv4 listen socket on port 1883. 1734408888: Opening ipv6 listen socket on port 1883. 1734408888: mosquitto version 2.0.20 running ``` -------------------------------- ### HTTP Response Backend Configuration Source: https://github.com/ngrok/ngrok-docs/blob/main/guides/migration/edges-to-endpoints.mdx Configure an HTTP response backend to serve static content for requests matching specific expressions. This example returns a 200 status code with 'pong' as the body for requests starting with '/api'. ```yaml on_http_request: - expressions: - req.url.path.startsWith("/api") actions: - type: custom-response config: status_code: 200 body: pong ``` -------------------------------- ### Serve Local Files with Ngrok Source: https://github.com/ngrok/ngrok-docs/blob/main/snippets/universal-gateway/shared/http-end-source.mdx Example of using the `file://` scheme to serve local directories. Ngrok acts as a built-in file server. Paths must be absolute. ```shell ngrok http file:///var/log ``` -------------------------------- ### Add Traffic Policy to Kubernetes Endpoint Source: https://github.com/ngrok/ngrok-docs/blob/main/getting-started/kubernetes/endpoints.mdx Define a Traffic Policy in YAML to manipulate requests or responses for a Kubernetes Endpoint. This example adds a custom header to the response. Ensure your Agent Endpoint is started with the traffic policy file. ```yaml on_http_respons: - actions: - type: add-header config: headers: x-hello-world: Hello, world! ``` ```bash ngrok http $PORT --url http://hello-world.default --binding kubernetes --traffic-policy-file hello-world.yaml ``` -------------------------------- ### Make Chat Completions Request with Vercel AI SDK Source: https://github.com/ngrok/ngrok-docs/blob/main/ai-gateway/providers/inference-net.mdx Utilize this Vercel AI SDK example for making requests to Inference.net via the ngrok AI Gateway. Ensure you have the necessary SDK packages installed and replace '...' with your Inference.net API key. ```typescript import { generateText } from "ai"; import { createOpenAI } from "@ai-sdk/openai"; const gateway = createOpenAI({ baseURL: "https://your-ai-gateway.ngrok.app/v1", apiKey: "...", // Your Inference.net key, forwarded by gateway }); const { text } = await generateText({ model: gateway("inference-net:meta-llama-3.1-8b-instruct/fp-8"), prompt: "Hello!", }); console.log(text); ``` -------------------------------- ### Install ngrok, uvicorn, fastapi, and loguru dependencies Source: https://github.com/ngrok/ngrok-docs/blob/main/using-ngrok-with/fastAPI.mdx List the required Python packages in a requirements.txt file. Ensure you are using a virtual environment for dependency management. ```sh # requirements.txt ngrok==1.4.0 uvicorn==0.29.0 fastapi==0.111.0 loguru==0.7.2 ``` -------------------------------- ### HTTPS Tunnel Group Backend Configuration Source: https://github.com/ngrok/ngrok-docs/blob/main/guides/migration/edges-to-endpoints.mdx Configure an HTTPS tunnel group backend to forward requests to an internal domain. Use `on_error: continue` to fall back to a `custom-response` action if the upstream tunnel is unavailable. This example demonstrates routing requests starting with '/api' to `https://service-app.internal`. ```yaml on_http_request: - expressions: - req.url.path.startsWith("/api") actions: - type: forward-internal config: url: https://service-app.internal on_error: continue - type: custom-response config: body: | No upstream tunnel available. Start your agent: ngrok http 80 --url https://service-app.internal ``` -------------------------------- ### GET ngrok api backends static-address get Source: https://github.com/ngrok/ngrok-docs/blob/main/agent/cli-api.mdx Get detailed information about a static backend by ID. ```APIDOC ## GET ngrok api backends static-address get ### Description Get detailed information about a static backend by ID. ### Method GET ### Endpoint ngrok api backends static-address get ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the static backend ``` -------------------------------- ### Example load balancing output Source: https://github.com/ngrok/ngrok-docs/blob/main/integrations/kubernetes-ingress/gslb.mdx Sample output showing responses from different data centers. ```json [{"id":"c46bdbd9-b588-4ffa-8018-d299d0918bbc","dc":"sydney"}] [{"id":"dce5a46e-15af-4479-a073-8fbc7f0097c5","dc":"nyc"}] [{"id":"ecc6451c-bc25-43bd-8cb6-a162f019adf3","dc":"frankfurt"}] [{"id":"ecc6451c-bc25-43bd-8cb6-a162f019adf3","dc":"frankfurt"}] [{"id":"ecc6451c-bc25-43bd-8cb6-a162f019adf3","dc":"frankfurt"}] [{"id":"c46bdbd9-b588-4ffa-8018-d299d0918bbc","dc":"sydney"}] [{"id":"c46bdbd9-b588-4ffa-8018-d299d0918bbc","dc":"sydney"}] [{"id":"ecc6451c-bc25-43bd-8cb6-a162f019adf3","dc":"frankfurt"}] [{"id":"ecc6451c-bc25-43bd-8cb6-a162f019adf3","dc":"frankfurt"}] [{"id":"dce5a46e-15af-4479-a073-8fbc7f0097c5","dc":"nyc"}] [{"id":"ecc6451c-bc25-43bd-8cb6-a162f019adf3","dc":"frankfurt"}] [{"id":"dce5a46e-15af-4479-a073-8fbc7f0097c5","dc":"nyc"}] [{"id":"dce5a46e-15af-4479-a073-8fbc7f0097c5","dc":"nyc"}] [{"id":"c46bdbd9-b588-4ffa-8018-d299d0918bbc","dc":"sydney"}] [{"id":"ecc6451c-bc25-43bd-8cb6-a162f019adf3","dc":"frankfurt"}] [{"id":"c46bdbd9-b588-4ffa-8018-d299d0918bbc","dc":"sydney"}] [{"id":"c46bdbd9-b588-4ffa-8018-d299d0918bbc","dc":"sydney"}] [{"id":"dce5a46e-15af-4479-a073-8fbc7f0097c5","dc":"nyc"}] [{"id":"ecc6451c-bc25-43bd-8cb6-a162f019adf3","dc":"frankfurt"}] [{"id":"dce5a46e-15af-4479-a073-8fbc7f0097c5","dc":"nyc"}] ``` -------------------------------- ### Complete AI Gateway Configuration Example Source: https://github.com/ngrok/ngrok-docs/blob/main/ai-gateway/reference/configuration-schema.mdx A comprehensive example demonstrating the configuration of the AI Gateway, including multiple providers (OpenAI, Anthropic, Ollama), API key management, model definitions, and advanced model and API key selection strategies. ```yaml on_http_request: - type: ai-gateway config: max_input_tokens: 4096 max_output_tokens: 2048 total_timeout: "3m" per_request_timeout: "30s" on_error: "halt" only_allow_configured_providers: true only_allow_configured_models: true providers: - id: "openai" metadata: team: "ml" api_keys: - value: ${secrets.get('openai', 'primary')} - value: ${secrets.get('openai', 'backup')} - value: ${secrets.get('openai', 'emergency')} models: - id: "gpt-4o" metadata: approved: true - id: "gpt-4o-mini" metadata: approved: true - id: "anthropic" api_keys: - value: ${secrets.get('anthropic', 'key')} models: - id: "claude-3-5-sonnet-20241022" - id: "ollama-internal" base_url: "https://ollama.company.internal" models: - id: "llama3-70b" model_selection: strategy: - "ai.models.filter(m, m.provider_id == 'openai')" - "ai.models.filter(m, m.provider_id == 'anthropic')" - "ai.models.filter(m, m.provider_id == 'ollama-internal')" api_key_selection: strategy: # Prefer keys with remaining quota - "ai.keys.filter(k, k.quota.remaining_requests > 100)" # Fall back to keys with low error rates - "ai.keys.filter(k, k.error_rate.rate_limit < 0.1)" # Fall back to all keys - "ai.keys" ``` -------------------------------- ### GET ngrok api event-sources get Source: https://github.com/ngrok/ngrok-docs/blob/main/agent/cli-api.mdx Get the details for a given type that triggers for the given event subscription. ```APIDOC ## GET ngrok api event-sources get ### Description Get the details for a given type that triggers for the given event subscription. ### Method GET ### Endpoint ngrok api event-sources get ### Parameters #### Query Parameters - **--subscription-id** (string) - Required - The unique identifier for the Event Subscription that this Event Source is attached to. - **--type** (string) - Required - Type of event for which an event subscription will trigger - **--api-key** (string) - Optional - API key to use ``` -------------------------------- ### Install pyngrok Source: https://github.com/ngrok/ngrok-docs/blob/main/using-ngrok-with/googleColab.mdx Install the pyngrok library in your Google Colab notebook using pip. This command installs the library quietly. ```bash !pip -q install pyngrok ``` -------------------------------- ### Create and run a Node.js HTTP server Source: https://github.com/ngrok/ngrok-docs/blob/main/getting-started/cloud-endpoints-quickstart.mdx Sets up a basic HTTP server using the built-in http module. ```javascript const http = require('http'); const server = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/html' }); const html = ` Test Page

Hello from Node.js HTTP Server!

`; res.end(html); }); const port = 8080; server.listen(port, () => { console.log(`Serving custom HTML at http://localhost:${port}`); }); ``` ```bash node service.js ``` -------------------------------- ### Serve files on Windows using Go SDK Source: https://github.com/ngrok/ngrok-docs/blob/main/snippets/universal-gateway/shared/http-end-source.mdx Utilize the Go SDK to serve files on Windows. This requires Go to be installed and the ngrok SDK to be imported. ```go package main import ( "log" "net/http" "os" "github.com/ngrok/ngrok-go/v2" ) func main() { ctx := ngrok.NewContext(context.Background(), ngrok.WithAuthtokenFromEnv()) // Open a TCP tunnel to localhost:80 ln, err := ngrok.Listen(ctx, "tcp", "localhost:80") if err != nil { log.Fatal(err) } defer ln.Close() // Close the listener when main exits log.Println("ngrok tunnel opened at:", ln.URL()) // Serve files from the current directory fs := http.FileServer(http.Dir(".")) // Handle all requests to the root path http.Handle("/", fs) // Start the HTTP server log.Println("HTTP server listening on", ln.Addr()) log.Fatal(http.Serve(ln, nil)) } ``` -------------------------------- ### Start ngrok Endpoints from Config Source: https://context7.com/ngrok/ngrok-docs/llms.txt Starts endpoints defined in the ngrok configuration file. Supports starting specific endpoints or all defined endpoints. ```bash # Start endpoints defined in config file ngrok start myapp ngrok start --all ```