0

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?

Schutt
  • 1,056
  • 6
  • 17

2 Answers2

1

Middlewares purpose are for checking logic before the the endpoint gets executed. I don't think using a middleware will accomplish your task.

Here is one solution that does not involve any middleware:

you can create a custom function that maps your responses.

function mapResponse(data){
  return {
    result: data
  }
}

and use it inside you api endpoints like this:

export default defineEventHandler((event) => {
  return mapResponse({ "test": true })
})

then you can also customize the function however you want.

aryankarim
  • 184
  • 1
  • 10
  • While this works it can be quite tidious and error prone. It seems that currently there is no other way in nuxt 3. – Schutt Jun 02 '23 at 10:45
1

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)
}
Schutt
  • 1,056
  • 6
  • 17
  • Hi, do you happen to know what this code would look like in Javascript? I don't know typescript. I'm trying to use the response data from one api request to set a cookie but I'm having a hard time intercepting the response in my middleware. I'd greatly appreciate any JS help with this code please. – Christine Treacy Jun 07 '23 at 01:08