Replies: 2 comments
|
i dont think you can do that with the current nitro version. one way that i handeled that was to get export default defineEventHandler(async (event) => {
// Skip middleware for certain routes
const url = getRequestURL(event)
const skipRoutes = [
'/api/public',
'/api/auth',
// Add other routes that don't need to be run
]
// Check if current route should skip clinic context
const shouldSkip = skipRoutes.some(route => url.pathname.startsWith(route))
if (shouldSkip) {
return
}
// Only run on API routes or specific paths
if (!url.pathname.startsWith('/api/')) {
return
}
try {
// your logic here
}
catch (error: any) {
// Handle errors appropriately
if (error.statusCode) {
throw error
}
throw createError({
statusCode: 500,
statusMessage: 'Failed to load clinic context',
})
}
}) |
|
Nitro's The docs reference h3's Object Syntax, which lets you attach middleware to a specific handler. Here's how: Option 1 — Route-level middleware using Object Syntax: In your route handler file (e.g., import { defineEventHandler } from 'h3';
const myMiddleware = defineEventHandler((event) => {
// this runs before the main handler
// e.g., auth check, logging, etc.
console.log('middleware for /images route');
});
export default defineEventHandler({
onRequest: [myMiddleware],
handler: async (event) => {
const fileId = getRouterParam(event, 'fileId');
// your actual handler logic
return { fileId };
},
});Option 2 — Global middleware with path filtering: // server/middleware/images-auth.ts
export default defineEventHandler((event) => {
const url = getRequestURL(event);
if (!url.pathname.startsWith('/images/')) return;
// your middleware logic only for /images/*
});Option 1 is cleaner when you want middleware tied to a specific route. Option 2 works when you need to cover a group of routes with a prefix pattern. The key h3 feature is the |
Uh oh!
There was an error while loading. Please reload this page.
In the document, it says:
But I have no idea how to use that. Is there any example? Like a middleware for "/images/:fileId"?
All reactions