Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 37 additions & 2 deletions docs/guide/server-routing.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ routes/
report.prod.jsx → production only, with JSX
```

`.dev` routes run only in development; `.prod` routes run in builds, deployments, and production previews. A resource used only by `.dev` routes is not provisioned for production.
`.dev` routes run only in development; `.prod` routes run in builds, deployments, and production previews. A resource imported only in `.dev` route files is not provisioned for production. Imports in directory middleware and other helper files count for both environments.

Suffixes apply in `routes/` and [`pages/`](./pages-routing/overview.md#environment-only-pages), not in `middleware/`, `crons/`, or `queues/`. `void prepare` generates types for both environments.

Expand Down Expand Up @@ -212,7 +212,7 @@ import { cors } from 'hono/cors';
const allowDashboard = cors({ origin: 'https://app.example.com' });
```

You can apply middleware globally or per-route.
You can apply middleware globally, to a route directory, or to a single handler.

### Global middleware

Expand Down Expand Up @@ -260,6 +260,41 @@ For app-specific bypasses such as health checks or public webhooks, compose that

Use `c.set()` to share data with downstream handlers. Augment `CloudContextVariables` for typed access with `c.get()`. See [Context variables](./type-safety.md#context-variables).

### Protecting a Pages section

Put a section guard in `middleware/`. For an admin section, check `c.req.path === '/admin' || c.req.path.startsWith('/admin/')` before allowing the request to proceed. The check must match the route that ultimately serves the request, because configured rewrites run before application middleware. Return 401 when sign-in is required and 403 when a signed-in user lacks permission. The same guard covers document requests, navigation data and action submissions.

You can also share a guard across each affected page's [loader](./pages-routing/loaders.md) and [actions](./pages-routing/actions-and-forms.md), including default and named actions. Prefer this approach for sections that use rewrites. Void reports `_middleware.*` files under `pages/` during development and build.

Keep private content out of public assets and [prerendered output](./edge/prerendering.md). Disable [shared ISR](./edge/revalidation.md) for protected URLs and any rewrite sources that serve them.

### Directory middleware

Put a guard next to the route files it protects. This example requires sign-in for the files under `routes/admin/`. Check the user's admin permission before calling `next()` if the section requires it.

```ts
// routes/admin/_middleware.ts
import { defineMiddleware } from 'void';
import { getUser } from 'void/auth';

export default defineMiddleware(async (c, next) => {
if (!getUser()) return c.text('Unauthorized', 401);
await next();
});
```

Use one `_middleware.ts`, `_middleware.mts`, `_middleware.js`, or `_middleware.mjs` per directory with an active route below it. Default-export a callable middleware. Return a response, set `c.res`, or await `next()` once. Rename an existing helper with one of these filenames if you want to keep importing it yourself.

After global middleware, Void runs the guards from `routes/` down to the directory containing the selected file. Guards see that file's route params and can edit the response after `await next()`, in reverse order. For example, `routes/admin.ts` and `routes/admin/index.ts` can answer different methods at `/admin`. Only the second uses `routes/admin/_middleware.ts`.

HEAD selects GET and omits the body. OPTIONS uses an explicit OPTIONS or all-method handler when it matches. An unmatched request has no directory chain. An HTTP rewrite dispatches the destination, which can run globals and common ancestors again. Return a 404 directly to keep its body, or return `c.notFound()` to render a not-found response.

On Cloudflare, guards also run before a WebSocket upgrade or an ordinary request handled by the WebSocket file. When a rewrite reaches that file, its guard runs on the destination. Use direct upgrade URLs in development, where an allowed rewritten upgrade can return 500. Durable Object hooks and direct `getRoom()` calls do not go through route middleware.

The guard runs when Void dispatches the route, including after a host server strips a mount prefix. Vite CORS can answer a preflight first. Node production and preview send GET and HEAD under `/assets/*` directly to the asset handler. Provider-served files and reserved endpoints also use their own serving paths. Removing the last global middleware can allow Cloudflare to serve disjoint fingerprinted assets without invoking the Worker.

Keep private content out of public files and [prerendered output](./edge/prerendering.md). Set `routing.isr: false` or use an effective ISR TTL of zero for protected URLs and any rewrite sources that serve them. [ISR](./edge/revalidation.md) also applies to eligible HTTP routes and can answer before middleware runs.

### Per-route middleware

Pass middleware to `defineHandler` before the final route handler:
Expand Down
19 changes: 16 additions & 3 deletions packages/void/src/application-analysis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import { scanPages } from './pages/scan.ts';
import { detectFramework, FRAMEWORK_SCAN_DIRS, inferProjectBindings } from './plugin-inference.ts';
import { resolveProjectPaths } from './project-paths.ts';
import { scanQueuesSync } from './queues/scan.ts';
import { scanDirectoryMiddleware } from './router/directory-middleware.ts';
import type { DirectoryMiddlewareScan } from './router/directory-middleware.ts';
import { scanEmailHandlersSync } from './router/email.ts';
import { isRouteEnabledForEnvironment } from './router/parse-filename.ts';
import type { RouteEnvironment } from './router/parse-filename.ts';
Expand Down Expand Up @@ -48,6 +50,7 @@ export type ApplicationAnalysis = {
email: ReturnType<typeof scanEmailHandlersSync>;
routes: ReturnType<typeof scanRoutePatternsSync>;
middleware: ReturnType<typeof scanMiddlewareSync>;
directoryMiddleware?: DirectoryMiddlewareScan;
reasons: ApplicationReasons;
};

Expand All @@ -67,9 +70,14 @@ export async function getNativeWorkerSourceFiles(
if (analysis.email.defaultHandler !== undefined) {
emailFiles.push(analysis.email.defaultHandler);
}
const routes = [...analysis.routes, ...analysis.websockets].filter((route) =>
isRouteEnabledForEnvironment(route, 'dev'),
);
const guards = analysis.framework ? undefined : scanDirectoryMiddleware(paths, routes);
return [
...[...analysis.routes, ...analysis.websockets].flatMap((route) =>
isRouteEnabledForEnvironment(route, 'dev') ? [join(paths.routesDir, route.filePath)] : [],
...routes.map((route) => join(paths.routesDir, route.filePath)),
...Array.from(new Set(Object.values(guards?.chains ?? {}).flat()), (file) =>
join(paths.routesDir, file),
),
...pages.flatMap(({ serverPath }) =>
serverPath === null ? [] : [join(paths.pagesDir, serverPath)],
Expand Down Expand Up @@ -144,6 +152,10 @@ export function analyzeApplicationSync(
const websockets = allWebsockets.filter((route) =>
isRouteEnabledForEnvironment(route, environment),
);
const routes = scanRoutePatternsSync(root, paths, environment);
const directoryMiddleware = framework
? undefined
: scanDirectoryMiddleware(paths, [...routes, ...websockets]);
// Typed durable modules currently use the root convention on every target.
const durableObjects = scanDurableObjectModules(root);
const email = scanEmailHandlersSync(paths.sourceRoot);
Expand Down Expand Up @@ -194,8 +206,9 @@ export function analyzeApplicationSync(
durableObjects,
workflows,
email,
routes: scanRoutePatternsSync(root, paths, environment),
routes,
middleware: scanMiddlewareSync(root, paths),
directoryMiddleware,
reasons,
};
}
1 change: 1 addition & 0 deletions packages/void/src/application-routing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export async function completeApplicationAnalysis(
inventory: {
routes: analysis.routes,
middleware: analysis.middleware,
directoryMiddleware: analysis.directoryMiddleware,
jobs: analysis.jobs,
queues: analysis.queues,
websockets: analysis.websockets,
Expand Down
18 changes: 15 additions & 3 deletions packages/void/src/pages/scan.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { existsSync } from 'node:fs';
import { join, dirname, basename, extname, toSlash } from 'pathslash';
import { glob } from 'tinyglobby';
import { glob, globSync } from 'tinyglobby';
import { parseSync } from 'vite';
import { readConfig } from '../config.ts';
import { voidWarn } from '../log.ts';
Expand Down Expand Up @@ -84,7 +84,7 @@ type PageScanOptions = {
output?: 'server' | 'static';
paths?: ProjectPaths;
pagesDir?: string;
/** Report pages that share a route. Off when another framework owns pages/ (Nuxt nests users.vue and users/index.vue). */
/** Check Void Pages conventions. Off when another framework owns pages/. */
checkRoutes?: boolean;
/** Keep only pages for this environment (`.dev` / `.prod` suffix). Unset keeps every page. */
environment?: RouteEnvironment;
Expand Down Expand Up @@ -350,6 +350,10 @@ export function pageFileEnvironment(relativePath: string): RouteEnvironment | nu
return env;
}

export function scanMisplacedPageMiddleware(pagesDir: string): Array<string> {
return globSync('**/_middleware.*', { cwd: pagesDir, dot: true }).sort();
}

export async function scanPages(root: string, options?: PageScanOptions): Promise<PageScanResult> {
const trailingSlash = options?.trailingSlash ?? readConfig(root).routing?.trailingSlash;
const pagesDir = options?.pagesDir ?? options?.paths?.pagesDir ?? readProjectPaths(root).pagesDir;
Expand Down Expand Up @@ -631,7 +635,15 @@ export async function scanPages(root: string, options?: PageScanOptions): Promis
}
}

return { pages, layouts, namedLayouts, ...(boundaries.length ? { boundaries } : {}) };
const misplacedMiddleware =
options?.checkRoutes === false ? [] : scanMisplacedPageMiddleware(pagesDir);
return {
pages,
layouts,
namedLayouts,
...(boundaries.length ? { boundaries } : {}),
...(misplacedMiddleware.length ? { misplacedMiddleware } : {}),
};
}

function compareText(left: string, right: string): number {
Expand Down
1 change: 1 addition & 0 deletions packages/void/src/pages/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ export type PageScanResult = {
layouts: Array<LayoutDefinition>;
namedLayouts: Array<NamedLayoutDefinition>;
boundaries?: Array<PageBoundaryDefinition>;
misplacedMiddleware?: Array<string>;
};

export type PageBoundaryDefinition = {
Expand Down
23 changes: 19 additions & 4 deletions packages/void/src/plugin-node-target.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,17 @@ const CF_ONLY_REGEX = new RegExp(
);

type NodeTarget = 'node' | 'bun' | 'deno';
type HonoApp = {
fetch: (request: Request) => Promise<Response>;
__voidIsDirectoryDenial?: (request: Request) => boolean;
};

/**
* Bridge Node.js HTTP to Web API and serve via a Hono app.
* Used by both dev server and preview server middleware.
*/
function honoMiddleware(
getApp: () => Promise<{ fetch: (req: Request) => Promise<Response> } | null>,
getApp: () => Promise<HonoApp | null>,
isViteFile?: (request: Request) => Promise<boolean>,
) {
return async (req: IncomingMessage, res: ServerResponse, next: (err?: unknown) => void) => {
Expand Down Expand Up @@ -78,6 +82,7 @@ function honoMiddleware(
// requests still fall through so Vite can serve assets and dev resources.
if (
response.status === 404 &&
!app.__voidIsDirectoryDenial?.(request) &&
((await isViteFile?.(request)) ||
(!response.headers.get('content-type')?.includes('text/html') &&
!response.headers.has('X-VoidPages')))
Expand Down Expand Up @@ -292,8 +297,12 @@ export function nodeTargetPlugin(
default: {
fetch(request: Request, env: { ASSETS: typeof assets }): Promise<Response>;
};
__voidIsDirectoryDenial?: HonoApp['__voidIsDirectoryDenial'];
};
return {
fetch: (request: Request) => mod.default.fetch(request, { ASSETS: assets }),
__voidIsDirectoryDenial: mod.__voidIsDirectoryDenial,
};
return { fetch: (request: Request) => mod.default.fetch(request, { ASSETS: assets }) };
},
async (request) => {
try {
Expand All @@ -311,14 +320,20 @@ export function nodeTargetPlugin(
configurePreviewServer(server) {
// Import the built app module (not index.js which starts a server).
const entryPath = join(process.cwd(), 'dist', 'ssr', 'app.js');
let appPromise: Promise<{ fetch: (req: Request) => Promise<Response> } | null> | null = null;
let appPromise: Promise<HonoApp | null> | null = null;

server.middlewares.use(
honoMiddleware(() => {
if (!appPromise) {
const entryUrl = pathToFileURL(entryPath).href;
appPromise = import(/* @vite-ignore */ entryUrl).then(
(m: { default: { fetch: (req: Request) => Promise<Response> } }) => m.default,
(m: {
default: HonoApp;
__voidIsDirectoryDenial?: HonoApp['__voidIsDirectoryDenial'];
}) => ({
fetch: (request) => m.default.fetch(request),
__voidIsDirectoryDenial: m.__voidIsDirectoryDenial,
}),
() => null,
);
}
Expand Down
Loading