Fix: Make middleware resilient when Directus schema is missing

This commit is contained in:
cawcenter
2025-12-12 00:39:47 -05:00
parent abd964a745
commit ea06283e4c

View File

@@ -4,7 +4,7 @@ import { getDirectusClient, readItems } from './lib/directus/client';
/**
* Multi-Tenant Middleware
* Resolves siteId based on incoming domain and attaches it to SSR context.
* Supports both tenant admin (/admin) and public pages.
* Gracefully handles missing Directus schema (first-run scenario).
*/
export const onRequest = defineMiddleware(async (context, next) => {
const host = context.request.headers.get('host') || 'localhost';
@@ -18,6 +18,18 @@ export const onRequest = defineMiddleware(async (context, next) => {
const platformDomain = import.meta.env.PUBLIC_PLATFORM_DOMAIN || 'platform.local';
const isPlatformAdmin = cleanHost === platformDomain;
// Initialize locals with safe defaults
context.locals.siteId = null;
context.locals.site = null;
context.locals.isAdminRoute = isAdminRoute;
context.locals.isPlatformAdmin = isPlatformAdmin;
context.locals.scope = isPlatformAdmin && isAdminRoute ? 'super-admin' : 'tenant';
// Skip Directus calls for static assets
if (pathname.match(/\.(ico|png|jpg|jpeg|svg|css|js|woff|woff2)$/)) {
return next();
}
try {
const directus = getDirectusClient();
@@ -34,24 +46,17 @@ export const onRequest = defineMiddleware(async (context, next) => {
})
);
if (!sites?.length) {
console.warn(`⚠ No site matched host: ${cleanHost}`);
context.locals.siteId = null;
context.locals.site = null;
} else {
if (sites?.length) {
context.locals.siteId = sites[0].id;
context.locals.site = sites[0];
}
} catch (err) {
console.error('❌ Middleware Error:', err);
context.locals.siteId = null;
context.locals.site = null;
} catch (err: any) {
// Silently handle - schema may not exist yet
// Only log in development
if (import.meta.env.DEV) {
console.warn('Middleware: Directus query failed (schema may not exist):', err?.message || err);
}
}
// Set admin scope
context.locals.isAdminRoute = isAdminRoute;
context.locals.isPlatformAdmin = isPlatformAdmin;
context.locals.scope = isPlatformAdmin && isAdminRoute ? 'super-admin' : 'tenant';
return next();
});