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    /// Classes the build knows a rule, script or static file for (sorted);
167    /// empty means every class is kept (see `next_rust_view::class_names::set_known_classes`).
168    pub known_classes: &'static [&'static str],
169}
170
171pub(crate) type CustomHandlers = Vec<(Option<Method>, Arc<dyn Endpoint>)>;
172
173#[derive(Clone, Copy, Debug)]
174pub(crate) enum Target {
175    Page(usize),
176    Api(usize),
177    Custom(usize),
178}
179
180struct CustomRoute {
181    pattern: String,
182    method: Option<Method>,
183    endpoint: Arc<dyn Endpoint>,
184}
185
186pub(crate) struct Intercept {
187    pub page: usize,
188    pub target: Matcher<()>,
189    pub context: RoutePattern,
190}
191
192pub(crate) struct AppInner {
193    pub routes: Routes,
194    pub matcher: Matcher<Target>,
195    pub intercepts: Vec<Intercept>,
196    pub customs: Vec<CustomHandlers>,
197    pub config: Arc<Config>,
198    pub env: Environment,
199    pub public_dir: PathBuf,
200    pub client_dir: PathBuf,
201    pub dev_status_file: PathBuf,
202    /// Files compiled into the binary; `None` reads from disk.
203    pub embedded: Option<&'static crate::embed::Embedded>,
204    pub cache: Cache,
205    pub page_store: Arc<dyn CacheStore>,
206    pub global_stack: Arc<[Arc<dyn Middleware>]>,
207    pub page_stacks: Vec<Arc<[Arc<dyn Middleware>]>>,
208    pub api_stacks: Vec<Arc<[Arc<dyn Middleware>]>>,
209    /// Keyed action id → index into `routes.actions`.
210    pub(crate) actions: HashMap<crate::action_token::ActionKey, usize>,
211    pub revalidating: Mutex<HashSet<String>>,
212    pub static_params: Mutex<HashMap<usize, Arc<Vec<Params>>>>,
213    pub plugins: Vec<Arc<dyn crate::plugin::Plugin>>,
214    pub public_env_json: Option<String>,
215}
216
217/// A configured application. Cheap to clone.
218#[derive(Clone)]
219pub struct App {
220    pub(crate) inner: Arc<AppInner>,
221}
222
223/// Builder returned by [`App::new`].
224pub struct AppBuilder {
225    routes: Routes,
226    config: Option<Config>,
227    env: Option<Environment>,
228    middleware: Vec<Arc<dyn Middleware>>,
229    cache: Option<Cache>,
230    page_store: Option<Arc<dyn CacheStore>>,
231    customs: Vec<CustomRoute>,
232    plugins: Vec<Arc<dyn crate::plugin::Plugin>>,
233}
234
235/// Convert `/users/:id`, `/files/*path` or `/users/[id]` into a pattern.
236pub fn parse_pattern(pattern: &str) -> std::result::Result<RoutePattern, String> {
237    let mut segs = Vec::new();
238    for part in pattern.split('/').filter(|p| !p.is_empty()) {
239        let seg = if let Some(name) = part.strip_prefix(':') {
240            PatternSegment::Dynamic(name.to_owned())
241        } else if let Some(name) = part.strip_prefix('*') {
242            match name.strip_suffix('?') {
243                Some(n) => PatternSegment::OptionalCatchAll(n.to_owned()),
244                None => PatternSegment::CatchAll(name.to_owned()),
245            }
246        } else {
247            match parse_segment(part)? {
248                Some(SegmentKind::Static(s)) => PatternSegment::Static(s),
249                Some(SegmentKind::Dynamic(s)) => PatternSegment::Dynamic(s),
250                Some(SegmentKind::CatchAll(s)) => PatternSegment::CatchAll(s),
251                Some(SegmentKind::OptionalCatchAll(s)) => PatternSegment::OptionalCatchAll(s),
252                _ => return Err(format!("unsupported segment `{part}` in pattern `{pattern}`")),
253            }
254        };
255        segs.push(seg);
256    }
257    Ok(RoutePattern(segs))
258}
259
260impl App {
261    /// Start building an application from generated routes.
262    #[allow(clippy::new_ret_no_self)]
263    pub fn new(routes: Routes) -> AppBuilder {
264        next_rust_view::class_names::set_class_names(routes.class_names);
265        next_rust_view::class_names::set_known_classes(routes.known_classes);
266        crate::internal::install_short_component_names(routes.class_names);
267        AppBuilder {
268            routes,
269            config: None,
270            env: None,
271            middleware: Vec::new(),
272            cache: None,
273            page_store: None,
274            customs: Vec::new(),
275            plugins: Vec::new(),
276        }
277    }
278
279    pub fn config(&self) -> &Config {
280        &self.inner.config
281    }
282
283    pub fn environment(&self) -> Environment {
284        self.inner.env
285    }
286
287    pub fn cache(&self) -> &Cache {
288        &self.inner.cache
289    }
290
291    /// Handle one request. This is the adapter surface: the built-in server,
292    /// tests and serverless adapters all call it.
293    pub async fn handle(&self, mut req: Request) -> Response {
294        let inner = self.inner.clone();
295        let nonce = crate::random_hex(16);
296        req.insert_extension(crate::CspNonce(nonce.clone()));
297        req.insert_extension(inner.config.clone());
298        req.limit_body(inner.config.server.body_limit);
299
300        if let Some(res) = self.pre_routing(&mut req).await {
301            return self.finish(res, &req_cookies_placeholder(), &nonce, "");
302        }
303        let cookies = req.cookies().clone();
304        let path = req.path().to_owned();
305        let endpoint: Arc<dyn Endpoint> = Arc::new(RouteEndpoint { inner: inner.clone() });
306        let res = Next::new(inner.global_stack.clone(), endpoint).run(req).await;
307        self.finish(res, &cookies, &nonce, &path)
308    }
309
310    /// Framework assets, base path, configured redirects and trailing slashes.
311    async fn pre_routing(&self, req: &mut Request) -> Option<Response> {
312        let inner = &self.inner;
313        let config = &inner.config;
314
315        let base = config.app.base_path.as_str();
316        if !base.is_empty() {
317            let path = req.path().to_owned();
318            let stripped = if path == base {
319                "/".to_owned()
320            } else if let Some(rest) = path.strip_prefix(base).filter(|r| r.starts_with('/')) {
321                rest.to_owned()
322            } else {
323                return Some(Response::not_found());
324            };
325            let query = req.uri().query().map(|q| format!("?{q}")).unwrap_or_default();
326            if req.set_path(&format!("{stripped}{query}")).is_err() {
327                return Some(Response::status(400));
328            }
329        }
330
331        let path = req.path();
332        if path.starts_with("/_next-rust/")
333            && let Some(res) = crate::internal::handle(inner, req).await
334        {
335            return Some(res);
336        }
337
338        for rule in &config.redirects {
339            if let Some(dest) = crate::redirects::apply(&rule.source, &rule.destination, path) {
340                let query = req.uri().query().map(|q| format!("?{q}")).unwrap_or_default();
341                let location = if dest.contains('?') { dest } else { format!("{dest}{query}") };
342                return Some(if rule.permanent {
343                    Response::permanent_redirect(&location)
344                } else {
345                    Response::redirect(&location)
346                });
347            }
348        }
349
350        if path.len() > 1 {
351            let has_slash = path.ends_with('/');
352            let looks_like_file = path.rsplit('/').next().is_some_and(|last| last.contains('.'));
353            if has_slash != config.app.trailing_slash && !looks_like_file {
354                let fixed = if has_slash { path.trim_end_matches('/').to_owned() } else { format!("{path}/") };
355                let fixed = if fixed.is_empty() { "/".to_owned() } else { fixed };
356                let query = req.uri().query().map(|q| format!("?{q}")).unwrap_or_default();
357                return Some(Response::permanent_redirect(&format!("{base}{fixed}{query}")));
358            }
359        }
360        None
361    }
362
363    fn finish(&self, mut res: Response, cookies: &crate::Cookies, nonce: &str, path: &str) -> Response {
364        let config = &self.inner.config;
365        crate::action_token::seal(&mut res, cookies, config.security.action_token_ttl, config.security.csrf);
366        for value in cookies.set_cookie_headers() {
367            res.append_header("set-cookie", &value);
368        }
369        if !path.is_empty() {
370            for rule in &config.headers {
371                if crate::redirects::matches(&rule.source, path) {
372                    for (k, v) in &rule.headers {
373                        res.set_header(k, v);
374                    }
375                }
376            }
377        }
378        if config.security.headers {
379            crate::middleware::apply_security_headers(
380                &mut res,
381                config.security.csp.as_deref(),
382                nonce,
383                config.security.hsts_max_age,
384            );
385        }
386        res
387    }
388
389    /// Re-render `path` on its next request (ISR) and drop data-cache
390    /// entries stored under the same path key.
391    pub async fn revalidate_path(&self, path: &str) -> bool {
392        let path = if path.len() > 1 { path.trim_end_matches('/') } else { path };
393        let page = self.inner.page_store.delete(&next_rust_cache::CacheKey::page(path)).await.unwrap_or(false);
394        page | self.inner.cache.revalidate_path(path).await.unwrap_or(false)
395    }
396
397    /// Invalidate pages and data tagged with `tag`. Returns the number of entries removed.
398    pub async fn revalidate_tag(&self, tag: &str) -> usize {
399        self.inner.page_store.delete_tag(tag).await.unwrap_or(0)
400            + self.inner.cache.revalidate_tag(tag).await.unwrap_or(0)
401    }
402
403    /// Render every static route without keeping the result: used by
404    /// `next-rust build` to check that static generation succeeds.
405    pub async fn export(&self) -> std::result::Result<crate::export::ExportReport, String> {
406        crate::export::prerender(&self.inner, &MemoryStore::new(usize::MAX)).await
407    }
408
409    /// Render every static route into the page cache, so the first visitor
410    /// gets a cached page. Production servers do this in the background at
411    /// startup.
412    pub async fn prerender(&self) -> std::result::Result<crate::export::ExportReport, String> {
413        crate::export::prerender(&self.inner, self.inner.page_store.as_ref()).await
414    }
415
416    /// Route table as `(kind, pattern, source)` for diagnostics.
417    pub fn route_table(&self) -> Vec<(&'static str, &'static str, &'static str)> {
418        let r = &self.inner.routes;
419        let mut out: Vec<_> = r.pages.iter().map(|p| ("page", p.pattern, p.source)).collect();
420        out.extend(r.apis.iter().map(|a| ("api", a.pattern, a.source)));
421        out
422    }
423}
424
425fn req_cookies_placeholder() -> crate::Cookies {
426    crate::Cookies::default()
427}
428
429/// Find the configuration.
430///
431/// `NEXT_RUST_CONFIG` wins. A release binary then uses the configuration it
432/// was built with, rooted at the working directory, so it runs on its own.
433/// Otherwise the working directory (and its ancestors) is searched, then the
434/// project root recorded at build time, so `./target/debug/my-app` works from
435/// any directory.
436pub fn discover_config(
437    project_root: Option<&str>,
438    embedded: Option<&crate::embed::Embedded>,
439    toml: Option<next_rust_core::config::TomlParser>,
440) -> std::result::Result<Config, String> {
441    let start = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
442    if std::env::var_os("NEXT_RUST_CONFIG").is_none()
443        && let Some((text, json)) = embedded.and_then(|e| e.config)
444    {
445        let parsed = match (json, toml) {
446            (true, _) => Config::from_json_str(text),
447            (false, Some(parse)) => parse(text),
448            (false, None) => Err("embedded TOML configuration needs a TOML parser".to_owned()),
449        };
450        let mut config = parsed.map_err(|e| format!("embedded configuration: {e}"))?;
451        config.root = start;
452        config.apply_env_overrides();
453        return Ok(config);
454    }
455    let from_cwd = Config::discover_with(&start, toml).map_err(|e| e.to_string())?;
456    if from_cwd.source.is_some() || from_cwd.app_dir().is_dir() {
457        return Ok(from_cwd);
458    }
459    match project_root {
460        Some(root) if std::path::Path::new(root).is_dir() => {
461            Config::discover_with(root, toml).map_err(|e| e.to_string())
462        }
463        _ => Ok(from_cwd),
464    }
465}
466
467impl AppBuilder {
468    pub(crate) fn project_root(&self) -> Option<&'static str> {
469        self.routes.project_root
470    }
471
472    pub(crate) fn embedded(&self) -> Option<&'static crate::embed::Embedded> {
473        self.routes.embedded
474    }
475
476    pub(crate) fn toml_parser(&self) -> Option<next_rust_core::config::TomlParser> {
477        self.routes.toml
478    }
479
480    /// Use an explicit configuration instead of discovering `next-rust.toml`.
481    pub fn config(mut self, config: Config) -> Self {
482        self.config = Some(config);
483        self
484    }
485
486    pub fn environment(mut self, env: Environment) -> Self {
487        self.env = Some(env);
488        self
489    }
490
491    /// Add global middleware (runs before `middleware.rs` files, in order).
492    pub fn middleware(mut self, mw: impl Middleware) -> Self {
493        self.middleware.push(Arc::new(mw));
494        self
495    }
496
497    /// Data cache (default: in-memory).
498    pub fn cache(mut self, cache: Cache) -> Self {
499        self.cache = Some(cache);
500        self
501    }
502
503    /// Store for statically rendered pages (default: files in the build
504    /// output in production, memory in development).
505    pub fn page_store(mut self, store: impl CacheStore) -> Self {
506        self.page_store = Some(Arc::new(store));
507        self
508    }
509
510    pub fn plugin(mut self, plugin: impl crate::plugin::Plugin) -> Self {
511        self.plugins.push(Arc::new(plugin));
512        self
513    }
514
515    /// Register a handler programmatically for any method.
516    /// Patterns accept `/users/:id`, `/files/*path` or `/users/[id]`.
517    pub fn route<H, Fut, R>(self, method: Method, pattern: &str, handler: H) -> Self
518    where
519        H: Fn(Request) -> Fut + Send + Sync + 'static,
520        Fut: Future<Output = R> + Send + 'static,
521        R: IntoResponse,
522    {
523        self.custom(Some(method), pattern, handler)
524    }
525
526    pub fn get<H, Fut, R>(self, pattern: &str, handler: H) -> Self
527    where
528        H: Fn(Request) -> Fut + Send + Sync + 'static,
529        Fut: Future<Output = R> + Send + 'static,
530        R: IntoResponse,
531    {
532        self.custom(Some(Method::GET), pattern, handler)
533    }
534
535    pub fn post<H, Fut, R>(self, pattern: &str, handler: H) -> Self
536    where
537        H: Fn(Request) -> Fut + Send + Sync + 'static,
538        Fut: Future<Output = R> + Send + 'static,
539        R: IntoResponse,
540    {
541        self.custom(Some(Method::POST), pattern, handler)
542    }
543
544    /// WebSocket endpoint: `.ws("/socket", |socket| async move { .. })`.
545    #[cfg(feature = "websocket")]
546    pub fn ws<H, Fut>(self, pattern: &str, handler: H) -> Self
547    where
548        H: Fn(crate::ws::WebSocket) -> Fut + Clone + Send + Sync + 'static,
549        Fut: Future<Output = ()> + Send + 'static,
550    {
551        self.custom(Some(Method::GET), pattern, move |req: Request| {
552            let handler = handler.clone();
553            async move { crate::ws::upgrade(req, handler) }
554        })
555    }
556
557    fn custom<H, Fut, R>(mut self, method: Option<Method>, pattern: &str, handler: H) -> Self
558    where
559        H: Fn(Request) -> Fut + Send + Sync + 'static,
560        Fut: Future<Output = R> + Send + 'static,
561        R: IntoResponse,
562    {
563        let handler = Arc::new(handler);
564        let endpoint = move |req: Request| {
565            let handler = handler.clone();
566            async move { handler(req).await.into_response() }
567        };
568        self.customs.push(CustomRoute { pattern: pattern.to_owned(), method, endpoint: Arc::new(endpoint) });
569        self
570    }
571
572    /// Validate routes and build the application.
573    pub fn build(self) -> std::result::Result<App, String> {
574        let env = self.env.unwrap_or_else(Environment::from_env);
575        let config = match self.config {
576            Some(c) => c,
577            None => discover_config(self.routes.project_root, self.routes.embedded, self.routes.toml)?,
578        };
579        crate::set_dev(env.is_dev());
580        let json = match config.logging.format {
581            next_rust_core::config::LogFormat::Json => true,
582            next_rust_core::config::LogFormat::Pretty => false,
583            next_rust_core::config::LogFormat::Auto => !env.is_dev(),
584        };
585        // Production prints only errors unless `[logging]` says otherwise.
586        crate::log::configure(json, config.logging.level(env));
587        crate::set_trust_proxy(config.server.trust_proxy);
588
589        let mut matcher = Matcher::new();
590        let mut intercepts = Vec::new();
591        for (i, page) in self.routes.pages.iter().enumerate() {
592            let pattern = parse_pattern(page.pattern)?;
593            if let Some(from) = page.intercept_from {
594                let mut target = Matcher::new();
595                target.insert(pattern.segments(), ()).map_err(|e| format!("{}: {e}", page.source))?;
596                intercepts.push(Intercept { page: i, target, context: parse_pattern(from)? });
597                continue;
598            }
599            matcher
600                .insert(pattern.segments(), Target::Page(i))
601                .map_err(|e| format!("route {} ({}): {e}", page.pattern, page.source))?;
602        }
603        for (i, api) in self.routes.apis.iter().enumerate() {
604            let pattern = parse_pattern(api.pattern)?;
605            matcher
606                .insert(pattern.segments(), Target::Api(i))
607                .map_err(|e| format!("route {} ({}): {e}", api.pattern, api.source))?;
608        }
609        // Programmatic routes: group handlers by pattern.
610        let mut customs: Vec<CustomHandlers> = Vec::new();
611        let mut custom_index: HashMap<String, usize> = HashMap::new();
612        for c in self.customs {
613            let pattern = parse_pattern(&c.pattern)?;
614            let shape = pattern.shape();
615            let idx = match custom_index.get(&shape) {
616                Some(i) => *i,
617                None => {
618                    let i = customs.len();
619                    matcher
620                        .insert(pattern.segments(), Target::Custom(i))
621                        .map_err(|e| format!("route {}: {e} (conflicts with a file route)", c.pattern))?;
622                    customs.push(Vec::new());
623                    custom_index.insert(shape, i);
624                    i
625                }
626            };
627            customs[idx].push((c.method, c.endpoint));
628        }
629
630        let mut global: Vec<Arc<dyn Middleware>> = self.middleware;
631        for p in &self.plugins {
632            global.extend(p.middleware());
633        }
634        if let Some(mw) = self.routes.middleware {
635            global.push(Arc::new(FnMiddleware(mw)));
636        }
637        let stack_of = |fns: Vec<MiddlewareFn>| -> Arc<[Arc<dyn Middleware>]> {
638            fns.into_iter().map(|f| Arc::new(FnMiddleware(f)) as Arc<dyn Middleware>).collect::<Vec<_>>().into()
639        };
640        let page_stacks = self
641            .routes
642            .pages
643            .iter()
644            .map(|p| stack_of(p.segments.iter().filter_map(|s| s.middleware).collect()))
645            .collect();
646        let api_stacks = self.routes.apis.iter().map(|a| stack_of(a.middleware.clone())).collect();
647        crate::action_token::check_secret()?;
648        if !self.routes.actions.is_empty() && !env.is_dev() && !crate::action_token::keys().from_env {
649            crate::log::warn(&format!(
650                "{} is not set: server-action links are signed with a random key, so open pages stop working \
651                 after a restart and links don't work across instances",
652                crate::SECRET_ENV
653            ));
654        }
655        let actions =
656            self.routes.actions.iter().enumerate().map(|(i, a)| (crate::action_token::action_key(a.id), i)).collect();
657
658        let output_dir = config.output_dir();
659        let page_store: Arc<dyn CacheStore> = match self.page_store {
660            Some(s) => s,
661            None if env.is_dev() => Arc::new(MemoryStore::new(1000)),
662            // Production keeps pages in memory: the binary writes no files.
663            None => Arc::new(MemoryStore::new(10_000)),
664        };
665        let cache = self.cache.unwrap_or_default();
666        next_rust_cache::install_global(cache.clone());
667        let _ = crate::PAGE_STORE.set(page_store.clone());
668
669        let public_env = next_rust_core::env::EnvVars::load(&config.root, env, &config.env.public_prefix)
670            .map(|e| e.public())
671            .unwrap_or_default();
672        let public_env_json = (!public_env.is_empty()).then(|| serde_json::to_string(&public_env).unwrap_or_default());
673
674        let inner = AppInner {
675            public_dir: config.public_dir(),
676            client_dir: config.root.join("client"),
677            dev_status_file: output_dir.join("dev/status.json"),
678            embedded: self.routes.embedded.filter(|e| !e.is_empty()),
679            routes: self.routes,
680            matcher,
681            intercepts,
682            customs,
683            env,
684            cache,
685            page_store,
686            global_stack: global.into(),
687            page_stacks,
688            api_stacks,
689            actions,
690            revalidating: Mutex::new(HashSet::new()),
691            static_params: Mutex::new(HashMap::new()),
692            plugins: self.plugins,
693            public_env_json,
694            config: Arc::new(config),
695        };
696        for p in &inner.plugins {
697            p.on_start(&inner.config);
698        }
699        Ok(App { inner: Arc::new(inner) })
700    }
701}
702
703/// Final endpoint of the global middleware chain: routing.
704struct RouteEndpoint {
705    inner: Arc<AppInner>,
706}
707
708impl Endpoint for RouteEndpoint {
709    fn call(&self, req: Request) -> BoxFuture<Response> {
710        let inner = self.inner.clone();
711        Box::pin(async move { dispatch(inner, req).await })
712    }
713}
714
715async fn dispatch(inner: Arc<AppInner>, mut req: Request) -> Response {
716    let path = req.path().to_owned();
717
718    if path.starts_with("/_next-rust/action/") {
719        return crate::actions::handle(&inner, req).await;
720    }
721    if req.method() == Method::GET || req.method() == Method::HEAD {
722        if path == "/sitemap.xml"
723            && let Some(f) = inner.routes.sitemap
724        {
725            return f().await.into_response();
726        }
727        if path == "/robots.txt"
728            && let Some(f) = inner.routes.robots
729        {
730            return f().await.into_response();
731        }
732    }
733
734    // Intercepting routes apply to client-side navigations only.
735    if let (Some(from), Some("1")) = (req.header("x-nr-from").map(str::to_owned), req.header("x-nr-nav")) {
736        for ic in &inner.intercepts {
737            if let Some(hit) = ic.target.at(&path)
738                && context_matches(&ic.context, &from)
739            {
740                req.set_params(hit.params);
741                let idx = ic.page;
742                // Tells the client runtime this HTML depends on the page it
743                // navigated from, so it isn't reused from other pages.
744                let mut res = run_page(&inner, idx, req).await;
745                res.set_header("x-nr-intercepted", "1");
746                return res;
747            }
748        }
749    }
750
751    let hit = inner.matcher.at(&path).map(|m| (*m.value, m.params));
752    match hit {
753        Some((Target::Page(i), params)) => {
754            if req.method() != Method::GET && req.method() != Method::HEAD {
755                return Response::text("Method Not Allowed").with_status(405).with_header("allow", "GET, HEAD");
756            }
757            req.set_params(params);
758            run_page(&inner, i, req).await
759        }
760        Some((Target::Api(i), params)) => {
761            req.set_params(params);
762            let stack = inner.api_stacks[i].clone();
763            let endpoint = ApiEndpoint { inner: inner.clone(), index: i };
764            Next::new(stack, Arc::new(endpoint)).run(req).await
765        }
766        Some((Target::Custom(i), params)) => {
767            req.set_params(params);
768            let handlers = &inner.customs[i];
769            let method = req.method().clone();
770            let found = handlers.iter().find(|(m, _)| {
771                m.as_ref().is_none_or(|m| *m == method || (method == Method::HEAD && *m == Method::GET))
772            });
773            match found {
774                Some((_, ep)) => {
775                    let head = method == Method::HEAD;
776                    let res = ep.call(req).await;
777                    if head { strip_body(res) } else { res }
778                }
779                None => method_not_allowed(handlers.iter().filter_map(|(m, _)| m.clone()).collect()),
780            }
781        }
782        None => {
783            if (req.method() == Method::GET || req.method() == Method::HEAD)
784                && let Some(res) = crate::static_files::serve_public(&inner, &req).await
785            {
786                return res;
787            }
788            crate::render::not_found_response(&inner, &req).await
789        }
790    }
791}
792
793fn context_matches(context: &RoutePattern, from: &str) -> bool {
794    let from = from.split('?').next().unwrap_or("");
795    let segs: Vec<&str> = from.split('/').filter(|s| !s.is_empty()).collect();
796    let n = context.segments().len();
797    if segs.len() < n {
798        return false;
799    }
800    let mut m = Matcher::new();
801    if m.insert(context.segments(), ()).is_err() {
802        return false;
803    }
804    m.at_segments(&segs[..n]).is_some()
805}
806
807async fn run_page(inner: &Arc<AppInner>, index: usize, req: Request) -> Response {
808    let stack = inner.page_stacks[index].clone();
809    let head = req.method() == Method::HEAD;
810    let endpoint = PageEndpoint { inner: inner.clone(), index };
811    let res = Next::new(stack, Arc::new(endpoint)).run(req).await;
812    if head { strip_body(res) } else { res }
813}
814
815struct PageEndpoint {
816    inner: Arc<AppInner>,
817    index: usize,
818}
819
820impl Endpoint for PageEndpoint {
821    fn call(&self, req: Request) -> BoxFuture<Response> {
822        let inner = self.inner.clone();
823        let index = self.index;
824        Box::pin(async move { crate::render::page_response(&inner, index, req).await })
825    }
826}
827
828struct ApiEndpoint {
829    inner: Arc<AppInner>,
830    index: usize,
831}
832
833impl Endpoint for ApiEndpoint {
834    fn call(&self, req: Request) -> BoxFuture<Response> {
835        let inner = self.inner.clone();
836        let index = self.index;
837        Box::pin(async move {
838            let api = &inner.routes.apis[index];
839            let method = req.method().clone();
840            if let Some((_, h)) = api.handlers.iter().find(|(m, _)| *m == method) {
841                return h(req).await;
842            }
843            if method == Method::HEAD
844                && let Some((_, h)) = api.handlers.iter().find(|(m, _)| *m == Method::GET)
845            {
846                return strip_body(h(req).await);
847            }
848            let mut allowed: Vec<Method> = api.handlers.iter().map(|(m, _)| m.clone()).collect();
849            if method == Method::OPTIONS {
850                allowed.push(Method::OPTIONS);
851                let list = allowed.iter().map(Method::as_str).collect::<Vec<_>>().join(", ");
852                return Response::status(204).with_header("allow", &list);
853            }
854            method_not_allowed(allowed)
855        })
856    }
857}
858
859fn method_not_allowed(allowed: Vec<Method>) -> Response {
860    let mut list: Vec<&str> = allowed.iter().map(Method::as_str).collect();
861    if list.contains(&"GET") && !list.contains(&"HEAD") {
862        list.push("HEAD");
863    }
864    Response::text("Method Not Allowed")
865        .with_status(StatusCode::METHOD_NOT_ALLOWED.as_u16())
866        .with_header("allow", &list.join(", "))
867}
868
869fn strip_body(mut res: Response) -> Response {
870    res.body = crate::response::Body::Empty;
871    res
872}