nuxt.jsnuxt3.jsh3nuxt-plugin

Nuxt 3 - after response middleware


I have a use-case where I would like to call a middleware after the response went through the route handler. The docs describe that the standard server middleware only runs BEFORE the request is handled (https://nuxt.com/docs/guide/directory-structure/server).

What I'd like to accomplish is:

// file: server/api/test/index.ts
export default defineEventHandler(async (event) => {
    return { "test": true }
})

When I call the endpoint via GET /api/test I would like the response to be:

{ "result": { "test": true } }

So basically mapping all APIs response in a object with key "result". This is quite easy to do with express middleware and other frameworks as you can usually await the route handler's result and then just wrap the result in the object.

How can this be accomplished with Nuxt 3 Middleware?


Solution

  • The awesome people over at the h3's GitHub page showed me a working solution.(https://github.com/unjs/h3/issues/397)

    // ~/server/utils/handler.ts
    import type { H3Event } from 'h3'
    
    export const defineMyHandler = (handler: (event: H3Event) => any) => {
      const _handler = async (event: H3Event) => {
        const response = await handler(event)
    
        const responseNew = doSome(response )
    
        return responseNew
      }
    
      return defineEventHandler(_handler)
    }