Home / Function/ routeGuardMiddleware() — astro Function Reference

routeGuardMiddleware() — astro Function Reference

Architecture documentation for the routeGuardMiddleware() function in route-guard.ts from the astro codebase.

Entity Profile

Dependency Diagram

graph TD
  8fce6e79_2898_59cd_64ff_b6babf2c78ba["routeGuardMiddleware()"]
  a9b78244_c0b0_5d0e_6e0e_88d9a32d883c["route-guard.ts"]
  8fce6e79_2898_59cd_64ff_b6babf2c78ba -->|defined in| a9b78244_c0b0_5d0e_6e0e_88d9a32d883c
  style 8fce6e79_2898_59cd_64ff_b6babf2c78ba fill:#6366f1,stroke:#818cf8,color:#fff

Relationship Graph

Source Code

packages/astro/src/vite-plugin-astro-server/route-guard.ts lines 25–82

export function routeGuardMiddleware(settings: AstroSettings): vite.Connect.NextHandleFunction {
	const { config } = settings;

	return function devRouteGuard(req, res, next) {
		const url = req.url;
		if (!url) {
			return next();
		}

		// Only intercept requests that look like browser navigation (HTML requests)
		// Let all other requests through (JS modules, assets, Vite transforms, etc.)
		const accept = req.headers.accept || '';
		if (!accept.includes('text/html')) {
			return next();
		}

		let pathname: string;
		try {
			pathname = decodeURI(new URL(url, 'http://localhost').pathname);
		} catch {
			// Malformed URI, let other middleware handle it
			return next();
		}

		// Always allow Vite internal paths through
		if (VITE_INTERNAL_PREFIXES.some((prefix) => pathname.startsWith(prefix))) {
			return next();
		}

		// Always allow requests with query params (Vite transform requests like ?url, ?raw)
		if (url.includes('?')) {
			return next();
		}

		// Check if the file exists in publicDir - allow if so
		const publicFilePath = new URL('.' + pathname, config.publicDir);
		if (fs.existsSync(publicFilePath)) {
			return next();
		}

		// Check if the file exists in srcDir - allow if so (potential route)
		const srcFilePath = new URL('.' + pathname, config.srcDir);
		if (fs.existsSync(srcFilePath)) {
			return next();
		}

		// Check if the file exists at project root (outside srcDir/publicDir)
		const rootFilePath = new URL('.' + pathname, config.root);
		if (fs.existsSync(rootFilePath)) {
			// File exists at root but not in srcDir or publicDir - block it
			const html = notFoundTemplate(pathname);
			return writeHtmlResponse(res, 404, html);
		}

		// File doesn't exist anywhere, let other middleware handle it
		return next();
	};
}

Domain

Subdomains

Frequently Asked Questions

What does routeGuardMiddleware() do?
routeGuardMiddleware() is a function in the astro codebase, defined in packages/astro/src/vite-plugin-astro-server/route-guard.ts.
Where is routeGuardMiddleware() defined?
routeGuardMiddleware() is defined in packages/astro/src/vite-plugin-astro-server/route-guard.ts at line 25.

Analyze Your Own Codebase

Get architecture documentation, dependency graphs, and domain analysis for your codebase in minutes.

Try Supermodel Free