Htmx extractors and request guards for axum.

Overview

axum-htmx


axum-htmx is a small extension library providing extractors and request guards for the various htmx headers within axum. Additionally, the library exports const values for all of the htmx headers, so there's no need to mess with strings in your handlers.

Getting Started

Simply run cargo add axum-htmx to add the library to your project.

If you are using the unreleased branch of axum from GitHub, you can build against the main version of axum-htmx by adding the following to your Cargo.toml:

[dependencies]
axum-htmx = { git = "https://github.com/robertwayne/axum-htmx" }

Extractors

All of the htmx request headers have a supported extractor. Extractors are infallible, meaning they will always succeed and never return an error. In the case where a header is not present, the extractor will return None or false dependant on the expected return type.

Header Extractor Value
HX-Boosted HxBoosted bool
HX-Current-URL HxCurrentUrl Option<String>
HX-History-Restore-Request HxHistoryRestoreRequest bool
HX-Prompt HxPrompt Option<String>
HX-Request HxRequest bool
HX-Target HxTarget Option<String>
HX-Trigger-Name HxTriggerName Option<String>
HX-Trigger HxTrigger Option<String>

Request Guards

Requires features guards.

In addition to the extractors, there is also a route-wide layer request guard for the HX-Request header. This will redirect any requests without the header to "/" by default.

It should be noted that this is NOT a replacement for an auth guard. A user can trivially set the HX-Request header themselves. This is merely a convenience for preventing users from receiving partial responses without context. If you need to secure an endpoint you should be using a proper auth system.

Example: Extractors

In this example, we'll look for the HX-Boosted header, which is set when applying the hx-boost attribute to an element. In our case, we'll use it to determine what kind of response we send.

When is this useful? When using a templating engine, like minijinja, it is common to extend different templates from a _base.html template. However, htmx works by sending partial responses, so extending our _base.html would result in lots of extra data being sent over the wire.

If we wanted to swap between pages, we would need to support both full template responses and partial responses (as the page can be accessed directly or through a boosted anchor), so we look for the HX-Boosted header and extend from a _partial.html template instead.

use axum::response::IntoResponse;
use axum_htmx::HxBoosted;

async fn get_index(HxBoosted(boosted): HxBoosted) -> impl IntoResponse {
    if boosted {
        // Send a template extending from _partial.html
    } else {
        // Send a template extending from _base.html
    }
}

Example: Router Guard

use axum::Router;
use axum_htmx::HxRequestGuardLayer;

fn router_one() -> Router {
    Router::new()
        // Redirects to "/" if the HX-Request header is not present
        .layer(HxRequestGuardLayer::default())
}

fn router_two() -> Router {
    Router::new()
        .layer(HxRequestGuardLayer::new("/redirect-to-this-route"))
}

Feature Flags

Flag Default Description Dependencies
guards Disabled Adds request guard layers. tower, futures-core, pin-project-lite

Contributing

Contributions are always welcome! If you have an idea for a feature or find a bug, let me know. PR's are appreciated, but if it's not a small change, please open an issue first so we're all on the same page!

License

axum-htmx is dual-licensed under either

at your option.

You might also like...
Experiments with Rust CRDTs using Tokio web application framework Axum.

crdt-genome Synopsis Experiments with Rust CRDTs using Tokio web application framework Axum. Background Exploring some ideas of Martin Kleppmann, part

Axum web framework tutorial for beginners.

Axum Tutorial For Beginners Hello web developers! This tutorial will cover how to write simple web applications in rust with axum framework. If you ar

Yew + Axum + blog = Yab

Yew + Axum + blog = Yab

Rust Axum+SQLx Sample

rust-axum-sqlx-sample Install git clone https://github.com/web3ten0/rust-axum-sqlx-1.git cd rust-axum-sqlx-1/local docker-compose up -d sh scripts/exe

🪪 Session-based user authentication for Axum.

axum-login 🪪 Session-based user authentication for Axum. 🎨 Overview axum-login is a Tower middleware providing session-based user authentication for

🔎 Prometheus metrics middleware for Axum

Axum-Prometheus A Prometheus middleware to collect HTTP metrics for Axum applications. axum-prometheus relies on metrics_exporter_prometheus as a back

Provides json/csv/protobuf streaming support for axum

axum streams for Rust Library provides HTTP response streaming support for axum web framework: JSON array stream format JSON lines stream format CSV s

A crate built on top of `axum-sessions`, implementing the CSRF Synchronizer Token Pattern

Axum Synchronizer Token Pattern CSRF prevention This crate provides a Cross-Site Request Forgery protection layer and middleware for use with the axum

Rate Limiting middleware for Tower/Axum/Tonic/Hyper utilizing the governor crate

A Tower service and layer that provides a rate-limiting backend by governor. Based heavily on the work done for actix-governor. Works with Axum, Hyper

Comments
  • HxRequestGuardLayer should take an (optional) redirect route

    HxRequestGuardLayer should take an (optional) redirect route

    Probably like:

    use axum::Router;
    use axum_htmx::HxRequestGuardLayer;
    
    fn protected_router() -> Router {
        Router::new()
            .layer(HxRequestGuardLayer::new().redirect_on_failure("/"))
    }
    

    EDIT: Possible that this could be default behavior, but it comes with the assumption that "/" will always resolve in a meaningful way, which may not (?) be the case. Could take an Option<&str> in the new fn to force this instead.

    enhancement 
    opened by robertwayne 0
Releases(v0.3.0)
  • v0.3.0(Jul 29, 2023)

    • HxRequestGuardLayer now redirects on failures instead of returning a 403. By default, it will redirect to "/", but you can specify a different route to redirect to with HxRequestGuardLayer::new("/your-route-here").
    Source code(tar.gz)
    Source code(zip)
  • v0.2.0(Jul 28, 2023)

    • Added HxRequestGuardLayer, allowing you to protect an entire router from non-htmx requests. This can be enabled via the new feature flag guards.
    Source code(tar.gz)
    Source code(zip)
  • v0.1.0(Jul 22, 2023)

Owner
Rob
Rob
Layers, extractors and template engine wrappers for axum based Web MVC applications

axum-template Layers, extractors and template engine wrappers for axum based Web MVC applications Getting started Cargo.toml [dependencies] axum-templ

Altair Bueno 11 Dec 15, 2022
A secure and efficient gateway for interacting with OpenAI's API, featuring load balancing, user request handling without individual API keys, and global access control.

OpenAI Hub OpenAI Hub is a comprehensive and robust tool designed to streamline and enhance your interaction with OpenAI's API. It features an innovat

Akase Cho 30 Jun 16, 2023
A blazingly fast HTTP client with a magnificent request building syntax, made for humans.

?? glue Make requests, select JSON responses, nest them in other requests: A magnificent syntax for blazingly fast cli HTTP calls, made for humans. Ta

Michele Esposito 4 Dec 7, 2022
Demo of Rust and axum web framework

Demo of Rust and axum web framework Demonstration of: Rust: programming language that focuses on reliability and stability. axum: web framework that f

Joel Parker Henderson 115 Dec 29, 2022
Simple example of axum, sqlx with sqlite and utoipa (swagger) - without auth

axum_crud_api Simple example to learn creating CRUD rest apis in Rust with axum, sqlx with sqlite and utoipa (swagger) - without auth Also shows how t

null 2 Nov 12, 2022
Heavy Metal Leptos Stack with Tailwind, Axum, Sqlite, and Cargo Leptos

Heavy Metal Stack Leptos stack with Axum, TailwindCSS, and Sqlite This example creates a basic todo app with an Axum backend that uses Leptos' server

Ben Wishovich 7 Dec 31, 2022
Starter template for use with the Leptos web framework and Axum.

Leptos Axum Starter Template This is a template for use with the Leptos web framework and the cargo-leptos tool using Axum. Creating your template rep

Leptos 10 Mar 4, 2023
Rust server with Axum, GraphQL and SurrealDb

??️ Article on my web Axum server, Async-GraphQl, SurrealDB template Run without any prior setup, DB is in memory: cargo run To use routes other than

null 15 Jun 26, 2023
Leptos Axum Prisma starter with Admin dashboard and SSR/SPA website

LAPA - Leptos Axum Prisma starter with Admin dashboard and SSR/SPA website Motivation I want to have practical full-stack setup to build websites and

Alexi Chepura 2 Jul 10, 2023
🥠 Sessions as a `tower` and `axum` middleware.

tower-sessions ?? Sessions as a `tower` and `axum` middleware. ?? Overview This crate provides sessions, key-value pairs associated with a site visito

Max Countryman 48 Oct 11, 2023