#Is it possible to select/define which server middlewares should be run on a specific server route?

4 messages · Page 1 of 1 (latest)

pallid lotus
#

For example I have a collection of routes under /server/api/user and I need all of them to run /server/middleware/auth.ts .
How do you go about it?

pallid lotus
#

Would something like this work?

export default defineEventHandler( async (event) => {
  
  const url = getRequestURL(event);
  
  if (url.pathname.startsWith("/api/user") ){

    const user = getUser()
    if (!user) {
      throw createError({
        statusCode: 401,
        statusMessage: "unauthorized",
      });
    }
  }
})
south ibex
#
    const endpoints = [
        '/api/auth/user',
        '/api/user/tweets',
        '/api/tweets',
        '/api/tweets/:id'
    ]

    const isHandledByThisMiddleware = endpoints.some(endopoint => {
        const pattern = new UrlPattern(endopoint)

        return pattern.match(event.req.url)
    })

    if (!isHandledByThisMiddleware) {
        return
    }```