nitro icon indicating copy to clipboard operation
nitro copied to clipboard

middleware for special routes

Open mhfeizi opened this issue 3 years ago • 1 comments

Is it possible to add middleware for special routes?

mhfeizi avatar May 14 '22 16:05 mhfeizi

Did you find a solution for this issue?

aliosmandev avatar Oct 02 '22 10:10 aliosmandev

@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

Intevel avatar Oct 18 '22 16:10 Intevel

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?

samohub avatar Jul 21 '23 15:07 samohub

There's a h3 feature coming that will enable this https://github.com/unjs/h3/issues/424

Hebilicious avatar Jul 22 '23 00:07 Hebilicious

image

clopezpro avatar Aug 04 '23 21:08 clopezpro

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.

pi0 avatar Aug 04 '23 21:08 pi0

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.context to set a user and access it somewhere else.

magnificent, thank you very much

clopezpro avatar Aug 07 '23 14:08 clopezpro