middleware for special routes
Is it possible to add middleware for special routes?
Did you find a solution for this issue?
@mhfeizi I think currently not, middlewares are called on every route. Maybe we have to wait until they implement this feature. @pi0 ? See this comment: https://github.com/unjs/nitro/blob/68a8c9f564da66dbc7a8a4658fed07c99f7b4bab/src/types/handler.ts#L13
We encountered the same issue, and created a helper function to use instead of DefineEventHandler, to more easily handle middleware per route.
import { H3Event } from 'h3'
const defineEndpoint = (callback: Function, middleware: Function[] = []) =>{
const newCallback = async (event: H3Event) => {
for (let i = 0; i < middleware.length; i++) {
const middlewareFn = middleware[i];
if (! await middlewareFn(event)) {
throw createError({ statusCode: 401, statusMessage: "Unauthorized" });
}
}
return callback(event);
};
return defineEventHandler(newCallback)
}
export {defineEndpoint}
But perhaps there are better ways to do this? @danielroe what do you think?
There's a h3 feature coming that will enable this https://github.com/unjs/h3/issues/424
Currently, you can conditionally run middleware in some routes:
// middleware/api-auth.ts
export default eventHandler(event => {
if (event.path.startsWith('/api')) {
await checkAPIAuth(event)
return
}
})
with the upcoming https://github.com/unjs/h3/pull/485, you can also directly define hooks only on routes you want alternatively in route level:
// api/foo.ts
export default eventHandler({
before: [checkAPIAuth],
handler(event) {
//
}
})
@clopezpro please use event.context to set a user and access it somewhere else.
Currently, you can conditionally run middleware in some routes:
// middleware/api-auth.ts export default eventHandler(event => { if (event.path.startsWith('/api')) { await checkAPIAuth(event) return } })with the upcoming unjs/h3#485, you can also directly define hooks only on routes you want alternatively in route level:
// api/foo.ts export default eventHandler({ before: [checkAPIAuth], handler(event) { // } })@clopezpro please use
event.contextto set a user and access it somewhere else.
magnificent, thank you very much