---
title: Build Vercel Functions with the Rust runtime
description: Create Rust handlers in api/ with vercel_runtime 2.x, parse JSON requests, run background tasks, configure Fluid compute settings, and deploy to Vercel.
url: "https://vercel.com/kb/guide/vercel-functions-on-rust"
published: 2026-12-04
last_updated: 2026-12-04
authors: Ben Sabic
related_resources:
  - title: "Deploy Rust on Vercel with Docker"
    url: "/kb/guide/deploy-rust-on-vercel-with-docker"
    description: "Build a Rust application with Axum and Docker, then deploy it to Vercel Functions. Learn how to configure environment variables, managed storage, and preview deployments for your project."
  - title: "Fluid Compute"
    url: "https://vercel.com/academy/optimize-your-vercel-account/fluid-compute"
    description: "Turn on Fluid compute, redeploy, and confirm in Observability that Active CPU time drops well below wall time."
install_vercel_plugin: npx plugins add vercel/vercel-plugin
search_with_vercel_cli: npx vercel@latest kb search "<query>"
read_with_vercel_cli: "npx vercel@latest kb inspect vercel-functions-on-rust"
---

Vercel's native [Rust runtime](https://vercel.com/docs/functions/runtimes/rust) builds Rust handlers into [Vercel Functions](https://vercel.com/docs/functions) that run on [Fluid compute](https://vercel.com/docs/fluid-compute). The [`vercel_runtime`](https://docs.rs/vercel_runtime/latest/vercel_runtime/) 2.x crate connects each handler to the runtime, which is in Beta on all plans.

You can deploy Rust API endpoints directly from source without maintaining a container image. If your application needs custom Linux dependencies, an existing Docker build, or [service bindings](https://vercel.com/docs/services/bindings), [deploy it with Docker](https://vercel.com/kb/guide/deploy-rust-on-vercel-with-docker).

## Prerequisites

Before you start, make sure you have a [Vercel account](https://vercel.com/signup). For local development, install the latest [Vercel CLI](https://vercel.com/docs/cli) and the current stable Rust toolchain with [rustup](https://rustup.rs).

## Build with your agent

Use this prompt in your application's repository to have a coding agent build and test a Rust endpoint that fits your existing project:

### Agent prompt

```txt
Help me add native Rust functions to this application on Vercel using https://vercel.com/kb/guide/vercel-functions-on-rust. Read and follow the guide using the Vercel CLI: `npx vercel@latest kb inspect vercel-functions-on-rust`.

Inspect the repository's framework, Rust crates, routes, and deployment configuration first. If the endpoint's purpose isn't clear, ask what input it should accept and what it should return. Build the selected endpoint using the project's existing conventions.

1. Use the current stable Rust toolchain and vercel_runtime 2.x. Add the required dependencies and a unique [[bin]] target for each handler in api/. Keep shared library code outside api/ and preserve existing Cargo targets and configuration.

2. Connect each native handler with service_fn and run. Return explicit HTTP statuses for expected errors, serialize JSON responses, and set the content type when constructing a Response. Validate input before performing database writes or other actions.

3. Preserve the application's authentication and authorization checks. Keep credentials in server environment variables and exclude secrets and raw internal errors from client responses. Identify missing database or service integrations instead of inventing them.

4. Use Axum when the selected feature needs related routes or shared middleware. Adapt the router to Vercel with VercelLayer and check how its routes fit the existing deployment before adding rewrites. Don't replace an application's routes with the guide's standalone catch-all configuration.

5. Check the workload against the guide's current runtime qualifications, including Beta status, duration, temporary storage, and service-binding support. Add background tasks only when needed and keep them within the invocation's duration limit.

6. Run formatting, compilation, and focused tests. Use vercel dev to exercise successful requests, invalid input, unsupported methods, and applicable permission failures. Report any checks you couldn't run and distinguish local results from hosted validation.

Return the changed files, required configuration, and test results. Explain how to run the endpoint locally and provide the remaining deployment steps with their target environment.

To find other KB guides, such as ones on related topics or next steps, search the Vercel Knowledge Base with the Vercel CLI: `npx vercel@latest kb search "<topic>"`
```

## 1\. Set up the project

Create the project folder with an `api` directory at its root:

```bash
mkdir vercel-rust-functions
cd vercel-rust-functions
mkdir api
```

Create `Cargo.toml` in the project root to define the package, dependencies, and binary target. The `hello` target points to `api/hello.rs`, which you'll add next:

```text
[package]
name = "vercel-rust-functions"
version = "0.1.0"
edition = "2024"

[dependencies]
tokio = { version = "1", features = ["full"] }
vercel_runtime = { version = "2" }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"

# Each handler has to be specified as [[bin]]
# Note that you need to provide unique names for each binary
[[bin]]
name = "hello"
path = "api/hello.rs"

[profile.release]
codegen-units = 1
lto = "fat"
opt-level = 3
```

`[[bin]]` entries tell Cargo which source files to build, while Vercel discovers the handlers in `api/`. Each entry needs a unique binary name and matching path. Vercel builds in release mode using the `[profile.release]` settings.

## 2\. Create your first handler

Create `api/hello.rs` with a handler that returns a JSON greeting. The async `main` function starts the runtime and registers that handler:

```rust
use serde_json::{Value, json};
use vercel_runtime::{Error, Request, run, service_fn};

#[tokio::main]
async fn main() -> Result<(), Error> {
    let service = service_fn(handler);
    run(service).await
}

async fn handler(_req: Request) -> Result<Value, Error> {
    Ok(json!({
        "message": "Hello, world!",
    }))
}
```

The runtime calls `handler` for incoming requests through the service created by `service_fn`. Its returned JSON becomes a `200` response, served at `/api/hello` without a `vercel.json` file.

## 3\. Run and test locally

Start [`vercel dev`](https://vercel.com/docs/cli/dev) from the project root. It compiles debug builds with your local toolchain and asks you to link the folder to a Vercel project if needed.

Add `--local` to skip project linking.

```bash
vercel dev
```

From a second terminal, call the greeting endpoint. Use the address printed by the server if it differs from `http://localhost:3000`:

```bash
curl -sS http://localhost:3000/api/hello
```

The response contains a JSON `message` field set to `Hello, world!`. For build failures or `404` responses, check the [handler configuration](#the-handler-fails-to-build-or-its-route-returns-404) before deploying.

## 4\. Deploy to Vercel

Deploy from the project root with [`vercel deploy`](https://vercel.com/docs/cli/deploy). The `--prod` flag sends this deployment to production; without it, a new project's first deployment still goes to production and subsequent deployments are previews:

```bash
vercel deploy --prod
```

The CLI excludes Cargo's `target` directory so Vercel builds from source. Call `/api/hello` at the deployment URL and confirm it returns the same JSON greeting as the local server. After adding or changing a handler, test it locally and redeploy to update the hosted endpoint.

To deploy from Git, add `target/` to `.gitignore` and commit `Cargo.toml`, `Cargo.lock`, and `api/` before importing the repository in Vercel. Include `vercel.json` if you've added custom configuration.

## Read request data and build custom responses

Handlers receive a `vercel_runtime::Request`, which is a `hyper::Request`. The inspection endpoint reads its method, path, query string, and country header, then returns them as JSON with `cache-control: no-store`.

Add a second binary below the `hello` entry in `Cargo.toml`:

```text
[[bin]]
name = "inspect"
path = "api/inspect.rs"
```

Create `api/inspect.rs`:

```rust
use serde_json::json;
use vercel_runtime::{Error, Request, Response, ResponseBody, run, service_fn};

fn header(req: &Request, name: &str) -> Option<String> {
    req.headers()
        .get(name)
        .and_then(|v| v.to_str().ok())
        .map(|s| s.to_owned())
}

#[tokio::main]
async fn main() -> Result<(), Error> {
    run(service_fn(handler)).await
}

async fn handler(req: Request) -> Result<Response<ResponseBody>, Error> {
    let method = req.method().to_string();
    let path = req.uri().path().to_owned();
    let query = req.uri().query().unwrap_or("").to_owned();
    let country = header(&req, "x-vercel-ip-country");

    let body = json!({
        "method": method,
        "path": path,
        "query": query,
        "country": country,
    });

    Ok(Response::builder()
        .status(200)
        .header("content-type", "application/json")
        .header("cache-control", "no-store")
        .body(body.to_string().into())?)
}
```

`req.uri().query()` returns the raw query string, unparsed. When you return a `Response`, `vercel_runtime` sends your status and headers as they are and adds no `content-type`, so set it yourself. The crate doesn't re-export `StatusCode`, so either pass numbers as shown or add `hyper` to `Cargo.toml` to use the named constants.

With the development server running, send a request that supplies a country header and query string:

```bash
curl -sS -i \
  -H "x-vercel-ip-country: US" \
  "http://localhost:3000/api/inspect?env=dev"
```

The response includes `cache-control: no-store` and reports the GET method, `/api/inspect` path, `env=dev` query, and US country header supplied in the request.

### Return-type conversions and error responses

The greeting relies on the runtime to turn a JSON value into a response, while the inspection endpoint sets its own headers. Choose a return type based on whether you need those automatic defaults or explicit control over the HTTP response:

| Return type                           | HTTP status           | Default `content-type`      |
| ------------------------------------- | --------------------- | --------------------------- |
| `serde_json::Value`                   | `200`                 | `application/json`          |
| `String` or `&str`                    | `200`                 | `text/plain`                |
| `Vec<u8>`                             | `200`                 | `application/octet-stream`  |
| `()`                                  | `204`                 | None                        |
| `StatusCode` (from `hyper` or `http`) | Matching status       | None (empty body)           |
| `Option<T>` (`None`)                  | `404`                 | None (`Not Found` body)     |
| `Response<ResponseBody>`              | Status set on builder | Only headers set on builder |

Returning `Err` from a handler wrapped in `service_fn` produces a `500` response that includes the error's display text. Keep secrets and raw database errors out of that message. For expected failures, return an explicit `4xx` response with a JSON-serialized body and log diagnostic details on the server.

## Parse a JSON POST body

The echo endpoint accepts a JSON object with a string `name` and an unsigned 32-bit integer `quantity`, then returns those fields without storing an item. It checks the HTTP method before reading the body and returns a client error if the request uses another method or the payload cannot be parsed into `ItemInput`.

Add `http-body-util` to the existing dependencies section in `Cargo.toml`, then add the `echo` binary entry. Keep the dependencies and targets already in the file:

```text
[dependencies]
# ...existing dependencies
http-body-util = "0.1"

[[bin]]
name = "echo"
path = "api/echo.rs"
```

Create `api/echo.rs` to handle POST requests and reject invalid input:

```rust
use http_body_util::BodyExt;
use serde::{Deserialize, Serialize};
use vercel_runtime::{Error, Request, Response, ResponseBody, run, service_fn};

#[derive(Deserialize)]
struct ItemInput {
    name: String,
    quantity: u32,
}

#[derive(Serialize)]
struct ItemResponse {
    name: String,
    quantity: u32,
}

#[tokio::main]
async fn main() -> Result<(), Error> {
    run(service_fn(handler)).await
}

async fn handler(req: Request) -> Result<Response<ResponseBody>, Error> {
    if req.method().as_str() != "POST" {
        return Ok(Response::builder()
            .status(405)
            .header("allow", "POST")
            .header("content-type", "application/json")
            .body(
                serde_json::json!({ "error": "Method not allowed" })
                    .to_string()
                    .into(),
            )?);
    }

    let bytes = req.into_body().collect().await?.to_bytes();
    let payload: ItemInput = match serde_json::from_slice(&bytes) {
        Ok(item) => item,
        Err(_) => {
            return Ok(Response::builder()
                .status(400)
                .header("content-type", "application/json")
                .body(
                    serde_json::json!({ "error": "Invalid JSON body" })
                        .to_string()
                        .into(),
                )?);
        }
    };

    let response = ItemResponse {
        name: payload.name,
        quantity: payload.quantity,
    };

    Ok(Response::builder()
        .status(200)
        .header("content-type", "application/json")
        .body(serde_json::to_string(&response)?.into())?)
}
```

[`BodyExt::collect`](https://docs.rs/http-body-util/latest/http_body_util/trait.BodyExt.html) reads the full request body into memory before [`serde_json::from_slice`](https://docs.rs/serde_json/latest/serde_json/fn.from_slice.html) parses it into `ItemInput`. Rust functions accept [request bodies up to 4.5 MB](https://vercel.com/docs/functions/limitations). Returning an explicit `400` for a bad payload keeps raw parsing errors out of a `500` response.

From another terminal, check valid input, a missing field, and an unsupported GET request while the development server is running:

```bash
# Valid JSON body
curl -sS -i -X POST http://localhost:3000/api/echo \
  -H "content-type: application/json" \
  -d '{"name":"widget","quantity":3}'

# Missing quantity
curl -sS -i -X POST http://localhost:3000/api/echo \
  -H "content-type: application/json" \
  -d '{"name":"widget"}'

# Unsupported GET request
curl -sS -i http://localhost:3000/api/echo
```

The valid request returns `200` with the submitted name and quantity. Omitting `quantity` returns `400` with an `Invalid JSON body` error. Sending GET returns `405` and an `Allow: POST` header.

## Run background tasks and request-scoped logs

The background endpoint returns a JSON response while a registered task continues running. Its two-second delay lets you see the response arrive before the completion log. The handler receives `AppState` as a second argument to register work and associate its logs with the request.

Add a `background` binary to `Cargo.toml`:

```text
[[bin]]
name = "background"
path = "api/background.rs"
```

Create `api/background.rs` using `state.wait_until` to register the task. This starts the work immediately and lets it continue after the handler returns its response:

```rust
use serde_json::{Value, json};
use vercel_runtime::{AppState, Error, Request, run, service_fn};

#[tokio::main]
async fn main() -> Result<(), Error> {
    run(service_fn(handler)).await
}

async fn handler(_req: Request, state: AppState) -> Result<Value, Error> {
    state
        .log_context
        .info("Accepted request, scheduling background work");

    let log_context = state.log_context.clone();
    state.wait_until(async move {
        tokio::time::sleep(std::time::Duration::from_secs(2)).await;
        log_context.info("Background work finished");
    });

    Ok(json!({ "status": "accepted" }))
}
```

Clone `state.log_context` into the background task to keep its logs associated with the request. The logging methods include `info`, `warn`, `error`, and `debug`; the runtime keeps the invocation open until its registered work finishes.

Call the background endpoint and watch for its log in the server terminal:

```bash
curl -sS http://localhost:3000/api/background
```

The endpoint returns `200` with an `accepted` status in the JSON body before the task finishes. About two seconds later, the server logs `Background work finished`.

On Vercel, the response and background work share the function's `maxDuration`. During local development, shutdown waits up to 30 seconds for pending tasks. Use [Vercel Workflows](https://vercel.com/docs/workflows) for multi-step work that must outlive one invocation.

## Configure duration, memory, and regions

For a project that includes the background handler, you can customize [duration](https://vercel.com/docs/functions/configuring-functions/duration) and [regions](https://vercel.com/docs/functions/configuring-functions/region) with a `vercel.json` file in the root. This configuration lowers the default duration to 60 seconds for background work and 30 seconds for the other Rust handlers, all in Washington, D.C. (`iad1`).

List exact paths before broader globs because [function settings](https://vercel.com/docs/project-configuration/vercel-json#functions) use the first match:

```json
{
  "$schema": "https://openapi.vercel.sh/vercel.json",
  "regions": ["iad1"],
  "functions": {
    "api/background.rs": {
      "maxDuration": 60,
      "regions": ["iad1"]
    },
    "api/*.rs": {
      "maxDuration": 30
    }
  }
}
```

Redeploy after saving `vercel.json` to apply the changes. Rust functions on Fluid compute have these defaults and plan limits:

| Setting          | Default                                    | Available changes                                                                                                                                                                                                                        |
| ---------------- | ------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Maximum duration | 300 seconds                                | Hobby supports up to 300 seconds; Pro and Enterprise support up to 800 seconds.                                                                                                                                                          |
| Region           | Washington, D.C. (`iad1`) for new projects | Choose a [region near your data](https://vercel.com/docs/regions#region-list). Hobby supports one region; Pro and Enterprise support [multiple regions](https://vercel.com/docs/functions/configuring-functions/region#limits).          |
| Memory and CPU   | 2 GB and 1 vCPU                            | Pro and Enterprise can use 4 GB and 2 vCPUs. Change [function memory](https://vercel.com/docs/functions/configuring-functions/memory) in the project settings and redeploy; Fluid compute does not accept this setting in `vercel.json`. |

## Serve an Axum router from one function

Use Axum's routing, middleware, and extractors to serve several endpoints from one Vercel Function. Enable the `axum` feature of `vercel_runtime` to connect the router to the runtime. Keeping these routes in one function also leaves room within Hobby's 12-function deployment limit.

### Set up the Axum project

Create a separate project with an `api` directory for Axum's catch-all rewrite, then add `Cargo.toml` at the root to enable the runtime's `axum` feature:

```text
[package]
name = "vercel-rust-axum"
version = "0.1.0"
edition = "2024"

[dependencies]
vercel_runtime = { version = "2.4", features = ["axum"] }
tokio = { version = "1", features = ["full"] }
axum = { version = "0.8" }
tower = { version = "0.5" }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"

[[bin]]
name = "axum"
path = "api/axum.rs"

[profile.release]
codegen-units = 1
lto = "fat"
opt-level = 3
```

Create `api/axum.rs` with the `/` and `/users` routes. `VercelLayer` adapts the router for `vercel_runtime::run`, allowing requests to reach Axum's handlers:

```rust
use axum::{
    Json, Router,
    response::IntoResponse,
    routing::{get, post},
};
use serde::{Deserialize, Serialize};
use tower::ServiceBuilder;
use vercel_runtime::{Error, axum::VercelLayer};

#[derive(Deserialize)]
struct CreateUser {
    name: String,
}

#[derive(Serialize)]
struct UserResponse {
    name: String,
}

async fn home() -> &'static str {
    "Axum on Vercel"
}

async fn create_user(Json(payload): Json<CreateUser>) -> impl IntoResponse {
    Json(UserResponse { name: payload.name })
}

#[tokio::main]
async fn main() -> Result<(), Error> {
    let router = Router::new()
        .route("/", get(home))
        .route("/users", post(create_user));

    let app = ServiceBuilder::new()
        .layer(VercelLayer::new())
        .service(router);

    vercel_runtime::run(app).await
}
```

### Route requests to the function

Add `vercel.json` with a [rewrite](https://vercel.com/docs/project-configuration/vercel-json#rewrites) that sends every incoming path to `/api/axum`. The rewrite selects the Vercel Function, and Axum uses the original path to match `/` or `/users` within the router:

```json
{
  "$schema": "https://openapi.vercel.sh/vercel.json",
  "rewrites": [
    {
      "source": "/(.*)",
      "destination": "/api/axum"
    }
  ]
}
```

### Test the router

Stop the greeting server and run `vercel dev` from the Axum project's root. In a second terminal, test `/` and `/users` without the `/api/axum` prefix.

Replace `http://localhost:3000` if the server prints a different address:

```bash
curl -sS http://localhost:3000/

curl -sS -i -X POST http://localhost:3000/users \
  -H "content-type: application/json" \
  -d '{"name":"Ada"}'
```

The GET request returns `Axum on Vercel`. The POST request returns `200` with the submitted name as JSON; it does not save a user record. Then [deploy the Axum project](#4.-deploy-to-vercel) from its root and repeat both requests at its deployment URL.

`VercelLayer` collects the request body before passing it to Axum. For ordinary HTTP responses, it streams bodies with a `content-type` containing `text/event-stream` or `application/json` and buffers other content types. Use [`stream_response`](https://docs.rs/crate/vercel_runtime/2.4.1/source/src/axum/mod.rs) to send server-sent events through a channel.

## Build before deploying

Use a prebuilt deployment when you want to build the function binaries on your own build machine and upload the resulting artifacts. Install [`cargo-zigbuild`](https://github.com/rust-cross/cargo-zigbuild) [and Zig](https://github.com/rust-cross/cargo-zigbuild) on Linux or macOS so the Rust builder can cross-compile the binaries for Linux.

> **Note:**
>
> Prebuilt Rust deployments are not supported from Windows. Build on Linux or macOS, or deploy source with `vercel deploy --prod`.

Pull the production settings, [build the deployment](https://vercel.com/docs/cli/build), and [upload the prebuilt output](https://vercel.com/docs/cli/deploying-from-cli):

```bash
vercel pull --environment=production
vercel build --prod
vercel deploy --prebuilt --prod
```

The build writes function binaries and deployment configuration to `.vercel/output`. The CLI uploads those artifacts without rebuilding the source on Vercel.

## What can you build with Rust functions?

Rust functions let a web frontend call Rust code through HTTP. They fit request-driven tasks such as validating an order or receiving an event from another service, provided the work stays within the function's duration and resource limits.

### Receive and verify webhooks

GitHub webhooks can update your app when an issue opens or a pull request merges. Before processing an event, [verify its signature](https://docs.github.com/en/webhooks/using-webhooks/validating-webhook-deliveries) against the unchanged request body. Store the secret configured in GitHub as `GITHUB_WEBHOOK_SECRET` in your function's [environment variables](https://vercel.com/docs/environment-variables).

From the greeting project's root, add the dependencies for signature verification:

```bash
cargo add hmac@0.13 sha2@0.11 hex@0.4
```

Create `src/lib.rs` to check GitHub's signature format and verify the payload with the HMAC library's constant-time comparison:

```rust
use hmac::{Hmac, KeyInit, Mac};
use sha2::Sha256;

pub fn verify_github_signature(
    secret: &[u8],
    signature: &str,
    body: &[u8],
) -> bool {
    let Some(encoded) = signature.strip_prefix("sha256=") else {
        return false;
    };
    let Ok(tag) = hex::decode(encoded) else {
        return false;
    };
    if secret.is_empty() {
        return false;
    }

    let mut mac = Hmac::<Sha256>::new_from_slice(secret)
        .expect("HMAC accepts keys of any length");
    mac.update(body);
    mac.verify_slice(&tag).is_ok()
}
```

Import the function into your webhook handler from `vercel_rust_functions`. Copy `X-Hub-Signature-256` into an owned string before consuming the request body, then pass the secret bytes, header value, and raw body bytes to the function. Reject missing or invalid signatures before parsing JSON, and return a server error if the secret is missing or empty.

Signature verification doesn't prevent duplicate deliveries. Use [GitHub's delivery ID](https://docs.github.com/en/webhooks/using-webhooks/best-practices-for-using-webhooks#use-the-x-github-delivery-header) to avoid repeating completed actions, with the processing status recorded in durable storage. For lengthy processing, acknowledge the event after a durable queue accepts it and let a worker perform the remaining work.

### Validate submitted data

Typed JSON parsing catches missing fields and incompatible values, but your application still needs business rules. For an order form, require a nonblank item name and a quantity from 1 to 100. Add this check to `api/echo.rs` after parsing `ItemInput` and before constructing `ItemResponse`:

```rust
if payload.name.trim().is_empty()
        || !(1..=100).contains(&payload.quantity)
    {
        return Ok(Response::builder()
            .status(422)
            .header("content-type", "application/json")
            .body(
                serde_json::json!({
                    "error": concat!(
                        "Name must not be blank and ",
                        "quantity must be between 1 and 100"
                    )
                })
                .to_string()
                .into(),
            )?);
    }
```

Requests that parse successfully but fail these rules now return `422`. Missing fields or values that don't fit the Rust types still return `400`, including negative quantities. Valid input returns `200` with the submitted values; the handler doesn't save an order, so add persistence only after validation succeeds.

### Expose a Rust library through HTTP

If your application already uses Rust for parsing or calculations, a function can expose that code to a web frontend. For example, the [`url`](https://docs.rs/url/latest/url/) [crate](https://docs.rs/url/latest/url/) can extract a submitted URL's host and path without fetching the address. Add the dependency and binary target to the greeting project's `Cargo.toml`, keeping the existing entries:

```text
[dependencies]
# Keep existing dependencies.
url = "2"

[[bin]]
name = "url"
path = "api/url.rs"
```

Create `api/url.rs` to read the `url` query parameter and return the parsed fields. This handler accepts HTTP and HTTPS URLs with a host and rejects input it can't parse into that form:

```rust
use serde_json::json;
use url::Url;
use vercel_runtime::{
    Error, Request, Response, ResponseBody, run, service_fn,
};

#[tokio::main]
async fn main() -> Result<(), Error> {
    run(service_fn(handler)).await
}

async fn handler(req: Request) -> Result<Response<ResponseBody>, Error> {
    let query = req.uri().query().unwrap_or("");
    let input = url::form_urlencoded::parse(query.as_bytes())
        .find(|(name, _)| name == "url")
        .map(|(_, value)| value);
    let parsed = input
        .and_then(|value| Url::parse(&value).ok())
        .filter(|url| {
            matches!(url.scheme(), "http" | "https") && url.has_host()
        });
    let (status, body) = match parsed {
        Some(url) => (200, json!({
            "scheme": url.scheme(),
            "host": url.host_str(),
            "path": url.path(),
        })),
        None => (400, json!({
            "error": "Provide an absolute HTTP or HTTPS URL with a host"
        })),
    };

    Ok(Response::builder()
        .status(status)
        .header("content-type", "application/json")
        .body(body.to_string().into())?)
}
```

With the development server running, call `/api/url` with its `url` query parameter set to `https://example.com/docs`. The response is `200` with the scheme, host, and path as separate JSON fields. Missing input or a URL such as `file:///tmp/data` returns `400`; the handler makes no outbound request.

### Combine responses from external APIs

An account page might need a customer's profile from one service and their subscription status from another. Fetch both in a Rust handler and return only the fields the frontend needs. Keep upstream credentials on the server and check that the caller can access the requested account.

Independent requests can run concurrently with [`tokio::try_join!`](https://docs.rs/tokio/latest/tokio/macro.try_join.html). Set [HTTP client timeouts](https://docs.rs/reqwest/latest/reqwest/struct.ClientBuilder.html#method.timeout) within the function's duration budget and decide whether an upstream failure should fail the whole response or leave an optional field unavailable. `try_join!` returns on the first error, so handle optional failures inside their request branches if partial results are acceptable.

### Build a multi-route backend with Axum

For a backend with related endpoints, keep account lookups and settings updates in one router with shared authentication middleware. The [Axum implementation](#serve-an-axum-router-from-one-function) shows how to route multiple paths to one Vercel Function and use typed request extractors. Add your database operations behind those handlers and enforce account permissions before reading or changing records.

## Use Rust in enterprise applications

In an internal quoting app, a Rust function can calculate prices using your company's rules while a web frontend collects the inputs. Employees should see only the customers they manage, and discounts above an agreed threshold may need a manager's approval.

### Reuse existing business logic

Keep pricing calculations in a shared Rust crate so internal apps use the same rules. In the [Axum project](#serve-an-axum-router-from-one-function), create `src/pricing.rs` and export it by adding `pub mod pricing;` to `src/lib.rs`. This function calculates a proposed quote and flags discounts above 10% for approval:

```rust
use serde::Serialize;

#[derive(Debug, Serialize)]
pub struct Quote {
    pub total_cents: u64,
    pub approval_required: bool,
    pub rule_version: &'static str,
}

pub fn calculate_quote(
    subtotal_cents: u64,
    discount_percent: u8,
) -> Result<Quote, &'static str> {
    if discount_percent > 100 {
        return Err("Discount must be between 0 and 100");
    }

    // Round the discount down to a whole cent.
    let discount_cents =
        u128::from(subtotal_cents) * u128::from(discount_percent) / 100;

    Ok(Quote {
        total_cents: subtotal_cents - discount_cents as u64,
        approval_required: discount_percent > 10,
        rule_version: "pricing-v1",
    })
}
```

Amounts use integer cents, and fractional-cent discounts round down. For a $100 subtotal, a 10% discount returns $90 without requiring approval; 11% returns $89 with approval required. The function doesn't save or approve a quote, so the operation that issues it must enforce that requirement.

Assign rule changes to the pricing team and test them against known quotes before deployment. Update the rule version when calculations change, and review request and response changes with the teams that call the API so a pricing update doesn't break their workflows.

### Control employee access

For employee-facing apps on Vercel, [Vercel Passport](https://vercel.com/docs/passport) requires sign-in through your company's identity provider before a visitor reaches a protected deployment. Passport is available on Enterprise plans and controls app access; your application still decides which customer records and approval actions each employee may use.

If the frontend forwards Passport identity to a separate Rust backend, [verify the token as a signed JWT](https://vercel.com/docs/passport/verify-identity#verify-tokens-outside-javascript) before trusting it. Check its signature and required claims against the expected source project and environment, then map the verified identity to your application's employee record.

The quote handler uses two application-owned types that you connect to your existing authentication and database code:

- Implement `VerifiedEmployee` in `src/auth.rs` as an Axum request extractor. It must reject missing or invalid credentials with `401` and provide the internal employee `id` after verification. For Passport, use the verified issuer and subject together to look up that employee.
  
- Implement `QuoteStore` in `src/store.rs` as a cloneable database adapter. Its async `can_quote` method returns `Result<bool, E>` from employee-to-customer assignments. Its async `subtotal_cents` method returns `Result<Option<u64>, E>` from stored pricing data. Propagate failures from both queries so the handler returns an error response.
  

Create `src/quotes.rs` with the handler, then export the `auth`, `store`, and `quotes` modules from `src/lib.rs`. In `api/axum.rs`, merge its routes into the existing router before applying `VercelLayer`, passing your initialized database adapter:

```rust
use axum::{
    Json, Router,
    extract::{Path, State},
    http::StatusCode,
    routing::post,
};
use serde::Deserialize;

// These two modules belong to your application.
use crate::{auth::VerifiedEmployee, store::QuoteStore};
use crate::pricing::{Quote, calculate_quote};

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct QuoteInput {
    discount_percent: u8,
}

// Merge into the existing router before applying VercelLayer:
// .merge(vercel_rust_axum::quotes::routes(store))
pub fn routes(store: QuoteStore) -> Router {
    Router::new()
        .route("/customers/{customer_id}/quote", post(quote))
        .with_state(store)
}

async fn quote(
    employee: VerifiedEmployee,
    State(store): State<QuoteStore>,
    Path(customer_id): Path<String>,
    Json(input): Json<QuoteInput>,
) -> Result<Json<Quote>, StatusCode> {
    let allowed = store
        .can_quote(&employee.id, &customer_id)
        .await
        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

    if !allowed {
        return Err(StatusCode::FORBIDDEN);
    }

    let subtotal = store
        .subtotal_cents(&customer_id)
        .await
        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
        .ok_or(StatusCode::NOT_FOUND)?;

    calculate_quote(subtotal, input.discount_percent)
        .map(Json)
        .map_err(|_| StatusCode::UNPROCESSABLE_ENTITY)
}
```

Send a POST request to `/customers/customer_123/quote` with a JSON body containing only `discount_percent`. The handler reads the subtotal from the database after checking access; the caller cannot supply an employee ID or override the stored price.

Employees without access receive `403` before the subtotal is read. Valid requests return the proposed quote as JSON, while discounts above 100% return `422`. Approving or issuing a quote needs a separate permission check and durable approval record tied to the quote's contents and pricing-rule version.

### Track changes and business actions

Record the verified employee ID, quote ID, pricing-rule version, and outcome for each calculation or approval. These records let your team explain which rules produced a price and who approved an exception. When saving a proposed quote, assign its ID and store the audit record alongside it in durable storage with appropriate access and retention policies.

Use [request-scoped logs](#run-background-tasks-and-request-scoped-logs) to investigate failed calculations and upstream errors. Log identifiers that let you find the corresponding audit record without copying entire customer records or authentication tokens into the logs.

## Limitations

- The Rust runtime is in Beta.
  
- Native Rust functions cannot consume [service bindings](https://vercel.com/docs/services/bindings). [Run Rust in a container](https://vercel.com/kb/guide/deploy-rust-on-vercel-with-docker) if your service needs them.
  
- The [extended max duration beta](https://vercel.com/docs/functions/configuring-functions/duration#extended-max-duration-beta), up to 1,800 seconds, doesn't cover Rust.
  
- Prebuilt Rust deployments require a Linux or macOS build machine; Windows can still deploy source for Vercel to build.
  
- The filesystem is read-only except for up to 500 MB in `/tmp`. Treat those files as temporary: they are lost when the function instance stops.
  

## Troubleshooting

### The handler fails to build or its route returns 404

For build failures, check that each handler has a `[[bin]]` entry in `Cargo.toml` with a unique name and the correct file path. Missing or duplicate targets can prevent compilation. If the deployment succeeds but the route returns `404`, check the URL and any rewrite that could send the request elsewhere.

### Community runtime code fails to compile

These errors can occur with code written for the deprecated `vercel-community/rust` runtime. Version 2.x no longer exports `Body` or `StatusCode`, and `run` expects a service rather than a bare handler.

Wrap the handler with `service_fn(handler)` and use a supported return type, such as `Response<ResponseBody>`. Add `hyper` if you need its named status constants, and remove any legacy `"runtime": "vercel-rust@..."` entry from `vercel.json` when moving to the native runtime.

### Compilation fails on edition 2024 or let chains

Check your compiler with `rustc --version` and update the stable toolchain with `rustup update stable`. The runtime uses language features newer than the minimum required for the 2024 edition. If the project pins a toolchain in `rust-toolchain.toml`, update that pin too.

## Next steps

- Explore [Rust runtime configuration](https://vercel.com/docs/functions/runtimes/rust) for your application.
  
- [Deploy Rust with Docker](https://vercel.com/kb/guide/deploy-rust-on-vercel-with-docker) when you need a container build.
  
- Understand how [Fluid compute scales and bills functions](https://vercel.com/docs/fluid-compute).
  
- Start a project from the [Hello World](https://vercel.com/templates/template/rust-hello-world) or [Axum](https://vercel.com/templates/template/rust-axum) template.
  
- Adapt [Rust streaming and background-task handlers](https://github.com/vercel/examples/tree/main/rust) for your API.

## Related Resources

- [Deploy Rust on Vercel with Docker](/kb/guide/deploy-rust-on-vercel-with-docker): Build a Rust application with Axum and Docker, then deploy it to Vercel Functions. Learn how to configure environment variables, managed storage, and preview deployments for your project.
- [Fluid Compute](https://vercel.com/academy/optimize-your-vercel-account/fluid-compute): Turn on Fluid compute, redeploy, and confirm in Observability that Active CPU time drops well below wall time.

## More Vercel Functions guides

- [Build an AI app with Rust and Vercel AI Gateway](/kb/guide/build-ai-app-with-rust-and-ai-gateway): Build a support chat app with a Next.js AI SDK UI frontend, a Rust Vercel Function that streams UI message events, and AI Gateway for model calls.
- [Migrate from Netlify Blobs to Vercel Blob](/kb/guide/migrate-from-netlify-blobs-to-vercel-blob): Migrate from Netlify Blobs to Vercel Blob, including stores, private and public access, metadata, conditional writes, a copy script, and a staged cutover.
- [Migrate a Python API from Railway to Vercel](/kb/guide/migrate-a-python-api-from-railway-to-vercel): Move a FastAPI, Flask, or Django API from Railway to Vercel Functions. Replace railway.json start commands, volumes, Celery workers, and cron services.

## Reference Architecture

Choose a stack and work through the decisions behind it, with curated documentation, guides, templates, and courses to help you build.

- [Agent stack](/kb/architecture/agents): Build and operate agents with models, tools, and durable workflows.
- [Web applications](/kb/architecture/web): Choose rendering, data, authentication, and caching approaches.
- [Backends](/kb/architecture/backends): Choose a runtime, connect services, and run background work.

[Browse all stacks](/kb/architecture)

## Build with prompts

Build an app, extend an agent, or improve your project with ready-to-use prompts for your coding agent.

[Browse the prompt library](/kb/prompts) · [Read the Markdown index](/kb/prompts.md)

## Search guides from your terminal

Search the Knowledge Base and read guides as Markdown with the Vercel CLI. No login required.

```bash
# Find guides by keyword
npx vercel@latest kb search "rewrites and redirects"
npx vercel@latest kb search "AI SDK streaming"

# Show the latest guides
npx vercel@latest kb

# Print a guide as Markdown, by slug or URL
npx vercel@latest kb inspect <guide>
```
