Skip to main content

Crate next_rust

Crate next_rust 

Source
Expand description

§Next Rust

A Rust-native full-stack web framework: the filesystem is your router, page.rs is a page, layout.rs wraps its children, and the build turns the app directory into a compiled, type-checked route table.

app/
├── layout.rs          → wraps every page
├── page.rs            → /
├── about/page.rs      → /about
└── blog/[slug]/page.rs → /blog/:slug
ⓘ
// app/page.rs
use next_rust::prelude::*;

pub fn Page() -> impl View {
    div![h1!["Hello World"], p!["Welcome to Next Rust."]]
}
ⓘ
// build.rs
fn main() { next_rust_build::generate(); }

// src/main.rs
next_rust::app!();

Guides live on the documentation website (website/ in the repository).

Re-exports§

pub use next_rust_ui as ui;
pub use next_rust_icons as icons;

Modules§

actions
Server actions: #[server_action] functions exposed at POST /_next-rust/action/<token>.
app
Route definitions, application builder and request dispatch.
attrs
Attribute helpers.
bytes
Provides abstractions for working with bytes.
class_names
Short class names for production builds.
components
Built-in components and composition helpers.
config
next-rust.toml configuration.
context
Render context and extractors.
cookies
Cookies with secure defaults.
deps
Re-exported crates for advanced use.
dotenv
.env loading with an explicit server/public split.
embed
Files compiled into the production binary.
error
The error type used by pages, layouts, loaders, API routes and actions.
export
Static generation: renders static routes into a page cache.
futures
Combinators and utilities for working with Futures, Streams, Sinks, and the AsyncRead and AsyncWrite traits.
http
A general purpose library of common HTTP types
http_date
IMF-fixdate formatting (RFC 9110 §5.6.7) without external dependencies.
jobs
Background and scheduled jobs.
log
Minimal structured logging.
metadata
Document metadata (<head> contents).
middleware
Middleware.
plugin
Runtime plugins.
prelude
Everything needed in page, layout and route files.
request
Incoming HTTP request.
response
Outgoing HTTP response.
runtime
Process entry point used by next_rust::main!().
seo
Generated sitemap.xml and robots.txt (app/sitemap.rs, app/robots.rs).
server
Production HTTP server built on hyper.
session
Server-side sessions.
sse
Server-Sent Events.
static_files
Static file serving for public/ (and framework client files), from disk in development and from the binary in release builds.
style
Stylesheets created by the css_module! and global_css! macros.
testing
In-process testing without a network socket.
tokio
A runtime for writing reliable network applications without compromising speed.

Macros§

Image
Responsive, lazily loaded image.
Link
Client-side-navigation aware link.
a
<a> element.
abbr
<abbr> element.
action
Reference a server action: action!(create_user) or action!(crate::actions::create_user). Evaluates to an ActionRef, usable as a form![..] part or via .url().
address
<address> element.
app
Define main for a Next Rust application with default settings.
area
<area> void element (children are ignored).
article
<article> element.
aside
<aside> element.
asset
Fingerprinted URL of a file in the project’s assets/ directory, computed at compile time: asset!("fonts/inter.woff2") → "/_next-rust/assets/fonts/inter.1a2b3c4d5e6f7a8b.woff2". Served with immutable caching; the URL changes whenever the file content changes.
audio
<audio> element.
b
<b> element.
base
<base> void element (children are ignored).
blockquote
<blockquote> element.
body
<body> element.
br
<br> void element (children are ignored).
button
<button> element.
canvas
<canvas> element.
caption
<caption> element.
circle
<circle> element.
cite
<cite> element.
clipPath
<clipPath> element.
code
<code> element.
col
<col> void element (children are ignored).
colgroup
<colgroup> element.
css_module
Import a CSS module (path relative to the current source file).
datalist
<datalist> element.
dd
<dd> element.
defs
<defs> element.
del
<del> element.
details
<details> element.
dfn
<dfn> element.
dialog
<dialog> element.
div
<div> element.
dl
<dl> element.
dt
<dt> element.
ellipse
<ellipse> element.
em
<em> element.
embed
<embed> void element (children are ignored).
feBlend
<feBlend> element (SVG).
feColorMatrix
<feColorMatrix> element (SVG).
feComposite
<feComposite> element (SVG).
feDropShadow
<feDropShadow> element (SVG).
feFlood
<feFlood> element (SVG).
feGaussianBlur
<feGaussianBlur> element (SVG).
feMerge
<feMerge> element (SVG).
feMergeNode
<feMergeNode> element (SVG).
feOffset
<feOffset> element (SVG).
fieldset
<fieldset> element.
figcaption
<figcaption> element.
figure
<figure> element.
filter
<filter> element (SVG).
footer
<footer> element.
foreignObject
<foreignObject> element (SVG).
form
<form> element.
fragment
Group children without a wrapper element: fragment![a, b, c].
g
<g> element.
global_css
Include a global stylesheet (path relative to the current source file), minified at compile time. Place the result in the view tree, typically in the root layout: div![global_css!("globals.css"), children].
h1
<h1> element.
h2
<h2> element.
h3
<h3> element.
h4
<h4> element.
h5
<h5> element.
h6
<h6> element.
head
<head> element.
header
<header> element.
hgroup
<hgroup> element.
hr
<hr> void element (children are ignored).
html
<html> element.
i
<i> element.
iframe
<iframe> element.
img
<img> void element (children are ignored).
input
<input> void element (children are ignored).
ins
<ins> element.
kbd
<kbd> element.
label
<label> element.
legend
<legend> element.
li
<li> element.
linearGradient
<linearGradient> element.
link
<link> void element (children are ignored).
main
<main> element.
mark
<mark> element.
marker
<marker> element (SVG).
mask
<mask> element (SVG).
menu
<menu> element.
meta
<meta> void element (children are ignored).
meter
<meter> element.
nav
<nav> element.
noscript
<noscript> element.
object
<object> element.
ol
<ol> element.
optgroup
<optgroup> element.
option
<option> element.
output
<output> element.
p
<p> element.
path
<path> element.
pattern
<pattern> element (SVG).
picture
<picture> element.
polygon
<polygon> element.
polyline
<polyline> element.
pre
<pre> element.
progress
<progress> element.
q
<q> element.
radialGradient
<radialGradient> element.
rect
<rect> element.
routes
Include the generated route table (routes()) in the current module.
rp
<rp> element.
rt
<rt> element.
ruby
<ruby> element.
s
<s> element.
samp
<samp> element.
script
<script> element.
section
<section> element.
select
<select> element.
slot
<slot> element.
small
<small> element.
source
<source> void element (children are ignored).
span
<span> element.
stop
<stop> element.
strong
<strong> element.
style
<style> element.
sub
<sub> element.
summary
<summary> element.
sup
<sup> element.
svg
<svg> element.
symbol
<symbol> element.
table
<table> element.
tbody
<tbody> element.
td
<td> element.
template
<template> element.
text
<text> element (SVG).
textPath
<textPath> element (SVG).
textarea
<textarea> element.
tfoot
<tfoot> element.
th
<th> element.
thead
<thead> element.
time
<time> element.
title
<title> element.
tr
<tr> element.
track
<track> void element (children are ignored).
tspan
<tspan> element (SVG).
u
<u> element.
ul
<ul> element.
use_
<use> element.
var
<var> element.
video
<video> element.
wbr
<wbr> void element (children are ignored).

Structs§

ActionContext
Request data available to actions declared as fn(ctx: ActionContext, input: T).
ActionDef
ActionRef
Reference to a server action, created with action!(path::to::fn).
ApiDef
App
A configured application. Cheap to clone.
AppBuilder
Builder returned by App::new.
Attr
An attribute. Create with the helpers in crate::attrs.
Auth
Authentication context primitive: set by your auth middleware, read by pages. Auth<T> is Option-like: auth.user() is None for guests.
AuthUser
Wrapper middleware inserts: req.insert_extension(AuthUser(user)).
Cache
Typed cache API over a shared store.
CacheEntry
A cached value with freshness information.
CacheKey
Cache key. Namespaces used by the framework: page:<path>, data:<key>, image:<hash>.
CacheOptions
Options for Cache::get_or_insert_json.
Children
Content passed to a layout or template.
ClientIp
The client’s IP address, read as crate::Request::client_ip reads it: the first X-Forwarded-For entry when [server] trust_proxy is on, the peer address otherwise. None when neither is known (tests, pre-rendering).
Config
Cookie
A cookie to set.
Cookies
Request cookies plus pending changes, shared between the request, the render context and the response.
Cors
CORS configuration.
CspNonce
Per-request CSP nonce stored in request extensions.
CsrfToken
CSRF token for forms when csrf() middleware or [security] csrf = "token" is used.
CssClass
A scoped class name from a CSS module.
Data
Result of the route’s load function: Data(posts): Data<Vec<Post>>.
Diagnostic
DocumentParts
Everything needed to render a full HTML document.
Element
An HTML element.
Embedded
Everything a release binary carries with it.
EmbeddedFile
One embedded file. path is relative to its directory and uses /.
Error
Framework error.
ErrorInfo
Information passed to error.rs / global-error.rs.
Extension
A value inserted by middleware (req.insert_extension(user)), e.g. the authenticated user: Extension(user): Extension<User>. Missing values produce a 500 in development with a clear message; use Option<Extension<T>> for optional values.
Feed
A syndication feed, rendered as RSS 2.0, Atom 1.0 or JSON Feed 1.1.
FeedEntry
One item in a Feed.
FileStore
Persistent store: one <hash>.bin (value) and <hash>.json (metadata) pair per key. Writes are atomic (write to a temp file, then rename).
FormState
Result of the last progressive-enhancement form submission (validation errors / error message), read once from a short-lived flash cookie.
Headers
Request headers.
Html
HTML body wrapper: Html(markup).
ImageProps
Builder behind Image!.
Json
JSON body wrapper: Json(data).
LinkProps
Props for Link!; the macro uses attribute helpers directly, this type exists for programmatic construction.
LocalFont
A self-hosted font.
MemorySessionStore
In-memory store for development and single-instance deployments.
MemoryStore
Bounded in-memory LRU store.
Metadata
Next
The rest of the chain.
Nonce
The per-request CSP nonce (for your own inline scripts).
PageDef
Params
Route parameters captured while matching, in pattern order.
Path
Typed route parameters: Path(p): Path<BlogParams>. A parameter that fails to parse (e.g. /users/abc for id: u64) renders the 404 page.
Query
Parsed query string: Query(q): Query (a map) or Query<T> (typed).
QueryMap
Query parameters as a multi-map.
RateLimit
Fixed-window-with-token-bucket rate limiter configuration.
RenderFlags
Features used by a rendered document; the server uses these to decide which (if any) client scripts to include.
Request
An HTTP request as seen by middleware, API routes and server actions.
RequestContext
Everything known about the request being rendered.
RequestId
Request identifier inserted by request_id.
RequestInfo
Basic request information.
Response
An HTTP response.
ResponseHeaders
Add headers to the page response.
Robots
pub async fn robots() -> Robots
RobotsRule
Routes
Everything discovered in the app directory.
SegmentDef
Files attached to one route segment (directory).
Session
Request-scoped session handle (cheap to clone).
Sitemap
pub async fn sitemap() -> Sitemap
SitemapEntry
SlotDef
Slots
Parallel-route slots passed to a layout (@analytics → slots.take("analytics")).
SseEvent
One SSE message.
Stylesheet
A compiled stylesheet.
Suspense
An async boundary: fallback is rendered immediately, content replaces it once resolved (in place when not streaming, out-of-order when streaming).
TestClient
Sends requests to an App directly.
TestResponse
A collected response.

Enums§

AttrValue
Attribute value.
Body
Response body.
Environment
Runtime environment.
ErrorKind
Node
A rendered view tree.
PageBody
ParamValue
Value of a route parameter.
RenderMode
Whether a render serves a live request or runs at build/revalidation time.
Rendering
Rendering mode declared by a page: pub const RENDERING: Rendering = Rendering::Dynamic;
RenderingMode
How a page is rendered.
SameSite

Constants§

CSRF_COOKIE
Name of the CSRF double-submit cookie.
SECRET_ENV
Environment variable holding the server secret.
STREAMING_RUNTIME
Inline script used to swap streamed content into place.
STRICT_CSP
The policy [security] csp = "strict" stands for: scripts only with the per-request nonce ('strict-dynamic' lets those scripts load modules and islands), everything else from this origin, no plugins, no framing by other sites, forms only to this origin. Inline style attributes stay allowed: components set widths and custom properties with them.
TAGS
Names of all generated element macros.
VERSION
The framework’s version, as in Cargo.toml.
VOID_TAGS
Names of void elements.

Traits§

AttrText
Values accepted as attribute text.
CacheStore
Storage backend.
ClassValue
Values accepted by class.
FromContext
Resolve a function argument from the render context.
IntoResponse
Conversion into a Response.
IntoViewResult
Conversion of a component’s return value into a render result: accepts impl View as well as Result<impl View, E>. Used by generated code.
Middleware
Middleware trait; implemented for all matching async functions/closures.
OrNotFound
Convert None into a 404.
Part
Something that can be placed inside an element macro.
SessionStore
Session storage backend.
View
Anything renderable.

Functions§

accept
accept attribute.
action
action attribute.
action_result
Inside a form with stay_on_success: show the action’s return value here after a successful submit. "" shows the whole value (a string or number); a key shows that field of a returned object. Filled as text, never as HTML.
active_class
Mark a link as the current page: when the URL path equals the link’s path, the link gets this class and aria-current="page". Applied by the server when rendering and kept up to date by the client runtime after every navigation, so it also works in layouts that stay on screen.
active_class_prefix
Like active_class, but also active on every page below the link’s path: a link to /docs is active on /docs/routing.
alt
alt attribute.
aria
aria-* attribute: aria("label", "Close") → aria-label="Close".
as_
as attribute.
async
r#async(true) for scripts.
attr
Any attribute: attr("hx-get", "/x"). Event handler attributes (on*) are refused here; see raw_attr.
attr_if
Include attr only when condition holds.
autocomplete
autocomplete attribute.
autofocus
autofocus boolean attribute.
autoplay
autoplay boolean attribute.
cache
Memoize an async computation in the data cache. Memoize f in the global data cache.
charset
charset attribute.
checked
checked boolean attribute.
class
class("a b"), class(styles.card), class(["a", "b"]), class([("active", is_active)]). Multiple class parts are merged.
cols
cols attribute.
colspan
colspan attribute.
constant_time_eq
Constant-time byte comparison (for tokens).
content
content attribute.
controls
controls boolean attribute.
cors
CORS middleware, including preflight handling.
crossorigin
crossorigin attribute.
csrf
Double-submit CSRF token protection for unsafe methods.
d
d attribute.
data
data-* attribute: data("id", "42") → data-id="42".
datetime
datetime attribute.
decoding
decoding attribute.
defer
defer boolean attribute.
dir
dir attribute.
disabled
disabled boolean attribute.
download
download attribute.
each
Render every item of an iterator.
enctype
enctype attribute.
enterkeyhint
enterkeyhint attribute.
escape_attr
Escape attribute values (&, <, >, ", ').
escape_text
Escape text content (&, <, >).
fetchpriority
fetchpriority attribute.
fill
fill attribute.
for
r#for("email")
for_
for attribute of <label>.
form_attr
form attribute.
fragment_of
Collect any iterator of views into a fragment.
height
height attribute.
hidden
hidden boolean attribute.
href
href attribute.
http_equiv
http-equiv attribute.
id
id attribute.
inert
inert boolean attribute.
inputmode
inputmode attribute.
integrity
integrity attribute.
invalidate
Memoize an async computation in the data cache. Remove a data-cache entry.
is_dev
Whether the process runs in development mode (detailed errors).
is_safe_url
Whether a URL is safe to place in a URL attribute.
island
Wrap server-rendered markup in an island marker so the client runtime can hydrate it. Used by the #[client] macro; props_json must be JSON.
ismap
ismap boolean attribute.
key
Stable identity for list items, used by client-side hydration.
label_attr
label attribute.
lang
lang attribute.
link_is_active
Whether a link to href is active on path, exactly or as a prefix.
list
list attribute.
loading
loading attribute.
mark_active_links
Apply active_class / active_class_prefix for path to a view tree (async boundaries are left to the client runtime).
max
max attribute.
maxlength
maxlength attribute.
media
media attribute.
method
method attribute.
min
min attribute.
minlength
minlength attribute.
multiple
multiple boolean attribute.
muted
muted boolean attribute.
name
name attribute.
nomodule
nomodule boolean attribute.
nonce
nonce attribute.
not_found
Render the nearest not-found.rs with status 404.
novalidate
novalidate boolean attribute.
on
Declarative client event binding for interactive islands: on("click", "increment") → data-nr-on-click="increment".
open
open boolean attribute.
parse_pattern
Convert /users/:id, /files/*path or /users/[id] into a pattern.
pattern
pattern attribute.
permanent_redirect
Permanent redirect (308, method preserved).
placeholder
placeholder attribute.
playsinline
playsinline boolean attribute.
prefetch
Disable prefetching for a link. By default a page is prefetched when the mouse rests on its link for 400 ms.
protected
Protect routes: when check returns false the user is redirected to login (with ?next= set) — or receives 401 for non-GET requests.
random_hex
n random bytes from the operating system CSPRNG, hex encoded.
rate_limit
In-memory token bucket rate limiting (per process). Responds 429 with Retry-After when exhausted. For multi-instance deployments, implement your own middleware backed by a shared store.
raw_attr
An attribute that is allowed to carry script, e.g. onclick. The value is still HTML-escaped, but its content will execute: never pass user input.
raw_html
Unescaped HTML. Never pass untrusted input.
readonly
readonly boolean attribute.
redirect
Temporary redirect (307, method preserved).
referrerpolicy
referrerpolicy attribute.
rel
rel attribute.
reload
Make a link do a full page load instead of client-side navigation: a![href("/logout"), reload(true), "Log out"].
render_static
Render synchronously. Suspense boundaries render their fallback.
render_to_string
Render to a string, awaiting all async content.
replace
Replace the history entry instead of pushing a new one (Link!).
request_id
Ensure every request has an x-request-id (reused from the client when it is a short, safe token) and echo it on the response.
required
required boolean attribute.
reset_on_success
On a form with stay_on_success: clear its fields after a successful submit.
resolve
Resolve every suspense boundary in a tree (siblings concurrently).
restyle_document
Rewrite the per-class <style> elements of a rendered document (a cached static page) for a browser that already has the style ids known: only what it is missing is kept. Every per-class stylesheet rendered so far (component libraries’ too) is considered, besides sheets.
revalidate_path
ISR / data-cache invalidation. Re-render path on its next request (pages rendered statically) and drop the matching data-cache entry. Usable from API routes and actions.
revalidate_tag
ISR / data-cache invalidation. Invalidate every cached page and data entry tagged with tag.
reversed
reversed boolean attribute.
role
role attribute.
rows
rows attribute.
rowspan
rowspan attribute.
run
Load .env files, configure logging and run the app.
run_with
Like run, with a customized builder:
script_key
The key of a script URL in Stylesheet::scripts: the path under /_next-rust/ or public/, without query string or fingerprint (/_next-rust/assets/js/site.1a2b3c4d5e6f7a8b.js → assets/js/site.js).
scroll
Keep the scroll position after a client navigation (Link!).
security_headers
Middleware form of the security headers (for custom setups).
selected
selected boolean attribute.
sessions
Session middleware.
signature
The build signature (Next Rust 0.1.10): what a page’s <meta name="generator"> and the framework’s scripts say built them while [build] signature = true.
sizes
sizes attribute.
slot_attr
slot attribute.
spellcheck
spellcheck attribute.
src
src attribute.
srcset
srcset attribute.
stay_on_success
On an action form: after a successful submit, stay on the page instead of refreshing it or following _redirect (which then only applies to browsers without JavaScript). Elements marked with action_result show what the action returned, and the form gets data-nr-state="success" for styling.
step
step attribute.
stream_document
Render a complete document as a stream of chunks.
stroke
stroke attribute.
style
style attribute.
suspense
An async boundary. fallback renders immediately; content is awaited.
tabindex
tabindex attribute.
target
target attribute.
title
title attribute.
translate
translate attribute.
type
r#type("submit")
type_
type attribute (also available as r#type).
value
value attribute.
view_box
viewBox attribute.
when
Render f() only when condition is true.
width
width attribute.
wrap
wrap attribute.
xmlns
xmlns attribute.

Type Aliases§

BoxFuture
Ctx
Shared handle to the context.
Result
Result alias with Error as the default error type.

Attribute Macros§

client
Mark a component as an interactive island.
server
Server-only code. The item is compiled only for non-browser targets, so referencing it from code compiled to wasm32 fails at compile time instead of leaking server logic or secrets into a client bundle.
server_action
Expose an async function as a server action.