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
8 changes: 8 additions & 0 deletions docs/guide/server-routing.md
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,14 @@ 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.

### Per-route middleware

Pass middleware to `defineHandler` before the final route handler:
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
76 changes: 68 additions & 8 deletions packages/void/src/plugin-routing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@ import { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync }
import { homedir } from 'node:os';
import { fileURLToPath } from 'node:url';
import { isDeepStrictEqual } from 'node:util';
import { dirname, join, relative, resolve } from 'pathslash';
import { basename, dirname, join, relative, resolve } from 'pathslash';
import {
createRunnableDevEnvironment,
isRunnableDevEnvironment,
normalizePath,
parseSync,
} from 'vite';
import type { Plugin, ResolvedConfig, RunnableDevEnvironment } from 'vite';
import type { DevEnvironment, Plugin, ResolvedConfig, RunnableDevEnvironment } from 'vite';
import type { ApplicationAnalysis } from './application-analysis.ts';
import { completeApplicationAnalysis } from './application-routing.ts';
import { hasApiRoutes, hasDocumentRoutes, resolveAssetRoutingPolicy } from './asset-routing.ts';
Expand Down Expand Up @@ -37,6 +37,7 @@ import { getDatabaseAuthDateType, getDatabaseDialect, readConfig } from './confi
import type { VoidConfig } from './config.ts';
import { collectPages, collectRevalidate, hasRevalidate } from './isr-config.ts';
import type { VoidMdPlugin } from './pages/islands-plugin.ts';
import { scanMisplacedPageMiddleware } from './pages/scan.ts';
import { readProjectPaths } from './project-paths.ts';
import { readDeployBuildQueueNames } from './queues/cloudflare-names.ts';
import {
Expand Down Expand Up @@ -138,6 +139,16 @@ function isInDirectory(path: string, directory: string): boolean {
return path === directory || path.startsWith(directory + '/');
}

function invalidateRouteModule(environment: DevEnvironment, structural: boolean): void {
const module = environment.moduleGraph.getModuleById(VIRTUAL_ROUTES_ID);
if (module) {
environment.moduleGraph.invalidateModule(module);
if (structural) {
environment.hot.send({ type: 'full-reload' });
}
}
}

/**
* Vite plugin that provides file-based routing.
* - Scans routes/ and middleware/ directories
Expand Down Expand Up @@ -213,6 +224,17 @@ export function routingPlugin(
),
);

function pageMiddlewareMessage(
files = scanMisplacedPageMiddleware(pagesDir),
): string | undefined {
if (files.length > 0) {
const locations = files
.map((file) => `"${paths.sourceRelative(`pages/${file}`)}"`)
.join(', ');
return `pages: Directory middleware is unsupported in Void Pages (${locations}). Use global middleware in ${paths.sourceRelative('middleware/')} or a shared guard in page loaders and actions.`;
}
}

function hasEmailHandlers(): boolean {
const email = scan?.email;
return Boolean(email && (email.addresses.length > 0 || email.defaultHandler));
Expand Down Expand Up @@ -863,6 +885,19 @@ export function routingPlugin(
return regenerateInOrder(async () => {
generatedRouteInputs = undefined;
await rescan();
if (!compileOptions.dev) {
const misplacedMiddleware = completedScan().pages.misplacedMiddleware ?? [];
if (this.meta.watchMode && existsSync(pagesDir)) {
this.addWatchFile(pagesDir);
for (const file of misplacedMiddleware) {
this.addWatchFile(join(pagesDir, file));
}
}
const diagnostic = pageMiddlewareMessage(misplacedMiddleware);
if (diagnostic) {
throw new Error(diagnostic);
}
}
if (options.target && (scan?.websockets?.length ?? 0) > 0) {
throw new Error('routing: WebSocket routes require the default Cloudflare target.');
}
Expand Down Expand Up @@ -1036,6 +1071,23 @@ export function routingPlugin(
// Watch the source convention directories for file changes
const watcher = devServer.watcher;

function refreshPageMiddlewareDiagnostic() {
const diagnostic = pageMiddlewareMessage();
if (diagnostic !== compileOptions.pageMiddlewareDiagnostic) {
compileOptions.pageMiddlewareDiagnostic = diagnostic;
if (diagnostic) {
devServer.config.logger.error(diagnostic, { timestamp: true });
} else {
devServer.config.logger.info('Void Pages middleware error cleared.', {
timestamp: true,
});
}
for (const environment of Object.values(devServer.environments)) {
invalidateRouteModule(environment, true);
}
}
}

const handleFileChange = async (path: string, event: 'add' | 'change' | 'unlink') => {
const normalizedPath = normalizePath(path);
invalidateSourceAnalysis(normalizedPath);
Expand Down Expand Up @@ -1066,6 +1118,14 @@ export function routingPlugin(

const shouldRestart = await regenerateInOrder(async () => {
invalidateSourceAnalysis(normalizedPath);
if (
isInDirectory(normalizedPath, normalizedPagesDir) &&
basename(normalizedPath).startsWith('_middleware.')
) {
// A filename diagnostic must take effect even if another route cannot be scanned.
refreshPageMiddlewareDiagnostic();
return;
}
if (workflowChanged && !isDeepStrictEqual(options.workflows, scanWorkflowModules(root))) {
return true;
}
Expand Down Expand Up @@ -1163,12 +1223,8 @@ export function routingPlugin(
}
}
}
const mod = env.moduleGraph.getModuleById(VIRTUAL_ROUTES_ID);
if (mod && routeInputsChanged) {
env.moduleGraph.invalidateModule(mod);
if (structural) {
env.hot.send({ type: 'full-reload' });
}
if (routeInputsChanged) {
invalidateRouteModule(env, structural);
}
}

Expand Down Expand Up @@ -1201,6 +1257,10 @@ export function routingPlugin(
watcher.on('add', (path) => onFileChange(path, 'add'));
watcher.on('change', (path) => onFileChange(path, 'change'));
watcher.on('unlink', (path) => onFileChange(path, 'unlink'));
// Seed before later plugins import the routes. Vite ignores initial add
// events, so reconcile again once the watcher has finished its scan.
watcher.on('ready', refreshPageMiddlewareDiagnostic);
refreshPageMiddlewareDiagnostic();

// File-based routing rule HMR: `public/_redirects` / `public/_headers`
// changes re-merge + invalidate the route module so rules take effect
Expand Down
4 changes: 3 additions & 1 deletion packages/void/src/router/compile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ export type CompileOptions = {
* `x-void-dev-trigger`; every build uses the proxy token or build key.
*/
dev?: boolean;
/** Misplaced Pages middleware reported by the dev app on requests. */
pageMiddlewareDiagnostic?: string;
/**
* Token for local dev manual trigger endpoints (`x-void-dev-trigger`).
* Stable for a dev-server process so tooling can print paste-ready curl
Expand Down Expand Up @@ -281,7 +283,7 @@ export function compileRouteTable(
}
const blockedExts = ASSET_EXTENSIONS.filter((e) => !usedExts.has(e));
lines.push(
`const __routingRuntime = __createRoutingRuntime(app, ${JSON.stringify({ dev: options.dev === true, nodeTarget: options.nodeTarget === true, managedDispatch, blockedAssetExtensions: blockedExts })});`,
`const __routingRuntime = __createRoutingRuntime(app, ${JSON.stringify({ dev: options.dev === true, nodeTarget: options.nodeTarget === true, managedDispatch, blockedAssetExtensions: blockedExts, pageMiddlewareDiagnostic: options.pageMiddlewareDiagnostic })});`,
'export const requestContext = __routingRuntime.requestContext;',
'app.use(__routingRuntime.contextMiddleware);',
'app.use(__routingRuntime.requestMiddleware);',
Expand Down
4 changes: 4 additions & 0 deletions packages/void/src/runtime/routing/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ export function createRoutingRuntime(
nodeTarget?: boolean;
managedDispatch?: boolean;
blockedAssetExtensions?: Array<string>;
pageMiddlewareDiagnostic?: string;
} = {},
): RoutingRuntime {
const originalUrls = new WeakMap<Request, URL>();
Expand Down Expand Up @@ -384,6 +385,9 @@ export function createRoutingRuntime(
return response;
},
requestMiddleware: async (c, next) => {
if (options.pageMiddlewareDiagnostic) {
return c.text(options.pageMiddlewareDiagnostic, 500, { 'Cache-Control': 'no-store' });
}
await requestContext.run(
options.nodeTarget
? { request: c.req.raw }
Expand Down
Loading