> ## Documentation Index
> Fetch the complete documentation index at: https://ngrok.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Rust SDK Quickstart

> Learn how to get started with the ngrok Rust SDK to create secure tunnels from your Rust applications to the internet.

<Prompt description="Give this to your AI coding agent to complete the full quickstart automatically." actions={["copy", "cursor"]}>
  Complete the ngrok Rust SDK quickstart:

  1. Create a Rust HTTP server project at `ngrok-rust-server/` on port 8080 that responds "Hello from Rust HTTP Server!"
  2. Create a second Rust project at `ngrok-rust-demo/` and add these dependencies to `Cargo.toml`: ngrok (0.14.0), tokio, axum, async-trait, hyper, hyper-util, and url
  3. Implement `src/main.rs` using `ngrok::Session::builder().authtoken_from_env()` and `session.http_endpoint()` to tunnel port 8080 to a reserved domain with a Google OAuth traffic policy — hardcode the domain string directly in the source
  4. Run `cargo run` in the server project in one terminal
  5. Run `NGROK_AUTHTOKEN=<token> cargo run` in the demo project in another
  6. Confirm the tunnel URL is printed and that visiting it requires a Google login

  Ask me for my auth token and reserved domain before starting — the auth token is passed at runtime via env var, the domain is set directly in `src/main.rs`.
</Prompt>

[The ngrok Rust SDK](https://docs.rs/ngrok/latest/ngrok/) is an open-source package that enables you to quickly and efficiently serve Rust 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](/getting-started/) packaged as a Rust 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.

<Info>
  If you'd prefer to skip the boilerplate setup, you can clone the complete example from the [ngrok-samples collection](https://github.com/ngrok-samples/rust-quickstart).
  In that case, you'll just need to reserve a domain and add your auth token as described below to get started.
</Info>

## What you'll need

* An [ngrok account](https://dashboard.ngrok.com/signup).
* Your [ngrok auth token](https://dashboard.ngrok.com/get-started/your-authtoken).
* [Rust installed](https://www.rust-lang.org/tools/install) on your machine. You can check this by running `rustc --version` in your terminal.

## 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:

```bash theme={null}
mkdir ngrok-rust-server
cd ngrok-rust-server
```

Next, create a new Rust project:

```bash theme={null}
cargo init
```

Replace the contents of `src/main.rs` with the following code to set up a basic HTTP server:

```rust title="ngrok-rust-server/src/main.rs" theme={null}
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:

```bash theme={null}
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:

```bash theme={null}
mkdir ngrok-rust-demo
cd ngrok-rust-demo
cargo init
cargo add ngrok
```

Edit your `Cargo.toml` file to include the necessary dependencies:

```toml title="ngrok-rust-demo/Cargo.toml" theme={null}
[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.

<Note>
  This example uses ngrok's default Google OAuth application.
  To use your own, see [the OAuth Traffic Policy Action documentation](/traffic-policy/actions/oauth/#google-example).
</Note>

```rust title="ngrok-rust-demo/src/main.rs" theme={null}
#![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](https://dashboard.ngrok.com/get-started/your-authtoken):

```bash theme={null}
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?

* Dig deeper into [Traffic Policies](/traffic-policy/), which enable you to [grant conditional access](/traffic-policy/examples/add-authentication/#conditional-access-using-oauth-variables), [send custom headers](/traffic-policy/actions/add-headers/#examples), [rewrite URLs](/traffic-policy/actions/url-rewrite/#examples), and more with your endpoints.
* Learn more about the [Agent SDKs](/agent-sdks/) to understand how the Rust SDK works under the hood.
* Check out [the ngrok Rust SDK repo](https://github.com/ngrok/ngrok-rust/tree/main?tab=readme-ov-file#ngrok-rust) for more code examples.
* If your use case calls for a centrally managed, always-on endpoint, instead of one that's only available when an agent is running, you should proceed to [getting started with Cloud Endpoints](/getting-started/cloud-endpoints-quickstart/).
