### Initialize Static Files Example Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/examples/actix-static-files.mdx This bash command initializes a new Shuttle project from a GitHub repository, specifically cloning the 'static-files' example from the 'actix-web' examples folder. Ensure you have the Shuttle CLI installed before running this command. ```bash shuttle init --from shuttle-hq/shuttle-examples --subfolder actix-web/static-files ``` -------------------------------- ### Initialize a New Shuttle Project Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/getting-started/quick-start.mdx Creates a new Shuttle project. You can choose from a 'Hello World' template, example projects, or pre-built templates. The 'Hello World' template is recommended for beginners. ```sh shuttle init ``` -------------------------------- ### Initialize WebSocket Example with Shuttle CLI Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/examples/axum-websockets.mdx This command initializes a new project by cloning the Shuttle examples, specifically the Axum WebSocket subfolder. It requires the Shuttle CLI to be installed. ```bash shuttle init --from shuttle-hq/shuttle-examples --subfolder axum/websocket ``` -------------------------------- ### Enable OpenTelemetry Exporter in Shuttle Project Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/docs/telemetry/getting-started.mdx This snippet shows how to add the `setup-otel-exporter` feature to the `shuttle-runtime` dependency in your project's `Cargo.toml` file. This is a prerequisite for enabling telemetry export in Shuttle. ```bash cargo add shuttle-runtime -F setup-otel-exporter ``` -------------------------------- ### Shuttle Runtime Cargo.toml Configuration Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/docs/telemetry/getting-started.mdx This snippet illustrates the expected format for the `shuttle-runtime` dependency in your `Cargo.toml` file after enabling the OpenTelemetry exporter feature. Ensure the `setup-exporter` feature is present in the features array. ```toml shuttle-runtime = { version = "0.56.0", features = ["setup-otel-exporter"] } ``` -------------------------------- ### Install Shuttle CLI (Windows) Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/getting-started/installation.mdx Installs the latest version of the Shuttle CLI on Windows using PowerShell. This script fetches and executes the installation command, simplifying the setup process. ```powershell iwr https://www.shuttle.dev/install-win | iex ``` -------------------------------- ### Bash: Initialize Project from Example Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/integrations/custom-resources.mdx This bash command initializes a new Shuttle project by cloning an example from a GitHub repository. It specifically targets the 'custom-resource/pdo' subfolder, allowing you to quickly set up the custom resource example. ```bash shuttle init --from https://github.com/shuttle-hq/shuttle-examples --subfolder custom-resource/pdo ``` -------------------------------- ### Initialize JWT Authentication Example Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/examples/rocket-jwt-authentication.mdx Initializes the JWT authentication example project using the shuttle CLI. This command clones the example from a specified repository and subfolder, setting up the necessary files for the Rocket JWT authentication example. ```bash shuttle init --from shuttle-hq/shuttle-examples --subfolder rocket/jwt-authentication ``` -------------------------------- ### Initialize Postgres Todo App Example Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/examples/rocket-postgres.mdx Command to initialize the Postgres Todo App example project using the Shuttle CLI. It clones the example from the shuttle-hq/shuttle-examples repository and specifies the rocket/postgres subfolder. ```bash shuttle init --from shuttle-hq/shuttle-examples --subfolder rocket/postgres ``` -------------------------------- ### Axum Router Setup Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/templates/tutorials/custom-service.mdx Builds an Axum `Router` with a single GET route for the root path ('/'). The handler for this route is `hello_world`, which returns a 'Hello world!' message with an OK status. ```rust use axum::http::StatusCode; use axum::response::IntoResponse; use axum::{routing::get, Router}; pub fn build_router() -> Router { Router::new().route("/", get(hello_world)) } pub async fn hello_world() -> impl IntoResponse { (StatusCode::OK, "Hello world!").into_response() } ``` -------------------------------- ### Install and Set Nightly Rust Toolchain Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/docs/builds.mdx This example demonstrates how to install the Rust nightly toolchain and set it as the default using `rustup`. This is useful for projects requiring features available only in the nightly build of Rust, executed as a pre-build hook. ```Shell ```sh shuttle_prebuild.sh rustup install nightly --profile minimal rustup default nightly ``` ``` -------------------------------- ### Initialize Shuttle Project with Qdrant Example Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/integrations/shuttle-qdrant.mdx Initializes a new Shuttle project using a pre-configured Axum + Qdrant example from a GitHub repository. This command clones the specified repository and checks out the 'axum/qdrant' subfolder. ```bash shuttle init --from shuttle-hq/shuttle-examples --subfolder axum/qdrant ``` -------------------------------- ### Initialize Actix Web Cookie Authentication Example Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/examples/actix-cookie-authentication.mdx Initializes the cookie authentication example for Actix Web by cloning the project from a specified GitHub repository and subfolder. This command requires the shuttle CLI to be installed. ```Bash shuttle init --from shuttle-hq/shuttle-examples --subfolder actix-web/cookie-authentication ``` -------------------------------- ### Deploy Example Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/examples/other.mdx Command to deploy the Shuttle project. ```bash shuttle deploy ``` -------------------------------- ### Rust: Basic Axum Hello World Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/templates/tutorials/authentication.mdx A minimal Axum application that sets up a router with a single GET route for '/hello' that returns 'Hello, world!'. This is the starting point for an Axum project on Shuttle. ```Rust use axum::{routing::get, Router}; async fn hello_world() -> &'static str { "Hello, world!" } #[shuttle_runtime::main] async fn axum() -> shuttle_axum::ShuttleAxum { let router = Router::new().route("/hello", get(hello_world)); Ok(router.into()) } ``` -------------------------------- ### Hello World - Salvo Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/examples/other.mdx This example demonstrates a 'Hello, world!' Rust application using the Salvo framework. It sets up a basic handler that renders plain text 'Hello, world!' and is prepared for deployment with Shuttle. ```rust use salvo::prelude::*; #[handler] async fn hello_world(res: &mut Response) { res.render(Text::Plain("Hello, world!")); } #[shuttle_runtime::main] async fn salvo() -> shuttle_salvo::ShuttleSalvo { let router = Router::new().get(hello_world); Ok(router.into()) } ``` -------------------------------- ### Bash: Initialize Shuttle Project with Axum Template Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/templates/tutorials/send-your-logs-to-datadog.mdx This bash command initializes a new Shuttle project using the Axum web framework template. It's the starting point for building a REST API with Shuttle and requires the Shuttle CLI to be installed. ```bash shuttle init --template axum ``` -------------------------------- ### Initialize Actix WebSocket Actorless Example Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/examples/actix-websocket-actorless.mdx Initializes the Actix WebSocket Actorless example project from a GitHub repository using the shuttle CLI. This command clones the specified repository and navigates to the correct subfolder. ```bash shuttle init --from shuttle-hq/shuttle-examples --subfolder actix-web/websocket-actorless ``` -------------------------------- ### Install Shuttle CLI from Source Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/getting-started/installation.mdx Installs the Shuttle CLI by building it directly from the source code using the Rust toolchain. This method requires a Rust toolchain to be installed and may take longer than other methods. ```sh cargo install cargo-shuttle ``` -------------------------------- ### Install libpq-dev for Postgres Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/support/troubleshooting.mdx This snippet addresses issues with missing libpq.so.5, often encountered with Postgres. It involves adding a `shuttle_setup_container.sh` script to your project to install the necessary runtime libraries using apt. ```Shell apt update && apt install -y libpq-dev ``` -------------------------------- ### Run Example Locally Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/examples/other.mdx Command to run the Shuttle project locally. ```bash shuttle run ``` -------------------------------- ### Hello World - Rama Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/examples/other.mdx A simple 'Hello, world!' Rust application using the Rama framework. It demonstrates handling forwarded headers to identify client IP addresses and returns a personalized greeting. This example is designed to be deployed with Shuttle. ```rust use rama::{ Context, Layer, error::ErrorContext, http:: StatusCode, layer::forwarded::GetForwardedHeaderLayer, service::web::{Router, response::Result}, }, net::forwarded::Forwarded, }; async fn hello_world(ctx: Context<()>) -> Result { Ok(match ctx.get::() { Some(forwarded) => format!( "Hello cloud user @ {}!", forwarded .client_ip() .context("missing IP information from user") .map_err(|err| (StatusCode::INTERNAL_SERVER_ERROR, err.to_string()))?, ), None => "Hello local user! Are you developing?".to_owned(), }) } #[shuttle_runtime::main] async fn main() -> Result { let router = Router::new().get("/", hello_world); let app = // Shuttle sits behind a load-balancer, // so in case you want the real IP of the user, // you need to ensure this headers is handled. // // Learn more at GetForwardedHeaderLayer::x_forwarded_for().into_layer(router); Ok(shuttle_rama::RamaService::application(app)) } ``` -------------------------------- ### HTML for Static File Example Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/examples/axum-static-files.mdx This is an example HTML file that serves as the homepage for the Axum static file serving example. It displays a simple message indicating that static files are being served. ```html Static Files

This is an example of serving static files with Axum and Shuttle.

``` -------------------------------- ### Install Shuttle CLI with binstall Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/templates/tutorials/websocket-chat-app-js.mdx Installs the Shuttle CLI using `cargo-binstall`, an alternative method for installing pre-compiled Cargo packages. This can be faster than building from source. ```bash cargo binstall cargo-shuttle ``` -------------------------------- ### Initialize Project with Shuttle CLI Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/examples/rocket-static-files.mdx This bash command initializes a new project using the Shuttle CLI. It clones example files from a specified GitHub repository and checks out a subfolder containing a Rocket static files example. ```bash shuttle init --from shuttle-hq/shuttle-examples --subfolder rocket/static-files ``` -------------------------------- ### Hello World - Thruster Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/examples/other.mdx This example showcases a 'Hello, world!' Rust application using the Thruster framework. It utilizes a middleware function to set the response body to 'Hello, World!' and is configured for Shuttle deployment. ```rust use thruster::{ context::basic_hyper_context::{generate_context, BasicHyperContext as Ctx, HyperRequest}, m, middleware_fn, App, HyperServer, MiddlewareNext, MiddlewareResult, ThrusterServer, }; #[middleware_fn] async fn hello(mut context: Ctx, _next: MiddlewareNext) -> MiddlewareResult { context.body("Hello, World!"); Ok(context) } #[shuttle_runtime::main] async fn thruster() -> shuttle_thruster::ShuttleThruster> { let server = HyperServer::new( App::::create(generate_context, ()).get("/", m![hello]), ); Ok(server.into()) } ``` -------------------------------- ### Install Shuttle CLI via cargo-binstall Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/getting-started/installation.mdx Installs the Shuttle CLI using the cargo-binstall tool, a package manager for Rust. This is an alternative method for users who prefer using Cargo. ```sh cargo binstall cargo-shuttle ``` -------------------------------- ### Hello World - Tower Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/examples/other.mdx A basic 'Hello, world!' Rust application using the Tower framework. It implements the `tower::Service` trait to handle HTTP requests and return a simple 'Hello, world!' response. This example is intended for deployment with Shuttle. ```rust use std::convert::Infallible; use std::future::Future; use std::pin::Pin; use std::task::{Context, Poll}; #[derive(Clone)] struct HelloWorld; impl tower::Service> for HelloWorld { type Response = hyper::Response; type Error = Infallible; type Future = Pin> + Send + Sync>>; fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll> { Poll::Ready(Ok(())) } fn call(&mut self, _req: hyper::Request) -> Self::Future { let body = hyper::Body::from("Hello, world!"); let resp = hyper::Response::builder() .status(200) .body(body) .expect("Unable to create the `hyper::Response` object"); let fut = async { Ok(resp) }; Box::pin(fut) } } #[shuttle_runtime::main] async fn tower() -> shuttle_tower::ShuttleTower { let service = HelloWorld; Ok(service.into()) } ``` -------------------------------- ### Hello World - Tide Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/examples/other.mdx A basic 'Hello, world!' Rust application using the Tide framework. It includes a logging middleware and defines a route that responds with 'Hello, world!'. This example is ready for deployment with Shuttle. ```rust #[shuttle_runtime::main] async fn tide() -> shuttle_tide::ShuttleTide<()> { let mut app = tide::new(); app.with(tide::log::LogMiddleware::new()); app.at("/").get(|_| async { Ok("Hello, world!") }); Ok(app.into()) } ``` -------------------------------- ### Prompting Best Practices for Shuttle MCP Server Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/integrations/mcp-server.mdx Example of how to prompt an AI assistant to utilize the Shuttle MCP server for up-to-date documentation and examples. This ensures the AI uses the most relevant Shuttle information. ```txt Build a Simple Todo App with Axum and then deploy it to Shuttle. Use the Shuttle MCP server. ``` -------------------------------- ### Initialize JWT Authentication Example with Shuttle Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/examples/axum-jwt-authentication.mdx Clone the JWT authentication example for Axum using the shuttle CLI. This command initializes a new project from a remote repository and specifies a subfolder. ```bash shuttle init --from shuttle-hq/shuttle-examples --subfolder axum/jwt-authentication ``` -------------------------------- ### Hello World - Warp Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/examples/other.mdx A straightforward 'Hello, world!' Rust application using the Warp framework. It defines a simple route that responds with 'Hello, World!' when accessed. This example is configured for deployment via Shuttle. ```rust use warp::Filter; use warp::Reply; #[shuttle_runtime::main] async fn warp() -> shuttle_warp::ShuttleWarp<(impl Reply,)> { let route = warp::any().map(|| "Hello, World!"); Ok(route.boxed().into()) } ``` -------------------------------- ### Axum CORS Layer Configuration (Basic) Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/templates/tutorials/rest-http-service-with-axum.mdx Configures a basic CORS policy for an Axum application using `CorsLayer` from `tower-http`. This example allows GET and POST methods and permits requests from any origin. It's a starting point for securing cross-origin requests. ```rust let cors = CorsLayer::new() // allow `GET` and `POST` when accessing the resource .allow_methods([Method::GET, Method::POST]) // allow requests from any origin .allow_origin(Any); ``` -------------------------------- ### Deploy Axum Web App with Shuttle Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/welcome/introduction.mdx Shows a minimal example of deploying a simple Axum web application on Shuttle. It includes a 'Hello, world!' endpoint and utilizes the `#[shuttle_runtime::main]` macro to handle the application's runtime and deployment, requiring minimal boilerplate code. ```Rust use axum::{routing::get, Router}; async fn hello_world() -> &'static str { "Hello, world!" } #[shuttle_runtime::main] async fn main() -> shuttle_axum::ShuttleAxum { let router = Router::new().route("/", get(hello_world)); Ok(router.into()) } ``` -------------------------------- ### Initialize SaaS Template Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/templates/fullstack/saas-template.mdx Initializes the SaaS starter template from a specified GitHub repository and subfolder. This command requires the 'shuttle' CLI tool to be installed. ```Shell shuttle init --from shuttle-hq/shuttle-examples --subfolder fullstack-templates/saas ``` -------------------------------- ### Rocket Postgres Todo App Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/examples/rocket-postgres.mdx Implements a TODO application using Rocket framework and SQLx with a PostgreSQL database. It includes routes for retrieving a to-do item by ID (GET /todo/) and creating a new to-do item (POST /todo) with a JSON body. The example requires Shuttle CLI and demonstrates database schema setup and management. ```rust #[macro_use] extern crate rocket; use rocket::response::status::BadRequest; use rocket::serde::json::Json; use rocket::State; use serde::{Deserialize, Serialize}; use shuttle_runtime::CustomError; use sqlx::{Executor, FromRow, PgPool}; #[get("/")] async fn retrieve(id: i32, state: &State) -> Result, BadRequest> { let todo = sqlx::query_as("SELECT * FROM todos WHERE id = $1") .bind(id) .fetch_one(&state.pool) .await .map_err(|e| BadRequest(e.to_string()))?; Ok(Json(todo)) } #[post("/", data = "")] async fn add( data: Json, state: &State, ) -> Result, BadRequest> { let todo = sqlx::query_as("INSERT INTO todos(note) VALUES ($1) RETURNING id, note") .bind(&data.note) .fetch_one(&state.pool) .await .map_err(|e| BadRequest(e.to_string()))?; Ok(Json(todo)) } struct MyState { pool: PgPool, } #[shuttle_runtime::main] async fn rocket(#[shuttle_shared_db::Postgres] pool: PgPool) -> shuttle_rocket::ShuttleRocket { pool.execute(include_str!("../schema.sql")) .await .map_err(CustomError::new)?; let state = MyState { pool }; let rocket = rocket::build() .mount("/todo", routes![retrieve, add]) .manage(state); Ok(rocket.into()) } #[derive(Deserialize)] struct TodoNew { pub note: String, } #[derive(Serialize, FromRow)] struct Todo { pub id: i32, pub note: String, } ``` ```sql DROP TABLE IF EXISTS todos; CREATE TABLE todos ( id serial PRIMARY KEY, note TEXT NOT NULL ); ``` ```toml [package] name = "postgres" version = "0.1.0" edition = "2021" [dependencies] rocket = { version = "0.5.0", features = ["json"] } serde = "1.0.148" shuttle-rocket = "0.56.0" shuttle-runtime = "0.56.0" shuttle-shared-db = { version = "0.56.0", features = ["postgres", "sqlx"] } sqlx = "0.8.2" tokio = "1.26.0" ``` -------------------------------- ### Axum Hello World Example Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/examples/axum.mdx This Rust code defines a simple Axum web server that responds with 'Hello, world!' to requests on the root path. It uses the `shuttle-runtime` to deploy the Axum router. Dependencies include `axum`, `shuttle-axum`, `shuttle-runtime`, and `tokio`. ```rust use axum::{ routing::get, Router }; async fn hello_world() -> &'static str { "Hello, world!" } #[shuttle_runtime::main] async fn main() -> shuttle_axum::ShuttleAxum { let router = Router::new().route("/", get(hello_world)); Ok(router.into()) } ``` ```toml [package] name = "hello-world" version = "0.1.0" edition = "2021" [dependencies] axum = "0.8" shuttle-axum = "0.56.0" shuttle-runtime = "0.56.0" tokio = "1.28.2" ``` -------------------------------- ### Add Tracing Dependency Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/docs/telemetry/custom-metrics.mdx Installs the `tracing` crate for your Rust project using Cargo. ```bash cargo add tracing ``` -------------------------------- ### Monotonic Counter Metric Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/docs/telemetry/custom-metrics.mdx Example of emitting a monotonic counter metric using `tracing::info!` with a custom attribute `monotonic_counter.requests`. ```rust tracing::info!(monotonic_counter.requests = 1, "New request received"); ``` -------------------------------- ### Example Trace Output Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/docs/telemetry/custom-metrics.mdx A sample JSON representation of a tracing event exported from a Shuttle application, including attributes, severity, and resource information. ```json { "attributes": { "code.filepath": "src/main.rs", "code.lineno": 4, "code.module_path": "my_project", "counter.hello": 1 }, "dropped_attributes_count": 0, "dt": "2025-02-04T15:56:27.068644985Z", "message": "Hello world from OTel!", "observed_timestamp": "2025-02-04T15:56:27.068649239Z", "resources": { "service.name": "my-project", "service.version": "0.1.0", "shuttle.deployment.env": "production", "shuttle.project.crate.name": "my_project", "shuttle.project.id": "proj_01JK8SHBZQ0XF0TKW0EDWBJ8NH", "shuttle.project.name": "my-project", "telemetry.sdk.language": "rust", "telemetry.sdk.name": "opentelemetry", "telemetry.sdk.version": "0.27.1" }, "severity_number": 9, "severity_text": "INFO", "source_type": "opentelemetry" } ``` -------------------------------- ### Best Practice: Meaningful Metric Names Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/docs/telemetry/custom-metrics.mdx Illustrates the importance of using clear and descriptive names for custom metrics in Shuttle applications, contrasting good and bad examples. ```rust // Good tracing::info!(counter.user_sessions = 1, "User session started"); // Bad tracing::info!(counter.us = 1, "Session"); ``` -------------------------------- ### Deploy Shuttle Project to Cloud Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/getting-started/quick-start.mdx Deploys your project to the Shuttle cloud platform. This process involves uploading your code, building a Docker image, and deploying it to Shuttle's infrastructure, assigning a public HTTPS URL. The initial deployment may take a few minutes. ```sh shuttle deploy ``` -------------------------------- ### Shell: Login to Get JWT Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/examples/rocket-jwt-authentication.mdx Example curl command to send a POST request to the login endpoint with username and password to obtain a JWT. The response will contain the authentication token. ```sh curl -X POST --data '{"username": "username", "password": "password"}' https:///login ``` -------------------------------- ### Rust Hello World with Actix Web Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/examples/actix.mdx This Rust code defines a simple 'Hello World' endpoint using the Actix Web framework. It sets up a basic web server that responds with 'Hello World!' when the root path '/' is accessed. The code requires the `actix-web`, `shuttle-actix-web`, and `shuttle-runtime` crates. ```Rust use actix_web::{get, web::ServiceConfig}; use shuttle_actix_web::ShuttleActixWeb; #[get("/")] async fn hello_world() -> &'static str { "Hello World!" } #[shuttle_runtime::main] async fn actix_web( ) -> ShuttleActixWeb { let config = move |cfg: &mut ServiceConfig| { cfg.service(hello_world); }; Ok(config.into()) } ``` -------------------------------- ### Shuttle AI Assistant Rules Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/integrations/mcp-server.mdx Example of AI assistant rules written in Markdown for the Shuttle project. These rules guide the AI to consistently use the Shuttle MCP server for documentation and actions. ```markdown # Shuttle Rules - Always use the Shuttle MCP to get the latest docs and examples - Whenever needed, use the Shuttle MCP server for deployments, logs, project, status, etc. ``` -------------------------------- ### Initialize Shuttle Project Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/templates/tutorials/custom-service.mdx Initializes a new Shuttle project with no template, setting up the basic cargo crate with a dependency on `shuttle-runtime`. ```bash shuttle init --template none ``` -------------------------------- ### Initialize Shuttle Project (Bash) Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/examples/actix-postgres.mdx Command to initialize a new Shuttle project from a GitHub repository and a specific subfolder. This command clones the shuttle-examples repository and checks out the actix-web/postgres subfolder. ```bash shuttle init --from shuttle-hq/shuttle-examples --subfolder actix-web/postgres ``` -------------------------------- ### Rust: Get Deployment Metadata with Shuttle Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/resources/shuttle-metadata.mdx Demonstrates how to use the `shuttle_runtime::ShuttleMetadata` attribute in a Rust Axum application to retrieve and display deployment metadata. The example annotates the main function and creates a route that returns the debug representation of the `DeploymentMetadata` struct. ```rust use axum::{routing::get, Router}; use shuttle_runtime::DeploymentMetadata; #[shuttle_runtime::main] async fn axum( #[shuttle_runtime::Metadata] metadata: DeploymentMetadata, ) -> shuttle_axum::ShuttleAxum { let router = Router::new().route("/", get(format!("{:?}", metadata))); Ok(router.into()) } ``` -------------------------------- ### Example Workspace Structure for Shuttle Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/docs/project-configuration.mdx This text-based structure illustrates a typical Rust cargo workspace setup for a project intended to run on Shuttle. It highlights the placement of configuration files (Shuttle.toml, Secrets.toml) and the organization of backend, frontend, and shared crates. ```text . ├── .gitignore ├── Cargo.toml ├── Secrets.toml (optional) ├── Shuttle.toml (optional) ├── backend/ │ ├── Cargo.toml (depends on shuttle-runtime) │ └── src/ │ └── main.rs (contains #[shuttle_runtime::main]) ├── frontend/ │ ├── Cargo.toml │ └── src/ │ └── main.rs └── shared/ ├── Cargo.toml └── src/ └── lib.rs ``` -------------------------------- ### Run Shuttle Project Locally Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/getting-started/quick-start.mdx Executes your Shuttle project on your local machine for testing purposes before deployment. This allows you to verify functionality without deploying to the cloud. ```sh shuttle run ``` -------------------------------- ### Generate iCalendar Event via cURL Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/templates/tutorials/serverless-calendar-app.mdx This example demonstrates how to generate an iCalendar (.ics) file using cURL by passing event details as GET parameters to a serverless application. The output is a standard iCalendar format that can be saved and opened by calendar applications. ```bash curl https://zerocal.shuttle.app?start=2022-11-04+20:00&duration=3h&title=Birthday&description=paaarty ``` ```ical BEGIN:VCALENDAR VERSION:2.0 PRODID:ICALENDAR-RS CALSCALE:GREGORIAN BEGIN:VEVENT DTSTAMP:20221002T123149Z CLASS:CONFIDENTIAL DESCRIPTION:paaarty DTEND:20221002T133149Z DTSTART:20221002T123149Z SUMMARY:Birthday UID:c99dd4bb-5c35-4d61-9c46-7a471de0e7f4 END:VEVENT END:VCALENDAR ``` -------------------------------- ### Provision Postgres Database with Shuttle Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/welcome/introduction.mdx Demonstrates how to automatically provision a Postgres database and obtain an authenticated connection pool using Shuttle's 'Infrastructure from Code' feature with Rust macros. This simplifies database setup by defining it directly within the application code. ```Rust #[shuttle_runtime::main] async fn main( // Automatically provisions a Postgres database // and hands you an authenticated connection pool #[shuttle_shared_db::Postgres] pool: sqlx::PgPool, ) -> ShuttleAxum { // Application code } ``` -------------------------------- ### Install Shuttle CLI (Linux/macOS) Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/getting-started/installation.mdx Installs the latest version of the Shuttle CLI using a curl and bash script. This method automatically detects the optimal installation for your OS, architecture, and distro, and can also install Rust if needed. ```sh curl -sSfL https://www.shuttle.dev/install | bash ``` -------------------------------- ### Verify Shuttle CLI Installation Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/getting-started/installation.mdx Verifies that the Shuttle CLI has been installed correctly by checking its version. This command should output the currently installed version number. ```sh shuttle --version ``` -------------------------------- ### Run Development Server Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/templates/fullstack/saas-template.mdx Starts the application with live reload capabilities using turbowatch. This script monitors changes in both the frontend and backend. The application can be accessed at http://localhost:8000. ```Shell npm run dev ``` -------------------------------- ### Install Shuttle CLI via pacman (Arch Linux) Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/getting-started/installation.mdx Installs the Shuttle CLI on Arch Linux using the pacman package manager. This command installs the package from the community repository. ```sh pacman -S cargo-shuttle ``` -------------------------------- ### Install Shuttle CLI via apk (Alpine Linux) Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/getting-started/installation.mdx Installs the Shuttle CLI on Alpine Linux using the apk package manager. This command installs the package from the testing repository, which may need to be enabled. ```sh apk add cargo-shuttle ``` -------------------------------- ### Build WASM Frontend with Trunk Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/docs/builds.mdx This example shows how to navigate to a frontend directory and build a WebAssembly (WASM) frontend using the `trunk` build tool with release optimizations. This is typically run as a post-build hook. ```Shell ```sh shuttle_postbuild.sh cd frontend trunk build --release ``` ``` -------------------------------- ### Login to Shuttle Account Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/getting-started/quick-start.mdx Authenticates your CLI with your Shuttle account. This command opens a browser window to the Shuttle Console for authentication. It supports authentication via Google, GitHub, or email. ```sh shuttle login ``` -------------------------------- ### Axum CORS Layer Configuration (Advanced) Source: https://github.com/shuttle-hq/shuttle-docs/blob/main/templates/tutorials/rest-http-service-with-axum.mdx An advanced Rust configuration for Axum's CORS policy using `CorsLayer`. This example enables credentials, allows multiple HTTP methods (GET, POST, PUT, DELETE), specifies allowed headers (ORIGIN, AUTHORIZATION, ACCEPT), and permits a specific origin parsed from application state. ```rust let cors = CorsLayer::new() .allow_credentials(true) .allow_methods(vec![Method::GET, Method::POST, Method::PUT, Method::DELETE]) .allow_headers(vec![ORIGIN, AUTHORIZATION, ACCEPT]) .allow_origin(state.domain.parse::().unwrap()); // once we've created our CORS layer, we can layer it on top of our router // in a nested router you'll want to layer it only after all the routes where it's required Router::new().layer(cors) ```