The ngrok Rust SDK is an open-source package that enables you to quickly and efficiently serve Node.js applications on the internet without the need to configure low-level network primitives like IPs, certificates, load balancers, or ports. You can think of it as the ngrok Agent CLI packaged as a Python library. This quickstart uses the ngrok Rust SDK to create an agent endpoint that forwards traffic from the internet to a Rust app running on your local device, then secure it by requiring visitors to log in with a Google account to access it.
If you’d prefer to skip the boilerplate setup, you can clone the complete example from the ngrok-samples collection. In that case, you’ll just need to reserve a domain and add your auth token as described below to get started.

What you’ll need

1. Start your app or service

Start up the app or service you’d like to put online. This is the app that your agent endpoint will forward online traffic to. If you don’t have an app to work with, you can set up a basic HTTP server at port 8080. First, create a directory for your Rust project and navigate into it:
mkdir ngrok-rust-server
cd ngrok-rust-server
Next, create a new Rust project:
cargo init
Replace the contents of src/main.rs with the following code to set up a basic HTTP server:
ngrok-rust-server/src/main.rs
use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream};

fn handle_connection(mut stream: TcpStream) {
    let mut buffer = [0; 512];

    // Read from the stream
    if let Ok(_) = stream.read(&mut buffer) {
        let body = "Hello from Rust HTTP Server!";
        let response = format!(
            "HTTP/1.1 200 OK\r\n\
             Content-Length: {}\r\n\
             Content-Type: text/plain\r\n\
             Connection: close\r\n\r\n\
             {}",
            body.len(),
            body
        );

        if let Err(e) = stream.write_all(response.as_bytes()) {
            eprintln!("Write error: {}", e);
        }

        // Flush to make sure the response is sent
        if let Err(e) = stream.flush() {
            eprintln!("Flush error: {}", e);
        }
    }
}

fn main() -> std::io::Result<()> {
    let listener = TcpListener::bind("127.0.0.1:8080")?;
    println!("Server running at http://127.0.0.1:8080");

    for stream in listener.incoming() {
        match stream {
            Ok(stream) => handle_connection(stream),
            Err(e) => eprintln!("Connection failed: {}", e),
        }
    }

    Ok(())
}
Navigate to the root directory of the project and run the following command to start the server:
cargo run

2. Install the Rust SDK

Open a new terminal, then run the following commands to create a new Rust project install the Rust SDK:
mkdir ngrok-rust-demo
cd ngrok-rust-demo
cargo init
cargo add ngrok
Edit your Cargo.toml file to include the necessary dependencies:
ngrok-rust-demo/Cargo.toml
[package]
name = "ngrok-rust-demo"
version = "0.1.0"
edition = "2021"

[dependencies]
ngrok = {version = "0.14.0"}
tokio = { version = "1", features = [
    "full"
] }
axum = { version = "0.7.4", features = ["tokio"] }
async-trait = "0.1.59"
hyper = {version = "1", features = ["full"]}
hyper-util = { version = "0.1", features = [
	"full"
] }
url = "2.5.4"

3. Create your endpoint

Create your agent endpoint, which will forward public traffic to your app. In the ngrok-rust-demo directory you created in the previous step, add the following code to your src/main.rs file. This example:
  • Starts an Agent endpoint that forwards from your reserved domain to your service running on port 8080.
  • Secures the endpoint with a Traffic Policy that requires authentication via Google OAuth.
This example uses ngrok’s default Google OAuth application. To use your own, see the OAuth Traffic Policy Action documentation.
ngrok-rust-demo/src/main.rs
#![deny(warnings)]
use ngrok::config::ForwarderBuilder;
use url::Url;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    // Set up ngrok tunnel
    let session = ngrok::Session::builder()
        .authtoken_from_env()
        .connect()
        .await?;

    let domain = "your-reserved-domain";

    // Forward HTTP traffic from ngrok to the local server
    let _listener = session
        .http_endpoint()
        .domain(domain)
        .traffic_policy(r#"{"on_http_request": [{"actions": [{"type": "oauth","config": {"provider": "google"}}]}]}"#)
        .listen_and_forward(Url::parse("http://localhost:8080").unwrap())
        .await?;

    println!("Ngrok tunnel established at {}", domain);

    // Wait indefinitely
    tokio::signal::ctrl_c().await?;
    Ok(())
}

4. Test your endpoint

Test your endpoint by running the following terminal command, swapping in your auth token:
NGROK_AUTHTOKEN=$YOUR_AUTHTOKEN_HERE cargo run
This should print your reserved domain URL to the terminal. When you visit the URL, you should be prompted to log in with Google. After logging in, you’ll see your app or service. If you used the example app in this quickstart, you’ll see “Hello from Rust HTTP Server!” displayed in your browser.

What’s next?

In this guide, you learned how to use the Rust SDK to an create agent endpoint that forwards traffic to your localhost. You saw one way to implement a traffic policy directly in your codebase, including an action that adds authentication to your app with no configuration required. What else can you do with these features?