Skip to main content

next_rust_server/
app.rs

1//! Route definitions, application builder and request dispatch.
2//!
3//! The types in the first half of this module are the contract between the
4//! build-time code generator and the runtime. Application code normally never
5//! constructs them by hand: `next_rust::routes!()` expands to generated code
6//! that does.
7
8use std::collections::{HashMap, HashSet};
9use std::future::Future;
10use std::path::PathBuf;
11use std::sync::{Arc, Mutex};
12
13use http::{Method, StatusCode};
14use next_rust_cache::{Cache, CacheStore, MemoryStore};
15use next_rust_core::{Config, Environment};
16use next_rust_router::{Matcher, Params, PatternSegment, RoutePattern, SegmentKind, parse_segment};
17use next_rust_view::{Children, Metadata, Node, Slots};
18
19use crate::context::Ctx;
20use crate::error::Result;
21use crate::middleware::{BoxFuture, Endpoint, FnMiddleware, Middleware, Next};
22use crate::request::Request;
23use crate::response::{IntoResponse, Response};
24use crate::seo::{Robots, Sitemap};
25
26pub type RenderFn = fn(Ctx) -> BoxFuture<Result<Node>>;
27pub type LayoutFn = fn(Ctx, Children, Slots) -> BoxFuture<Result<Node>>;
28pub type LoadingFn = fn(Ctx) -> Node;
29pub type ErrorFn = fn(Ctx, ErrorInfo) -> Node;
30pub type MetadataFn = fn(Ctx) -> BoxFuture<Result<Metadata>>;
31pub type MiddlewareFn = fn(Request, Next) -> BoxFuture<Response>;
32pub type HandlerFn = fn(Request) -> BoxFuture<Response>;
33pub type ParamsFn = fn() -> BoxFuture<Result<Vec<Params>>>;
34pub type SitemapFn = fn() -> BoxFuture<Sitemap>;
35pub type RobotsFn = fn() -> BoxFuture<Robots>;
36
37/// Rendering mode declared by a page: `pub const RENDERING: Rendering = Rendering::Dynamic;`
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
39pub enum Rendering {
40    #[default]
41    Auto,
42    Static,
43    Dynamic,
44}
45
46/// Information passed to `error.rs` / `global-error.rs`.
47#[derive(Debug, Clone)]
48pub struct ErrorInfo {
49    pub status: u16,
50    /// User-safe message in production, detailed message in development.
51    pub message: String,
52    /// Random identifier that is also written to the server log.
53    pub digest: String,
54}
55
56impl ErrorInfo {
57    pub(crate) fn from_error(e: &crate::Error, dev: bool) -> Self {
58        let digest = crate::random_hex(6);
59        let status = e.status().as_u16();
60        if status >= 500 {
61            crate::log::error(&format!("render error [{digest}]: {}", e.detailed_message()));
62        }
63        ErrorInfo { status, message: if dev { e.detailed_message() } else { e.public_message() }, digest }
64    }
65}
66
67/// Files attached to one route segment (directory).
68#[derive(Clone, Default)]
69pub struct SegmentDef {
70    pub layout: Option<LayoutFn>,
71    pub template: Option<LayoutFn>,
72    pub loading: Option<LoadingFn>,
73    pub error: Option<ErrorFn>,
74    pub not_found: Option<RenderFn>,
75    pub metadata: Option<MetadataFn>,
76    /// Nested `middleware.rs` (never the app-root one, which is global).
77    pub middleware: Option<MiddlewareFn>,
78    pub slots: Vec<SlotDef>,
79    /// Identity of `layout` (its file, relative to the project), used to
80    /// recognize a layout the browser already shows.
81    pub layout_id: &'static str,
82    /// The build found that `layout` (and its `load`) reads nothing from the
83    /// request, so client navigations may keep it on screen instead of
84    /// rendering it again.
85    pub layout_reusable: bool,
86    /// `layout` reads route parameters (`Params` / `Path`): it is only reused
87    /// while every parameter keeps its value.
88    pub layout_uses_params: bool,
89}
90
91#[derive(Clone)]
92pub struct SlotDef {
93    pub name: &'static str,
94    /// The matching slot page or its `default.rs`.
95    pub render: Option<RenderFn>,
96}
97
98pub enum PageBody {
99    Rust(RenderFn),
100    /// Contents of `page.html`.
101    Html(&'static str),
102}
103
104pub struct PageDef {
105    /// Filesystem-style pattern, e.g. `/blog/[slug]`.
106    pub pattern: &'static str,
107    pub source: &'static str,
108    pub body: PageBody,
109    /// Root → leaf segments.
110    pub segments: Vec<SegmentDef>,
111    pub metadata: Option<MetadataFn>,
112    /// Resolved by the build (`Auto` is treated as `Dynamic`).
113    pub rendering: Rendering,
114    pub revalidate: Option<u64>,
115    pub generate_params: Option<ParamsFn>,
116    /// Render params not returned by `generate_params` on demand.
117    pub dynamic_params: bool,
118    /// Cache tags for `revalidate_tag`.
119    pub tags: &'static [&'static str],
120    /// Set for intercepting routes: the URL pattern they intercept from.
121    pub intercept_from: Option<&'static str>,
122}
123
124pub struct ApiDef {
125    pub pattern: &'static str,
126    pub source: &'static str,
127    pub handlers: Vec<(Method, HandlerFn)>,
128    pub middleware: Vec<MiddlewareFn>,
129}
130
131pub struct ActionDef {
132    /// Stable identifier (`module::path::fn_name`).
133    pub id: &'static str,
134    pub handler: HandlerFn,
135}
136
137/// Everything discovered in the app directory.
138#[derive(Default)]
139pub struct Routes {
140    pub pages: Vec<PageDef>,
141    pub apis: Vec<ApiDef>,
142    pub actions: Vec<ActionDef>,
143    /// `not-found.rs` / `layout.rs` / `metadata` of the app root, used for unmatched URLs.
144    pub root: SegmentDef,
145    /// App-root `middleware.rs`: runs for every request, before routing.
146    pub middleware: Option<MiddlewareFn>,
147    pub global_error: Option<ErrorFn>,
148    pub sitemap: Option<SitemapFn>,
149    pub robots: Option<RobotsFn>,
150    /// Absolute project root recorded at build time (fallback for config discovery).
151    pub project_root: Option<&'static str>,
152    /// Configuration and static files compiled into release binaries.
153    pub embedded: Option<&'static crate::embed::Embedded>,
154    /// Changes whenever the application's source changes. Part of every layout
155    /// key, so a browser never keeps a layout from an older deployment.
156    pub build_id: &'static str,
157    /// Reads `next-rust.toml` at runtime. Set by the generated code for
158    /// development builds; release builds embed their configuration as JSON
159    /// and leave this `None`, so no TOML parser is linked.
160    pub toml: Option<next_rust_core::config::TomlParser>,
161    /// Stylesheets added to every page, such as the generated Tailwind CSS.
162    pub stylesheets: &'static [&'static next_rust_view::Stylesheet],
163    /// Release builds with Tailwind: `(class, short name)` pairs sorted by
164    /// class, applied to every page this app renders.
165    pub class_names: next_rust_view::class_names::ClassNames,
166}
167
168pub(crate) type CustomHandlers = Vec<(Option<Method>, Arc<dyn Endpoint>)>;
169
170#[derive(Clone, Copy, Debug)]
171pub(crate) enum Target {
172    Page(usize),
173    Api(usize),
174    Custom(usize),
175}
176
177struct CustomRoute {
178    pattern: String,
179    method: Option<Method>,
180    endpoint: Arc<dyn Endpoint>,
181}
182
183pub(crate) struct Intercept {
184    pub page: usize,
185    pub target: Matcher<()>,
186    pub context: RoutePattern,
187}
188
189pub(crate) struct AppInner {
190    pub routes: Routes,
191    pub matcher: Matcher<Target>,
192    pub intercepts: Vec<Intercept>,
193    pub customs: Vec<CustomHandlers>,
194    pub config: Arc<Config>,
195    pub env: Environment,
196    pub public_dir: PathBuf,
197    pub client_dir: PathBuf,
198    pub dev_status_file: PathBuf,
199    /// Files compiled into the binary; `None` reads from disk.
200    pub embedded: Option<&'static crate::embed::Embedded>,
201    pub cache: Cache,
202    pub page_store: Arc<dyn CacheStore>,
203    pub global_stack: Arc<[Arc<dyn Middleware>]>,
204    pub page_stacks: Vec<Arc<[Arc<dyn Middleware>]>>,
205    pub api_stacks: Vec<Arc<[Arc<dyn Middleware>]>>,
206    /// Keyed action id → index into `routes.actions`.
207    pub(crate) actions: HashMap<crate::action_token::ActionKey, usize>,
208    pub revalidating: Mutex<HashSet<String>>,
209    pub static_params: Mutex<HashMap<usize, Arc<Vec<Params>>>>,
210    pub plugins: Vec<Arc<dyn crate::plugin::Plugin>>,
211    pub public_env_json: Option<String>,
212}
213
214/// A configured application. Cheap to clone.
215#[derive(Clone)]
216pub struct App {
217    pub(crate) inner: Arc<AppInner>,
218}
219
220/// Builder returned by [`App::new`].
221pub struct AppBuilder {
222    routes: Routes,
223    config: Option<Config>,
224    env: Option<Environment>,
225    middleware: Vec<Arc<dyn Middleware>>,
226    cache: Option<Cache>,
227    page_store: Option<Arc<dyn CacheStore>>,
228    customs: Vec<CustomRoute>,
229    plugins: Vec<Arc<dyn crate::plugin::Plugin>>,
230}
231
232/// Convert `/users/:id`, `/files/*path` or `/users/[id]` into a pattern.
233pub fn parse_pattern(pattern: &str) -> std::result::Result<RoutePattern, String> {
234    let mut segs = Vec::new();
235    for part in pattern.split('/').filter(|p| !p.is_empty()) {
236        let seg = if let Some(name) = part.strip_prefix(':') {
237            PatternSegment::Dynamic(name.to_owned())
238        } else if let Some(name) = part.strip_prefix('*') {
239            match name.strip_suffix('?') {
240                Some(n) => PatternSegment::OptionalCatchAll(n.to_owned()),
241                None => PatternSegment::CatchAll(name.to_owned()),
242            }
243        } else {
244            match parse_segment(part)? {
245                Some(SegmentKind::Static(s)) => PatternSegment::Static(s),
246                Some(SegmentKind::Dynamic(s)) => PatternSegment::Dynamic(s),
247                Some(SegmentKind::CatchAll(s)) => PatternSegment::CatchAll(s),
248                Some(SegmentKind::OptionalCatchAll(s)) => PatternSegment::OptionalCatchAll(s),
249                _ => return Err(format!("unsupported segment `{part}` in pattern `{pattern}`")),
250            }
251        };
252        segs.push(seg);
253    }
254    Ok(RoutePattern(segs))
255}
256
257impl App {
258    /// Start building an application from generated routes.
259    #[allow(clippy::new_ret_no_self)]
260    pub fn new(routes: Routes) -> AppBuilder {
261        next_rust_view::class_names::set_class_names(routes.class_names);
262        crate::internal::install_short_component_names(routes.class_names);
263        AppBuilder {
264            routes,
265            config: None,
266            env: None,
267            middleware: Vec::new(),
268            cache: None,
269            page_store: None,
270            customs: Vec::new(),
271            plugins: Vec::new(),
272        }
273    }
274
275    pub fn config(&self) -> &Config {
276        &self.inner.config
277    }
278
279    pub fn environment(&self) -> Environment {
280        self.inner.env
281    }
282
283    pub fn cache(&self) -> &Cache {
284        &self.inner.cache
285    }
286
287    /// Handle one request. This is the adapter surface: the built-in server,
288    /// tests and serverless adapters all call it.
289    pub async fn handle(&self, mut req: Request) -> Response {
290        let inner = self.inner.clone();
291        let nonce = crate::random_hex(16);
292        req.insert_extension(crate::CspNonce(nonce.clone()));
293        req.limit_body(inner.config.server.body_limit);
294
295        if let Some(res) = self.pre_routing(&mut req).await {
296            return self.finish(res, &req_cookies_placeholder(), &nonce, "");
297        }
298        let cookies = req.cookies().clone();
299        let path = req.path().to_owned();
300        let endpoint: Arc<dyn Endpoint> = Arc::new(RouteEndpoint { inner: inner.clone() });
301        let res = Next::new(inner.global_stack.clone(), endpoint).run(req).await;
302        self.finish(res, &cookies, &nonce, &path)
303    }
304
305    /// Framework assets, base path, configured redirects and trailing slashes.
306    async fn pre_routing(&self, req: &mut Request) -> Option<Response> {
307        let inner = &self.inner;
308        let config = &inner.config;
309
310        let base = config.app.base_path.as_str();
311        if !base.is_empty() {
312            let path = req.path().to_owned();
313            let stripped = if path == base {
314                "/".to_owned()
315            } else if let Some(rest) = path.strip_prefix(base).filter(|r| r.starts_with('/')) {
316                rest.to_owned()
317            } else {
318                return Some(Response::not_found());
319            };
320            let query = req.uri().query().map(|q| format!("?{q}")).unwrap_or_default();
321            if req.set_path(&format!("{stripped}{query}")).is_err() {
322                return Some(Response::status(400));
323            }
324        }
325
326        let path = req.path();
327        if path.starts_with("/_nr/")
328            && let Some(res) = crate::internal::handle(inner, req).await
329        {
330            return Some(res);
331        }
332
333        for rule in &config.redirects {
334            if let Some(dest) = crate::redirects::apply(&rule.source, &rule.destination, path) {
335                let query = req.uri().query().map(|q| format!("?{q}")).unwrap_or_default();
336                let location = if dest.contains('?') { dest } else { format!("{dest}{query}") };
337                return Some(if rule.permanent {
338                    Response::permanent_redirect(&location)
339                } else {
340                    Response::redirect(&location)
341                });
342            }
343        }
344
345        if path.len() > 1 {
346            let has_slash = path.ends_with('/');
347            let looks_like_file = path.rsplit('/').next().is_some_and(|last| last.contains('.'));
348            if has_slash != config.app.trailing_slash && !looks_like_file {
349                let fixed = if has_slash { path.trim_end_matches('/').to_owned() } else { format!("{path}/") };
350                let fixed = if fixed.is_empty() { "/".to_owned() } else { fixed };
351                let query = req.uri().query().map(|q| format!("?{q}")).unwrap_or_default();
352                return Some(Response::permanent_redirect(&format!("{base}{fixed}{query}")));
353            }
354        }
355        None
356    }
357
358    fn finish(&self, mut res: Response, cookies: &crate::Cookies, nonce: &str, path: &str) -> Response {
359        let config = &self.inner.config;
360        crate::action_token::seal(&mut res, cookies, config.security.action_token_ttl, config.security.csrf);
361        for value in cookies.set_cookie_headers() {
362            res.append_header("set-cookie", &value);
363        }
364        if !path.is_empty() {
365            for rule in &config.headers {
366                if crate::redirects::matches(&rule.source, path) {
367                    for (k, v) in &rule.headers {
368                        res.set_header(k, v);
369                    }
370                }
371            }
372        }
373        if config.security.headers {
374            crate::middleware::apply_security_headers(
375                &mut res,
376                config.security.csp.as_deref(),
377                nonce,
378                config.security.hsts_max_age,
379            );
380        }
381        res
382    }
383
384    /// Re-render `path` on its next request (ISR) and drop data-cache
385    /// entries stored under the same path key.
386    pub async fn revalidate_path(&self, path: &str) -> bool {
387        let path = if path.len() > 1 { path.trim_end_matches('/') } else { path };
388        let page = self.inner.page_store.delete(&next_rust_cache::CacheKey::page(path)).await.unwrap_or(false);
389        page | self.inner.cache.revalidate_path(path).await.unwrap_or(false)
390    }
391
392    /// Invalidate pages and data tagged with `tag`. Returns the number of entries removed.
393    pub async fn revalidate_tag(&self, tag: &str) -> usize {
394        self.inner.page_store.delete_tag(tag).await.unwrap_or(0)
395            + self.inner.cache.revalidate_tag(tag).await.unwrap_or(0)
396    }
397
398    /// Render every static route without keeping the result: used by
399    /// `next-rust build` to check that static generation succeeds.
400    pub async fn export(&self) -> std::result::Result<crate::export::ExportReport, String> {
401        crate::export::prerender(&self.inner, &MemoryStore::new(usize::MAX)).await
402    }
403
404    /// Render every static route into the page cache, so the first visitor
405    /// gets a cached page. Production servers do this in the background at
406    /// startup.
407    pub async fn prerender(&self) -> std::result::Result<crate::export::ExportReport, String> {
408        crate::export::prerender(&self.inner, self.inner.page_store.as_ref()).await
409    }
410
411    /// Route table as `(kind, pattern, source)` for diagnostics.
412    pub fn route_table(&self) -> Vec<(&'static str, &'static str, &'static str)> {
413        let r = &self.inner.routes;
414        let mut out: Vec<_> = r.pages.iter().map(|p| ("page", p.pattern, p.source)).collect();
415        out.extend(r.apis.iter().map(|a| ("api", a.pattern, a.source)));
416        out
417    }
418}
419
420fn req_cookies_placeholder() -> crate::Cookies {
421    crate::Cookies::default()
422}
423
424/// Find the configuration.
425///
426/// `NEXT_RUST_CONFIG` wins. A release binary then uses the configuration it
427/// was built with, rooted at the working directory, so it runs on its own.
428/// Otherwise the working directory (and its ancestors) is searched, then the
429/// project root recorded at build time, so `./target/debug/my-app` works from
430/// any directory.
431pub fn discover_config(
432    project_root: Option<&str>,
433    embedded: Option<&crate::embed::Embedded>,
434    toml: Option<next_rust_core::config::TomlParser>,
435) -> std::result::Result<Config, String> {
436    let start = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
437    if std::env::var_os("NEXT_RUST_CONFIG").is_none()
438        && let Some((text, json)) = embedded.and_then(|e| e.config)
439    {
440        let parsed = match (json, toml) {
441            (true, _) => Config::from_json_str(text),
442            (false, Some(parse)) => parse(text),
443            (false, None) => Err("embedded TOML configuration needs a TOML parser".to_owned()),
444        };
445        let mut config = parsed.map_err(|e| format!("embedded configuration: {e}"))?;
446        config.root = start;
447        config.apply_env_overrides();
448        return Ok(config);
449    }
450    let from_cwd = Config::discover_with(&start, toml).map_err(|e| e.to_string())?;
451    if from_cwd.source.is_some() || from_cwd.app_dir().is_dir() {
452        return Ok(from_cwd);
453    }
454    match project_root {
455        Some(root) if std::path::Path::new(root).is_dir() => {
456            Config::discover_with(root, toml).map_err(|e| e.to_string())
457        }
458        _ => Ok(from_cwd),
459    }
460}
461
462impl AppBuilder {
463    pub(crate) fn project_root(&self) -> Option<&'static str> {
464        self.routes.project_root
465    }
466
467    pub(crate) fn embedded(&self) -> Option<&'static crate::embed::Embedded> {
468        self.routes.embedded
469    }
470
471    pub(crate) fn toml_parser(&self) -> Option<next_rust_core::config::TomlParser> {
472        self.routes.toml
473    }
474
475    /// Use an explicit configuration instead of discovering `next-rust.toml`.
476    pub fn config(mut self, config: Config) -> Self {
477        self.config = Some(config);
478        self
479    }
480
481    pub fn environment(mut self, env: Environment) -> Self {
482        self.env = Some(env);
483        self
484    }
485
486    /// Add global middleware (runs before `middleware.rs` files, in order).
487    pub fn middleware(mut self, mw: impl Middleware) -> Self {
488        self.middleware.push(Arc::new(mw));
489        self
490    }
491
492    /// Data cache (default: in-memory).
493    pub fn cache(mut self, cache: Cache) -> Self {
494        self.cache = Some(cache);
495        self
496    }
497
498    /// Store for statically rendered pages (default: files in the build
499    /// output in production, memory in development).
500    pub fn page_store(mut self, store: impl CacheStore) -> Self {
501        self.page_store = Some(Arc::new(store));
502        self
503    }
504
505    pub fn plugin(mut self, plugin: impl crate::plugin::Plugin) -> Self {
506        self.plugins.push(Arc::new(plugin));
507        self
508    }
509
510    /// Register a handler programmatically for any method.
511    /// Patterns accept `/users/:id`, `/files/*path` or `/users/[id]`.
512    pub fn route<H, Fut, R>(self, method: Method, pattern: &str, handler: H) -> Self
513    where
514        H: Fn(Request) -> Fut + Send + Sync + 'static,
515        Fut: Future<Output = R> + Send + 'static,
516        R: IntoResponse,
517    {
518        self.custom(Some(method), pattern, handler)
519    }
520
521    pub fn get<H, Fut, R>(self, pattern: &str, handler: H) -> Self
522    where
523        H: Fn(Request) -> Fut + Send + Sync + 'static,
524        Fut: Future<Output = R> + Send + 'static,
525        R: IntoResponse,
526    {
527        self.custom(Some(Method::GET), pattern, handler)
528    }
529
530    pub fn post<H, Fut, R>(self, pattern: &str, handler: H) -> Self
531    where
532        H: Fn(Request) -> Fut + Send + Sync + 'static,
533        Fut: Future<Output = R> + Send + 'static,
534        R: IntoResponse,
535    {
536        self.custom(Some(Method::POST), pattern, handler)
537    }
538
539    /// WebSocket endpoint: `.ws("/socket", |socket| async move { .. })`.
540    #[cfg(feature = "websocket")]
541    pub fn ws<H, Fut>(self, pattern: &str, handler: H) -> Self
542    where
543        H: Fn(crate::ws::WebSocket) -> Fut + Clone + Send + Sync + 'static,
544        Fut: Future<Output = ()> + Send + 'static,
545    {
546        self.custom(Some(Method::GET), pattern, move |req: Request| {
547            let handler = handler.clone();
548            async move { crate::ws::upgrade(req, handler) }
549        })
550    }
551
552    fn custom<H, Fut, R>(mut self, method: Option<Method>, pattern: &str, handler: H) -> Self
553    where
554        H: Fn(Request) -> Fut + Send + Sync + 'static,
555        Fut: Future<Output = R> + Send + 'static,
556        R: IntoResponse,
557    {
558        let handler = Arc::new(handler);
559        let endpoint = move |req: Request| {
560            let handler = handler.clone();
561            async move { handler(req).await.into_response() }
562        };
563        self.customs.push(CustomRoute { pattern: pattern.to_owned(), method, endpoint: Arc::new(endpoint) });
564        self
565    }
566
567    /// Validate routes and build the application.
568    pub fn build(self) -> std::result::Result<App, String> {
569        let env = self.env.unwrap_or_else(Environment::from_env);
570        let config = match self.config {
571            Some(c) => c,
572            None => discover_config(self.routes.project_root, self.routes.embedded, self.routes.toml)?,
573        };
574        crate::set_dev(env.is_dev());
575        let json = match config.logging.format {
576            next_rust_core::config::LogFormat::Json => true,
577            next_rust_core::config::LogFormat::Pretty => false,
578            next_rust_core::config::LogFormat::Auto => !env.is_dev(),
579        };
580        // Production prints only errors unless `[logging]` says otherwise.
581        crate::log::configure(json, config.logging.level(env));
582        crate::set_trust_proxy(config.server.trust_proxy);
583
584        let mut matcher = Matcher::new();
585        let mut intercepts = Vec::new();
586        for (i, page) in self.routes.pages.iter().enumerate() {
587            let pattern = parse_pattern(page.pattern)?;
588            if let Some(from) = page.intercept_from {
589                let mut target = Matcher::new();
590                target.insert(pattern.segments(), ()).map_err(|e| format!("{}: {e}", page.source))?;
591                intercepts.push(Intercept { page: i, target, context: parse_pattern(from)? });
592                continue;
593            }
594            matcher
595                .insert(pattern.segments(), Target::Page(i))
596                .map_err(|e| format!("route {} ({}): {e}", page.pattern, page.source))?;
597        }
598        for (i, api) in self.routes.apis.iter().enumerate() {
599            let pattern = parse_pattern(api.pattern)?;
600            matcher
601                .insert(pattern.segments(), Target::Api(i))
602                .map_err(|e| format!("route {} ({}): {e}", api.pattern, api.source))?;
603        }
604        // Programmatic routes: group handlers by pattern.
605        let mut customs: Vec<CustomHandlers> = Vec::new();
606        let mut custom_index: HashMap<String, usize> = HashMap::new();
607        for c in self.customs {
608            let pattern = parse_pattern(&c.pattern)?;
609            let shape = pattern.shape();
610            let idx = match custom_index.get(&shape) {
611                Some(i) => *i,
612                None => {
613                    let i = customs.len();
614                    matcher
615                        .insert(pattern.segments(), Target::Custom(i))
616                        .map_err(|e| format!("route {}: {e} (conflicts with a file route)", c.pattern))?;
617                    customs.push(Vec::new());
618                    custom_index.insert(shape, i);
619                    i
620                }
621            };
622            customs[idx].push((c.method, c.endpoint));
623        }
624
625        let mut global: Vec<Arc<dyn Middleware>> = self.middleware;
626        for p in &self.plugins {
627            global.extend(p.middleware());
628        }
629        if let Some(mw) = self.routes.middleware {
630            global.push(Arc::new(FnMiddleware(mw)));
631        }
632        let stack_of = |fns: Vec<MiddlewareFn>| -> Arc<[Arc<dyn Middleware>]> {
633            fns.into_iter().map(|f| Arc::new(FnMiddleware(f)) as Arc<dyn Middleware>).collect::<Vec<_>>().into()
634        };
635        let page_stacks = self
636            .routes
637            .pages
638            .iter()
639            .map(|p| stack_of(p.segments.iter().filter_map(|s| s.middleware).collect()))
640            .collect();
641        let api_stacks = self.routes.apis.iter().map(|a| stack_of(a.middleware.clone())).collect();
642        crate::action_token::check_secret()?;
643        if !self.routes.actions.is_empty() && !env.is_dev() && !crate::action_token::keys().from_env {
644            crate::log::warn(&format!(
645                "{} is not set: server-action links are signed with a random key, so open pages stop working \
646                 after a restart and links don't work across instances",
647                crate::SECRET_ENV
648            ));
649        }
650        let actions =
651            self.routes.actions.iter().enumerate().map(|(i, a)| (crate::action_token::action_key(a.id), i)).collect();
652
653        let output_dir = config.output_dir();
654        let page_store: Arc<dyn CacheStore> = match self.page_store {
655            Some(s) => s,
656            None if env.is_dev() => Arc::new(MemoryStore::new(1000)),
657            // Production keeps pages in memory: the binary writes no files.
658            None => Arc::new(MemoryStore::new(10_000)),
659        };
660        let cache = self.cache.unwrap_or_default();
661        next_rust_cache::install_global(cache.clone());
662        let _ = crate::PAGE_STORE.set(page_store.clone());
663
664        let public_env = next_rust_core::env::EnvVars::load(&config.root, env, &config.env.public_prefix)
665            .map(|e| e.public())
666            .unwrap_or_default();
667        let public_env_json = (!public_env.is_empty()).then(|| serde_json::to_string(&public_env).unwrap_or_default());
668
669        let inner = AppInner {
670            public_dir: config.public_dir(),
671            client_dir: config.root.join("client"),
672            dev_status_file: output_dir.join("dev/status.json"),
673            embedded: self.routes.embedded.filter(|e| !e.is_empty()),
674            routes: self.routes,
675            matcher,
676            intercepts,
677            customs,
678            env,
679            cache,
680            page_store,
681            global_stack: global.into(),
682            page_stacks,
683            api_stacks,
684            actions,
685            revalidating: Mutex::new(HashSet::new()),
686            static_params: Mutex::new(HashMap::new()),
687            plugins: self.plugins,
688            public_env_json,
689            config: Arc::new(config),
690        };
691        for p in &inner.plugins {
692            p.on_start(&inner.config);
693        }
694        Ok(App { inner: Arc::new(inner) })
695    }
696}
697
698/// Final endpoint of the global middleware chain: routing.
699struct RouteEndpoint {
700    inner: Arc<AppInner>,
701}
702
703impl Endpoint for RouteEndpoint {
704    fn call(&self, req: Request) -> BoxFuture<Response> {
705        let inner = self.inner.clone();
706        Box::pin(async move { dispatch(inner, req).await })
707    }
708}
709
710async fn dispatch(inner: Arc<AppInner>, mut req: Request) -> Response {
711    let path = req.path().to_owned();
712
713    if path.starts_with("/_nr/action/") {
714        return crate::actions::handle(&inner, req).await;
715    }
716    if req.method() == Method::GET || req.method() == Method::HEAD {
717        if path == "/sitemap.xml"
718            && let Some(f) = inner.routes.sitemap
719        {
720            return f().await.into_response();
721        }
722        if path == "/robots.txt"
723            && let Some(f) = inner.routes.robots
724        {
725            return f().await.into_response();
726        }
727    }
728
729    // Intercepting routes apply to client-side navigations only.
730    if let (Some(from), Some("1")) = (req.header("x-nr-from").map(str::to_owned), req.header("x-nr-nav")) {
731        for ic in &inner.intercepts {
732            if let Some(hit) = ic.target.at(&path)
733                && context_matches(&ic.context, &from)
734            {
735                req.set_params(hit.params);
736                let idx = ic.page;
737                // Tells the client runtime this HTML depends on the page it
738                // navigated from, so it isn't reused from other pages.
739                let mut res = run_page(&inner, idx, req).await;
740                res.set_header("x-nr-intercepted", "1");
741                return res;
742            }
743        }
744    }
745
746    let hit = inner.matcher.at(&path).map(|m| (*m.value, m.params));
747    match hit {
748        Some((Target::Page(i), params)) => {
749            if req.method() != Method::GET && req.method() != Method::HEAD {
750                return Response::text("Method Not Allowed").with_status(405).with_header("allow", "GET, HEAD");
751            }
752            req.set_params(params);
753            run_page(&inner, i, req).await
754        }
755        Some((Target::Api(i), params)) => {
756            req.set_params(params);
757            let stack = inner.api_stacks[i].clone();
758            let endpoint = ApiEndpoint { inner: inner.clone(), index: i };
759            Next::new(stack, Arc::new(endpoint)).run(req).await
760        }
761        Some((Target::Custom(i), params)) => {
762            req.set_params(params);
763            let handlers = &inner.customs[i];
764            let method = req.method().clone();
765            let found = handlers.iter().find(|(m, _)| {
766                m.as_ref().is_none_or(|m| *m == method || (method == Method::HEAD && *m == Method::GET))
767            });
768            match found {
769                Some((_, ep)) => {
770                    let head = method == Method::HEAD;
771                    let res = ep.call(req).await;
772                    if head { strip_body(res) } else { res }
773                }
774                None => method_not_allowed(handlers.iter().filter_map(|(m, _)| m.clone()).collect()),
775            }
776        }
777        None => {
778            if (req.method() == Method::GET || req.method() == Method::HEAD)
779                && let Some(res) = crate::static_files::serve_public(&inner, &req).await
780            {
781                return res;
782            }
783            crate::render::not_found_response(&inner, &req).await
784        }
785    }
786}
787
788fn context_matches(context: &RoutePattern, from: &str) -> bool {
789    let from = from.split('?').next().unwrap_or("");
790    let segs: Vec<&str> = from.split('/').filter(|s| !s.is_empty()).collect();
791    let n = context.segments().len();
792    if segs.len() < n {
793        return false;
794    }
795    let mut m = Matcher::new();
796    if m.insert(context.segments(), ()).is_err() {
797        return false;
798    }
799    m.at_segments(&segs[..n]).is_some()
800}
801
802async fn run_page(inner: &Arc<AppInner>, index: usize, req: Request) -> Response {
803    let stack = inner.page_stacks[index].clone();
804    let head = req.method() == Method::HEAD;
805    let endpoint = PageEndpoint { inner: inner.clone(), index };
806    let res = Next::new(stack, Arc::new(endpoint)).run(req).await;
807    if head { strip_body(res) } else { res }
808}
809
810struct PageEndpoint {
811    inner: Arc<AppInner>,
812    index: usize,
813}
814
815impl Endpoint for PageEndpoint {
816    fn call(&self, req: Request) -> BoxFuture<Response> {
817        let inner = self.inner.clone();
818        let index = self.index;
819        Box::pin(async move { crate::render::page_response(&inner, index, req).await })
820    }
821}
822
823struct ApiEndpoint {
824    inner: Arc<AppInner>,
825    index: usize,
826}
827
828impl Endpoint for ApiEndpoint {
829    fn call(&self, req: Request) -> BoxFuture<Response> {
830        let inner = self.inner.clone();
831        let index = self.index;
832        Box::pin(async move {
833            let api = &inner.routes.apis[index];
834            let method = req.method().clone();
835            if let Some((_, h)) = api.handlers.iter().find(|(m, _)| *m == method) {
836                return h(req).await;
837            }
838            if method == Method::HEAD
839                && let Some((_, h)) = api.handlers.iter().find(|(m, _)| *m == Method::GET)
840            {
841                return strip_body(h(req).await);
842            }
843            let mut allowed: Vec<Method> = api.handlers.iter().map(|(m, _)| m.clone()).collect();
844            if method == Method::OPTIONS {
845                allowed.push(Method::OPTIONS);
846                let list = allowed.iter().map(Method::as_str).collect::<Vec<_>>().join(", ");
847                return Response::status(204).with_header("allow", &list);
848            }
849            method_not_allowed(allowed)
850        })
851    }
852}
853
854fn method_not_allowed(allowed: Vec<Method>) -> Response {
855    let mut list: Vec<&str> = allowed.iter().map(Method::as_str).collect();
856    if list.contains(&"GET") && !list.contains(&"HEAD") {
857        list.push("HEAD");
858    }
859    Response::text("Method Not Allowed")
860        .with_status(StatusCode::METHOD_NOT_ALLOWED.as_u16())
861        .with_header("allow", &list.join(", "))
862}
863
864fn strip_body(mut res: Response) -> Response {
865    res.body = crate::response::Body::Empty;
866    res
867}