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 atPOST /_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.tomlconfiguration.- context
- Render context and extractors.
- cookies
- Cookies with secure defaults.
- deps
- Re-exported crates for advanced use.
- dotenv
.envloading 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 theAsyncReadandAsyncWritetraits. - 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.xmlandrobots.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!andglobal_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)oraction!(crate::actions::create_user). Evaluates to anActionRef, usable as aform![..]part or via.url(). - address
<address>element.- app
- Define
mainfor 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.- clip
Path <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).- feColor
Matrix <feColorMatrix>element (SVG).- feComposite
<feComposite>element (SVG).- feDrop
Shadow <feDropShadow>element (SVG).- feFlood
<feFlood>element (SVG).- feGaussian
Blur <feGaussianBlur>element (SVG).- feMerge
<feMerge>element (SVG).- feMerge
Node <feMergeNode>element (SVG).- feOffset
<feOffset>element (SVG).- fieldset
<fieldset>element.- figcaption
<figcaption>element.- figure
<figure>element.- filter
<filter>element (SVG).- footer
<footer>element.- foreign
Object <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.- linear
Gradient <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.- radial
Gradient <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).- text
Path <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§
- Action
Context - Request data available to actions declared as
fn(ctx: ActionContext, input: T). - Action
Def - Action
Ref - 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>isOption-like:auth.user()isNonefor guests. - Auth
User - Wrapper middleware inserts:
req.insert_extension(AuthUser(user)). - Cache
- Typed cache API over a shared store.
- Cache
Entry - A cached value with freshness information.
- Cache
Key - Cache key. Namespaces used by the framework:
page:<path>,data:<key>,image:<hash>. - Cache
Options - Options for
Cache::get_or_insert_json. - Children
- Content passed to a layout or template.
- Client
Ip - The client’s IP address, read as
crate::Request::client_ipreads it: the firstX-Forwarded-Forentry when[server] trust_proxyis on, the peer address otherwise.Nonewhen 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.
- Csrf
Token - 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
loadfunction:Data(posts): Data<Vec<Post>>. - Diagnostic
- Document
Parts - Everything needed to render a full HTML document.
- Element
- An HTML element.
- Embedded
- Everything a release binary carries with it.
- Embedded
File - One embedded file.
pathis relative to its directory and uses/. - Error
- Framework error.
- Error
Info - 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; useOption<Extension<T>>for optional values. - Feed
- A syndication feed, rendered as RSS 2.0, Atom 1.0 or JSON Feed 1.1.
- Feed
Entry - One item in a
Feed. - File
Store - Persistent store: one
<hash>.bin(value) and<hash>.json(metadata) pair per key. Writes are atomic (write to a temp file, then rename). - Form
State - 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). - Image
Props - Builder behind
Image!. - Json
- JSON body wrapper:
Json(data). - Link
Props - Props for
Link!; the macro uses attribute helpers directly, this type exists for programmatic construction. - Local
Font - A self-hosted font.
- Memory
Session Store - In-memory store for development and single-instance deployments.
- Memory
Store - 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/abcforid: u64) renders the 404 page. - Query
- Parsed query string:
Query(q): Query(a map) orQuery<T>(typed). - Query
Map - Query parameters as a multi-map.
- Rate
Limit - Fixed-window-with-token-bucket rate limiter configuration.
- Render
Flags - 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.
- Request
Context - Everything known about the request being rendered.
- Request
Id - Request identifier inserted by
request_id. - Request
Info - Basic request information.
- Response
- An HTTP response.
- Response
Headers - Add headers to the page response.
- Robots
pub async fn robots() -> Robots- Robots
Rule - Routes
- Everything discovered in the app directory.
- Segment
Def - Files attached to one route segment (directory).
- Session
- Request-scoped session handle (cheap to clone).
- Sitemap
pub async fn sitemap() -> Sitemap- Sitemap
Entry - 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:
fallbackis rendered immediately,contentreplaces it once resolved (in place when not streaming, out-of-order when streaming). - Test
Client - Sends requests to an
Appdirectly. - Test
Response - A collected response.
Enums§
- Attr
Value - Attribute value.
- Body
- Response body.
- Environment
- Runtime environment.
- Error
Kind - Node
- A rendered view tree.
- Page
Body - Param
Value - Value of a route parameter.
- Render
Mode - 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; - Rendering
Mode - How a page is rendered.
- Same
Site
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. Inlinestyleattributes 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§
- Attr
Text - Values accepted as attribute text.
- Cache
Store - Storage backend.
- Class
Value - Values accepted by
class. - From
Context - Resolve a function argument from the render context.
- Into
Response - Conversion into a
Response. - Into
View Result - Conversion of a component’s return value into a render result: accepts
impl Viewas well asResult<impl View, E>. Used by generated code. - Middleware
- Middleware trait; implemented for all matching async functions/closures.
- OrNot
Found - Convert
Noneinto a 404. - Part
- Something that can be placed inside an element macro.
- Session
Store - Session storage backend.
- View
- Anything renderable.
Functions§
- accept
acceptattribute.- action
actionattribute.- 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/docsis active on/docs/routing. - alt
altattribute.- aria
aria-*attribute:aria("label", "Close")→aria-label="Close".- as_
asattribute.- async
r#async(true)for scripts.- attr
- Any attribute:
attr("hx-get", "/x"). Event handler attributes (on*) are refused here; seeraw_attr. - attr_if
- Include
attronly whenconditionholds. - autocomplete
autocompleteattribute.- autofocus
autofocusboolean attribute.- autoplay
autoplayboolean attribute.- cache
- Memoize an async computation in the data cache.
Memoize
fin the global data cache. - charset
charsetattribute.- checked
checkedboolean attribute.- class
class("a b"),class(styles.card),class(["a", "b"]),class([("active", is_active)]). Multipleclassparts are merged.- cols
colsattribute.- colspan
colspanattribute.- constant_
time_ eq - Constant-time byte comparison (for tokens).
- content
contentattribute.- controls
controlsboolean attribute.- cors
- CORS middleware, including preflight handling.
- crossorigin
crossoriginattribute.- csrf
- Double-submit CSRF token protection for unsafe methods.
- d
dattribute.- data
data-*attribute:data("id", "42")→data-id="42".- datetime
datetimeattribute.- decoding
decodingattribute.- defer
deferboolean attribute.- dir
dirattribute.- disabled
disabledboolean attribute.- download
downloadattribute.- each
- Render every item of an iterator.
- enctype
enctypeattribute.- enterkeyhint
enterkeyhintattribute.- escape_
attr - Escape attribute values (
&,<,>,",'). - escape_
text - Escape text content (
&,<,>). - fetchpriority
fetchpriorityattribute.- fill
fillattribute.- for
r#for("email")- for_
forattribute of<label>.- form_
attr formattribute.- fragment_
of - Collect any iterator of views into a fragment.
- height
heightattribute.- hidden
hiddenboolean attribute.- href
hrefattribute.- http_
equiv http-equivattribute.- id
idattribute.- inert
inertboolean attribute.- inputmode
inputmodeattribute.- integrity
integrityattribute.- 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_jsonmust be JSON. - ismap
ismapboolean attribute.- key
- Stable identity for list items, used by client-side hydration.
- label_
attr labelattribute.- lang
langattribute.- link_
is_ active - Whether a link to
hrefis active onpath, exactly or as a prefix. - list
listattribute.- loading
loadingattribute.- mark_
active_ links - Apply
active_class/active_class_prefixforpathto a view tree (async boundaries are left to the client runtime). - max
maxattribute.- maxlength
maxlengthattribute.- media
mediaattribute.- method
methodattribute.- min
minattribute.- minlength
minlengthattribute.- multiple
multipleboolean attribute.- muted
mutedboolean attribute.- name
nameattribute.- nomodule
nomoduleboolean attribute.- nonce
nonceattribute.- not_
found - Render the nearest
not-found.rswith status 404. - novalidate
novalidateboolean attribute.- on
- Declarative client event binding for interactive islands:
on("click", "increment")→data-nr-on-click="increment". - open
openboolean attribute.- parse_
pattern - Convert
/users/:id,/files/*pathor/users/[id]into a pattern. - pattern
patternattribute.- permanent_
redirect - Permanent redirect (308, method preserved).
- placeholder
placeholderattribute.- playsinline
playsinlineboolean 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
checkreturns false the user is redirected tologin(with?next=set) — or receives 401 for non-GET requests. - random_
hex nrandom bytes from the operating system CSPRNG, hex encoded.- rate_
limit - In-memory token bucket rate limiting (per process). Responds 429 with
Retry-Afterwhen 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
readonlyboolean attribute.- redirect
- Temporary redirect (307, method preserved).
- referrerpolicy
referrerpolicyattribute.- rel
relattribute.- 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
requiredboolean 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 idsknown: only what it is missing is kept. Every per-class stylesheet rendered so far (component libraries’ too) is considered, besidessheets. - revalidate_
path - ISR / data-cache invalidation.
Re-render
pathon 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
reversedboolean attribute.- role
roleattribute.- rows
rowsattribute.- rowspan
rowspanattribute.- run
- Load
.envfiles, 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/orpublic/, 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
selectedboolean 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
sizesattribute.- slot_
attr slotattribute.- spellcheck
spellcheckattribute.- src
srcattribute.- srcset
srcsetattribute.- 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 withaction_resultshow what the action returned, and the form getsdata-nr-state="success"for styling. - step
stepattribute.- stream_
document - Render a complete document as a stream of chunks.
- stroke
strokeattribute.- style
styleattribute.- suspense
- An async boundary.
fallbackrenders immediately;contentis awaited. - tabindex
tabindexattribute.- target
targetattribute.- title
titleattribute.- translate
translateattribute.- type
r#type("submit")- type_
typeattribute (also available asr#type).- value
valueattribute.- view_
box viewBoxattribute.- when
- Render
f()only whenconditionis true. - width
widthattribute.- wrap
wrapattribute.- xmlns
xmlnsattribute.
Type Aliases§
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
wasm32fails at compile time instead of leaking server logic or secrets into a client bundle. - server_
action - Expose an async function as a server action.