npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

bini-router

v2.2.2

Published

File-based routing, nested layouts, and API routes for Vite + React with MDX support

Readme

bini-router

File-based routing for Vite and React, built on React Router's data router.

npm version license vite react typescript

bini-router turns the files in src/app into a route tree with nested layouts, route groups, parallel and intercepting routes, MDX pages, and Web-standard API routes. During development it server-renders every HTML navigation, and it exposes a route manifest that bini-ssg uses for static pre-rendering. Platform-specific production wiring (Netlify, Vercel, Cloudflare, Node, Deno) is handled by bini-deploy.

Table of Contents

Features

| Area | Capability | | --- | --- | | Routing | Folder pages (dashboard/page.tsx) and flat files (about.tsx, [id].tsx), freely mixed. Dynamic segments [id], [...slug], [[...slug]]. | | Composition | Route groups (group), parallel routes @slot, intercepting routes (.) (..) (...), nested layouts and templates. | | Boundaries | Nearest-wins loading, error, and not-found files, plus global-error. | | Data | React Router data exports (loader, action, and more) on pages and layouts. | | Content | MDX and Markdown pages through @mdx-js/rollup. | | Static analysis | metadata, document, CSS imports, data-export flags, staticParams, and prerender = false are read from source and exposed in the route manifest. | | Development | Every HTML navigation is rendered through a built-in SSR entry. | | API | Request -> Response handlers served in dev and preview, compiled to a portable dist/api/index.mjs on build. | | Ergonomics | Auto-imports for React and React Router APIs; link prefetching on hover and focus. | | Resilience | Oxc-based analysis keeps the last good version of a file with a syntax error or an empty file, so routes do not disappear mid-edit. |

Installation

npm install bini-router react-router-dom
npm install -D @mdx-js/rollup   # only for .mdx / .md pages

| Dependency | Requirement | | --- | --- | | Vite | 8 or later. The plugin throws on older versions. | | React | 18 or later | | react-router-dom | A data-router release. The generated app uses createBrowserRouter, createRoutesFromElements, route lazy, and StaticRouter imported from react-router-dom. |

Quick Start

1. Register the plugin in vite.config.ts:

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import { biniroute } from 'bini-router'

export default defineConfig({
  plugins: [react(), biniroute()],
})

biniroute() returns an array of plugins; pass it to plugins as-is. If you also use biniSSG(), list it after biniroute().

2. Mount the app in src/main.tsx:

import { createRoot } from 'react-dom/client'
import App, { rootOptions } from 'virtual:bini-app'

createRoot(document.getElementById('root')!, rootOptions).render(<App />)

3. Add a page at src/app/page.tsx:

export default function Home() {
  return <h1>Hello</h1>
}

Keep <div id="root"></div> in index.html. Do not import CSS from src/main.* (this fails with BINI_R022); import global styles from src/app/layout.tsx or a page instead.

Application Entry

The Quick Start entry mounts the app with createRoot. The example below also supports pre-rendered pages: it preloads the current route, waits for the router, and then chooses between createRoot and hydrateRoot.

import React from 'react'
import { createRoot, hydrateRoot } from 'react-dom/client'
import App, {
  preloadRoute,
  routerReady,
  resetNavState,
  rootOptions,
  reportBiniError,
} from 'virtual:bini-app'

class LastResortBoundary extends React.Component<
  { children: React.ReactNode },
  { error: Error | null }
> {
  state = { error: null as Error | null }

  static getDerivedStateFromError(error: Error) {
    return { error }
  }

  render() {
    if (this.state.error) {
      if (import.meta.env.DEV) return null
      return (
        <div role="alert">
          <h1>Something went wrong</h1>
          <pre>{String(this.state.error.message || this.state.error)}</pre>
          <button type="button" onClick={() => this.setState({ error: null })}>
            Try again
          </button>
        </div>
      )
    }
    return this.props.children
  }
}

const rootElement = document.querySelector('[data-bini-ssr-fallback]')
  ? null
  : document.getElementById('root')

if (rootElement) {
  const isShell = (window as { __BINI_SHELL__?: boolean }).__BINI_SHELL__ === true
  const bootShell = rootElement.querySelector('[data-bini-boot]') !== null
  const tree = (
    <LastResortBoundary>
      <App />
    </LastResortBoundary>
  )

  resetNavState()

  const ready = Promise.race([
    preloadRoute(location.pathname).then(() => routerReady()),
    new Promise<void>((resolve) => setTimeout(resolve, 10_000)),
  ]).catch((err) => reportBiniError(err, '', 'uncaught'))

  void ready.then(() => {
    try {
      if (isShell || bootShell || !rootElement.hasChildNodes()) {
        createRoot(rootElement, rootOptions).render(tree)
      } else {
        hydrateRoot(rootElement, tree, rootOptions)
      }
    } catch (err) {
      reportBiniError(err, '', 'uncaught')
    }
  })
}

export { App }

How the entry behaves:

  1. Preload. preloadRoute(location.pathname) loads the lazy modules for the current URL, then routerReady() waits for the browser router to initialize. A 10-second timeout prevents a stalled route from blocking the mount.
  2. Client render or hydrate. The app is created with createRoot when the page is a shell (window.__BINI_SHELL__ === true), when the root contains a [data-bini-boot] element, or when the root is empty. Otherwise the existing pre-rendered markup is hydrated with hydrateRoot.
  3. Fallback marker. If the document contains a [data-bini-ssr-fallback] element, this entry does not mount the app.
  4. Last-resort boundary. Errors that escape every route boundary are caught here. In development the boundary renders nothing; in production it renders an error message with a "Try again" button.

Virtual modules

The route tree is generated in memory and never written to disk.

virtual:bini-app

| Export | Description | | --- | --- | | default | App component (a RouterProvider) | | routes | Route objects, safe to import on the server | | AppRoutes | Renders useRoutes(routes), for custom routers such as StaticRouter | | getRouter() | Lazily creates the createBrowserRouter instance (browser only) | | basename | Resolved router basename | | rootOptions | Error handlers for createRoot / hydrateRoot | | preloadRoute(pathname) | Preloads a route's lazy modules | | routerReady() | Resolves once the browser router is initialized | | resetNavState() | Clears previous-location tracking (parallel and intercepting routes) | | reportBiniError() | Dispatches a runtime error to the dev overlay (development only) | | __staticParams | Map of route pattern to an async function returning the page's staticParams() result. Consumed by bini-ssg. | | __prerenderOptOut | Map of route patterns that export prerender = false. Consumed by bini-ssg. |

virtual:bini-routes exports staticRoutes, dynamicRoutes, allRoutes, routeMetadata, and a default manifest object (see Route manifest).

Internal modules. virtual:bini-ssr-entry (exports render(url, { timeoutMs }), __staticParams, and __prerenderOptOut; used by dev SSR) and virtual:bini-defaults / bini-router/defaults (the built-in Spinner, Default404, DefaultError, and DefaultSlotFallback components) are also resolved by the plugin.

TypeScript projects need ambient declarations for virtual:bini-app and virtual:bini-routes (see Troubleshooting).

Project Structure

The app directory is src/app and the API directory is src/app/api. Neither is configurable.

src/
  main.tsx
  app/
    layout.tsx            Root layout
    page.tsx              /
    about.mdx             /about
    (marketing)/          Route group (no URL segment)
      pricing/page.tsx    /pricing
    dashboard/
      layout.tsx
      page.tsx            /dashboard
      loading.tsx
      [id]/page.tsx       /dashboard/:id
    inbox/
      layout.tsx          Receives the "sidebar" slot as a prop
      page.tsx            /inbox
      @sidebar/
        default.tsx
        page.tsx
    blog/
      index.tsx           /blog
      [slug].tsx          /blog/:slug
      not-found.tsx
    docs/[...path]/page.tsx   /docs/*
    api/
      users.ts            /api/users
      posts/[id].ts       /api/posts/:id

Conventions

  • Files and folders starting with _ or . are ignored, as are node_modules, *.d.*, *.test.*, *.spec.*, and *.stories.* files, and .md / .mdx documentation files such as README.md, CHANGELOG.md, and LICENSE.md.
  • layout, template, loading, error, not-found, global-error, and default files must be .tsx, .jsx, .ts, or .js.
  • Pages support those extensions plus .mdx and .md.
  • Route, group, and slot names may contain letters, digits, _, and - (segments up to 100 characters; slot names must start with a letter). Dynamic parameter names must be valid identifiers. Other names are skipped with BINI_R008.
  • Files over 10 MB are skipped (BINI_R005). Directory traversal is capped at 100 levels.

Routing

Pages and dynamic segments

| Pattern | Example | URL | | --- | --- | --- | | Static | dashboard/page.tsx or dashboard.tsx | /dashboard | | Index | blog/index.tsx | /blog | | Dynamic | blog/[slug].tsx | /blog/:slug | | Catch-all | docs/[...path]/page.tsx | /docs/* (at least one segment) | | Optional catch-all | docs/[[...path]]/page.tsx | /docs/* (zero or more) |

Read dynamic parameters with useParams(). For page routes, catch-all segments are exposed under React Router's '*' key (params['*']), not under the name written in the folder. A required catch-all without a real page at its parent path adds a guard route, so the parent URL renders the not-found page.

Route groups

A folder wrapped in parentheses, such as (marketing), groups routes and can carry its own layout without adding a URL segment.

Parallel routes

A folder prefixed with @ defines a named slot. The slot is passed as a prop to the layout.* in the same directory as the @slot folder:

// src/app/inbox/layout.tsx
export default function InboxLayout({ sidebar }) {
  return (
    <div className="grid">
      <aside>{sidebar}</aside>
      <main><Outlet /></main>
    </div>
  )
}

The slot renders the first entry matching the current URL, then the slot's own default.*, then a built-in empty fallback. A slot without a receiving layout is an error (BINI_R013). Data exports in slot pages are not executed (BINI_R012).

Intercepting routes

Folders or flat files prefixed with (.), (..), or (...) (same level, one level up, or app root) render alternative content at a URL when the previous in-app location matches the interceptor's source route. Direct visits and reloads render the real page. If no real page exists at the target URL, the interceptor's page is registered as the route and the not-found page is shown for direct visits. Data exports in interceptors are not executed (BINI_R012).

Conflicts

Two files that resolve to the same URL, intercept level, and slot are a route conflict (BINI_R007). The build fails and the dev server throws. Delete one of the files; there is no priority system.

Layouts and Templates

Layouts wrap every page in their directory and below. They receive params, any parallel-route slots, and children. Render either <Outlet /> or {children}.

// src/app/dashboard/layout.tsx
export default function DashboardLayout({ params }) {
  return (
    <div className="dashboard">
      <aside>Sidebar</aside>
      <main><Outlet /></main>
    </div>
  )
}

Layouts that contain an <html> element, or have no default export, are excluded from the chain. The same check applies to templates and to loading, error, not-found, global-error, and default files. Circular chains are detected (BINI_R010).

A template.* file wraps each page inside the layout chain. The nearest usable template wins, and templates receive children only.

Route Data Exports

Pages and layouts can export loader, action, shouldRevalidate, ErrorBoundary, HydrateFallback / hydrateFallbackElement, and handle. They are detected statically and wired into the generated data router.

export async function loader() {
  const res = await fetch('/api/users')
  return res.json()
}

export default function Users() {
  const users = useLoaderData()
  return <ul>{users.map((u) => <li key={u.id}>{u.name}</li>)}</ul>
}

Routes whose page or layouts have data exports are marked clientOnly in the manifest. They are not server-rendered: the static renderer does not run React Router lazy routes, the dev server logs BINI_R023, and bini-ssg writes an empty shell for them.

For a route that exports ErrorBoundary, bini-router does not generate an errorElement, so the nearest error.* and not-found.* files are not attached to that route.

Loading, Not Found, and Error Boundaries

loading, error, and not-found files use nearest-wins resolution: a file in a subfolder applies to routes in that subfolder and shadows its ancestors. Built-in defaults are used when none is found.

| File | Behavior | | --- | --- | | loading.* | Suspense fallback for pages and layouts in scope. | | not-found.* | Handles unmatched URLs under its folder (wrapped in that folder's layouts) and 404 responses thrown from routes. | | error.* | Receives { error, reset } and catches render errors and route errors. Boundaries reset on navigation and on HMR updates. | | global-error.* | Fallback, in the app root, for errors that reach the root route. | | default.* | Inside a @slot folder, renders when no slot route matches. |

In development, runtime errors are also dispatched as a __bini_error__ event on window, which bini-overlay listens for.

Metadata and Document

Static extraction applies to .tsx, .jsx, .ts, and .js files. .mdx and .md pages do not support metadata, document, or CSS extraction.

metadata

Export metadata from any layout or page. It is statically extracted into the route manifest, merged from the outermost layout to the page, and removed from the client bundle (the export is stripped from the module unless the same metadata constant is referenced elsewhere in the file). Object values are merged one level deep, and later entries win.

bini-ssg writes the merged metadata into each page's <head> at build time. bini-router itself only uses the resolved title, which it applies to document.title on client navigation.

// layout.tsx
export const metadata = {
  title: { default: 'My App', template: '%s | My App' },
  description: 'Built with bini-router',
}

// dashboard/page.tsx
export const metadata = { title: 'Dashboard' }   // "Dashboard | My App"

A page title is formatted with the nearest layout title.template. If the page has no title, the nearest layout's string title or title.default is used.

Values must be statically evaluable: literals, template literals, arrays, objects, module-scope const references, TypeScript as / satisfies wrappers, and JSON.stringify of static values. Non-static properties are skipped individually with a BINI_R020 warning.

document

Use document for head tags that must appear in both development and production, and for <html> / <body> attributes. Like metadata, the export is removed from the client bundle.

export const document = {
  html: { lang: 'en' },
  body: { class: 'antialiased' },
  head: (
    <>
      <title>My App</title>
      <meta name="description" content="Built with bini-router" />
      <link rel="icon" href="/favicon.ico" />
    </>
  ),
}

| Key | Applied in dev | Applied at build (bini-ssg) | | --- | --- | --- | | head | Yes | Yes | | html, body | Yes | Yes | | metadata | Title only (client-side) | Yes |

The nearest document export (page first, then the closest layout) is used; documents are not merged. Attribute values and children must be static, otherwise they are dropped with a BINI_R004 warning. dangerouslySetInnerHTML={{ __html: <static value> }} is supported for JSON-LD scripts.

When a route has no document.head, the dev server hoists any <title>, <meta>, and <link> tags that React rendered inside the page into <head>. Tags with an itemprop attribute stay in place.

Static Params and Prerender

| Export | Behavior | | --- | --- | | staticParams | A function (sync or async) exported from a dynamic page that lists the URLs to pre-render. The manifest records staticParams: true for the route, and virtual:bini-app exposes the function through __staticParams. bini-router never calls it; bini-ssg does, substituting the returned parameters into the route pattern. | | prerender = false | Marks a route as opted out of pre-rendering and is exposed through __prerenderOptOut. No other value of prerender is read by bini-router. |

API Routes

Place .ts or .js files in src/app/api/. Every handler receives a standard Request and a context object:

{ params, searchParams, env, waitUntil? }

Three handler styles are supported:

// 1. Per-method exports: GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS
export function GET(req: Request, { params }) {
  return Response.json({ id: params.id })
}

// 2. Default function: handles all methods; plain values are sent as JSON
export default function handler() {
  return { ok: true }
}

// 3. Any default export with .fetch(), such as a Hono app
import { Hono } from 'hono'
const app = new Hono()
app.all('/hello', (c) => c.json({ message: 'Hello' }))
export default app

If a file exports method handlers, other methods receive 405 with an Allow header, and HEAD falls back to GET. Method exports take precedence over a default export (BINI_R021). Routes in .fetch() objects are written without the /api prefix.

| File | Route | | --- | --- | | api/users.ts | /api/users | | api/users/route.ts | /api/users | | api/posts/index.ts | /api/posts | | api/posts/[id].ts | /api/posts/:id | | api/[...catch].ts | /api/* | | api/(internal)/health.ts | /api/health |

*.d.ts, *.test.*, and *.spec.* files are ignored, as is anything starting with _ or .. Static routes match before dynamic ones, and dynamic ones before catch-alls. Catch-all values are available as params['*'] and under the name used in the file or folder (params.catch for [...catch]).

Request handling

| Concern | Behavior | | --- | --- | | URL | Handlers see the URL with the base and /api stripped (/api/users?x=1 arrives as /users?x=1). | | Host validation | In dev and preview, the Host header is validated against Vite's server.allowedHosts (preview.allowedHosts in preview), plus any configured server.host and server.hmr.host. Malformed hosts get 400, disallowed hosts get 403. localhost, *.localhost, and IP addresses are always allowed. The same check guards dev HTML navigations. | | Body limit | Bodies over bodySizeLimit (1 MB by default) are rejected with 413. | | Parameters | Decoded values containing /, \, .., or a null byte do not match, and paths with empty segments are rejected. | | Errors | Unmatched requests return a JSON 404; thrown exceptions return a generic JSON 500. |

Dev, build, and preview

  • vite dev loads handlers through the ssr environment's ModuleRunner, so edits apply immediately.
  • vite build compiles the API into <build.outDir>/api/index.mjs when src/app/api exists. The bundle uses only Web APIs, exports fetch(request, env, executionContext) (also as the default export { fetch }), and runs on Node, Workers, Deno, Netlify, and Vercel. Packages from node_modules stay external.
  • vite preview serves the compiled bundle. Without a prior build, API requests return 503.

The bundle is emitted inside the client output folder, so static hosts must not publish it as an asset. bini-deploy handles this for supported platforms.

The plugin installs a builder.buildApp that builds the client first and then every other environment that has an input, including api. If you define your own builder.buildApp, it must build the api environment, otherwise dist/api is not produced.

Development and Preview

Dev server. Every HTML navigation is rendered through the built-in SSR entry and injected into index.html. A request qualifies when it is a GET or HEAD that accepts text/html and is not for /@*, /src/*, /node_modules/*, /api/*, /__*, or a static asset extension. Rendering times out after 15 seconds and responds with a 500 page. CSS imported by the matched layouts and page is inlined as <style> tags. Adding or removing routes, or changing a layout, template, loading, error, not-found, global-error, or default file, triggers a full reload.

Preview server. vite preview serves pre-rendered pages and shell pages from build.outDir. For each HTML navigation it tries <path>/index.html, then dynamic and catch-all shell folders ([param]/index.html), then 404.html with a 404 status.

Configuration

biniroute({
  cors: false,
  trustProxy: false,
  bodySizeLimit: 1024 * 1024,
})

| Option | Type | Default | Description | | --- | --- | --- | --- | | cors | boolean \| { origin?, methods?, headers? } | false | Adds CORS headers to API responses and answers OPTIONS preflights with 204 unless the route exports OPTIONS. true allows any origin with the standard methods and the headers Content-Type, Authorization, and X-Request-ID. origin accepts a string or a list matched per request. | | trustProxy | boolean | false | Builds the request origin from X-Forwarded-Host and X-Forwarded-Proto in dev and preview. The forwarded host must still pass the allow-list. | | bodySizeLimit | number \| false | 1048576 | Maximum API request body in bytes. false, 0, or Infinity disable the limit. |

Everything else is fixed by convention: directories, the router basename (derived from Vite's base), auto-import presets, MDX options, route prefetching, and the built-in SSR entry. Prefetching on link hover and focus can be disabled per link with data-no-prefetch.

Set BINI_DEBUG=1 (or BINI_DEBUG_HMR=1) for verbose plugin logs.

Auto-imports

Provided by unplugin-auto-import for script files (not .mdx / .md): the React preset plus the following from react-router-dom: Link, NavLink, Outlet, Form, redirect, useNavigate, useParams, useLocation, useSearchParams, useLoaderData, useActionData, useNavigation, useFetcher, useFetchers, useMatches, useRouteLoaderData, useRouteError, useRevalidator, useSubmit, Await, useAsyncValue, useAsyncError, and isRouteErrorResponse. In TypeScript projects, vite dev writes declarations to src/auto-imports.d.ts.

Environment Variables

bini-router does not read environment variables. API handlers receive env from whatever calls the compiled fetch(request, env, ctx):

| Runtime | env | | --- | --- | | vite dev, vite preview | undefined. bini-env loads your .env files into process.env instead. | | Cloudflare Workers | The entry generated by bini-deploy passes the Worker's env bindings. | | Node (bini-server) | process.env is passed as env. bini-server also loads .env files from the working directory at startup (through loadEnvFiles from bini-env/node); variables already set in the environment win. | | Netlify, Vercel, Deno | Not passed. Hono's env(c) falls back to process.env (or Deno.env), so getEnv(c, key) from bini-env still works. |

Read secrets at runtime, for example with getEnv(c, key) from bini-env in Hono handlers. Do not use import.meta.env in API code: Vite replaces it at build time with values from the build machine.

Base Path

Sub-path deployments are driven by Vite's base option. The router basename is derived from it, and API routes are served at /api/* and <base>/api/*. Relative bases (./, ., or empty) resolve to a basename of /, and an absolute URL base uses its pathname. There is no separate basename option.

export default defineConfig({
  base: '/my-app/',
  plugins: [react(), biniroute()],
})

Programmatic API

The following are exported from bini-router for tooling.

| Export | Purpose | | --- | --- | | biniroute(options?) | The Vite plugin array | | generateRouteManifest(appDir, apiDir?, state?) | Scans src/app and returns the route manifest | | generateBuildManifest(appDir, apiDir?, state?) | Scans API routes for deployment tooling | | getMetadataForRoute(manifest, pathname) / getCssForRoute(manifest, pathname) | Look up a manifest entry or its CSS list | | matchManifestRoute(manifest, pathname) / matchRoute(pattern, pathname, options?) | Match a pathname against a manifest or a single pattern | | getShellRoutes(manifest) / shellDirForPattern(routePath, name?) | Shell pages that a static build must write | | createBiniRouterState(options?) | Router state with parse caches, shared across calls. strictPages limits page discovery to page.* files and interceptors; strictApi limits API discovery to index.* and route.* files. | | createBiniBuildApp() | The shared builder.buildApp implementation | | getSourceFacts(file, state?) / scanSourceFacts(root, state?) | Static source analysis (used by bini-native) | | isSourceFile(name) / isClientSourceFile(root, file) | Source-file predicates | | deriveBase(base, command) | Router basename and API prefix from Vite's base | | resolveBodySizeLimit(value) / isAllowedHost(host, allowed) | Option and host helpers | | report(severity, code, file?, detail?, state?) | Record a diagnostic |

Exported types: BiniPluginOptions, RouteManifest, RouteManifestEntry, RouteMetadata, RouteFileMetadata, RouteDocument, HeadNode, RouteSlotInfo, RouteInterceptInfo, RouteMatchResult, ClientRouteManifest, ClientRouteMetadata, BuildManifest, BuildAppFn, RouterState, Severity, ShellRoute, and SourceFacts. The bini-router/client entry exports the ErrorBoundary used by the generated app module.

Route manifest

import { generateRouteManifest, matchManifestRoute } from 'bini-router'

const manifest = generateRouteManifest('src/app')
manifest.static      // ['/', '/about']
manifest.dynamic     // ['/blog/:slug']
manifest.metadata    // per-route entries

matchManifestRoute(manifest, '/blog/hello')
// { type: 'dynamic', routePath: '/blog/:slug', params: { slug: 'hello' } }

Patterns use :name for dynamic segments, * for a required catch-all, and ** for an optional catch-all. Paths are logical and never include Vite's base. Each entry includes:

  • title, meta (merged metadata), document, css, layouts, filePath
  • dynamic, catchallKind ('required' | 'optional' | null), catchallParamName, slotName
  • the data-export flags loader, action, shouldRevalidate, errorBoundary, hydrateFallback, and handle
  • clientOnly (the page or a layout has data exports) and staticParams
  • when present, parallel (slots at that route) and intercepts

prerender = false is not part of the manifest; it is exposed through __prerenderOptOut in virtual:bini-app.

Inside application code, virtual:bini-routes exposes a reduced, client-safe manifest. Each entry has title, dynamic, catchallParamName, the data-export flags that are set and, when present, the route's document head, html, and body. File paths and merged metadata are not included.

The ecosystem packages bini-ssg, bini-deploy, bini-overlay, and bini-native build on this API.

Diagnostics

Problems are reported through Vite's logger with a BINI_* code and a code frame where available. In vite build, errors are collected and thrown together as a single BINI_AGGREGATE error. Internal failures use BINI_INTERNAL.

| Code | Severity | Meaning | | --- | --- | --- | | BINI_R001 | error | A page.* file has no default export | | BINI_R003 | warn | A Host or X-Forwarded-Host header was rejected | | BINI_R004 | warn | A dynamic document.head value was dropped | | BINI_R005 | warn | File over 10 MB was not parsed | | BINI_R007 | error | Route conflict (pages or API routes) | | BINI_R008 | error / warn | Invalid route, group, slot, intercept, or API name | | BINI_R010 | warn | Circular layout chain | | BINI_R011 | warn | Maximum directory depth reached | | BINI_R012 | warn | Loader or action ignored in a parallel slot or interceptor | | BINI_R013 | error | Parallel slot has no receiving layout | | BINI_R017 | warn | Layout dropped from the chain | | BINI_R018 | error | No runnable ssr environment for dev rendering | | BINI_R019 | warn | Built-in default component not found next to the plugin | | BINI_R020 | warn | Non-static metadata properties skipped | | BINI_R021 | warn | Handler file exports both HTTP methods and a default export | | BINI_R022 | error | CSS imported from src/main.* | | BINI_R023 | warn | Route has data exports and is not server-rendered |

Troubleshooting

TypeScript cannot resolve virtual:bini-app or virtual:bini-routes

Add ambient declarations, for example in vite-env.d.ts:

declare module 'virtual:bini-app' {
  const App: () => import('react').ReactElement
  export default App
  export const basename: string
  export const routes: import('react-router-dom').RouteObject[]
  export function AppRoutes(): import('react').ReactElement | null
  export function getRouter(): ReturnType<typeof import('react-router-dom').createBrowserRouter>
  export const rootOptions: import('react-dom/client').RootOptions
  export function preloadRoute(pathname: string): Promise<unknown>
  export function routerReady(): Promise<void>
  export function resetNavState(): void
  export function reportBiniError(error: unknown, componentStack?: string, kind?: 'caught' | 'uncaught'): void
}

declare module 'virtual:bini-routes' {
  type RouteInfo = {
    title?: string
    dynamic: boolean
    catchallParamName?: string
    loader?: true
    action?: true
    shouldRevalidate?: true
    errorBoundary?: true
    hydrateFallback?: true
    handle?: true
  }
  export const staticRoutes: string[]
  export const dynamicRoutes: string[]
  export const allRoutes: string[]
  export const routeMetadata: Record<string, RouteInfo>
}

"bini-router requires Vite 8 or newer." Upgrade Vite. The plugin relies on the Environment API, the ModuleRunner, and Rolldown-based builds.

BINI_R018 or "ssr environment is not runnable". Dev rendering and API handlers run through the ssr environment. Make sure no plugin declares environments.ssr after biniroute().

BINI_R022 about CSS in main.tsx. Move the import to src/app/layout.tsx or a page.

A route is missing. Check that the file has a default export, parses without errors, is not under a _ or . prefixed path, and is not a .test / .spec / .stories file. Run generateRouteManifest('src/app') in a Node script to see what the router sees.

The title is correct after load, but description and other meta tags are missing in development. The title from metadata is applied on the client; every other metadata field is written to HTML by bini-ssg at build time only. Declare head tags in document.head to get them in both environments.

useParams() has no value under my catch-all's name. Page catch-alls are exposed as params['*'].

A page is empty in dev with BINI_R023. The page or a layout has a data export, so the route renders on the client.

A slot or interceptor does not render. Slots need a layout.* next to the @slot folder that reads the slot as a prop. Interceptors only apply when the previous in-app location matches their source route.

An API route returns 405, 403, 413, or 503. Respectively: the method is not exported; the host is not in allowedHosts (set trustProxy behind a proxy that forwards the host); the body exceeds bodySizeLimit; or vite preview was started before vite build.

The dev page responds with a 500 "SSR timeout". A component or loader did not resolve within 15 seconds.

Missing @mdx-js/rollup. Install it with npm i -D @mdx-js/rollup.

License

MIT © Binidu Ranasinghe