Skip to content

How use guard in nitro or specific middleware to a route #910

Answered by stafyniaksacha
Cyrs2001 asked this question in Q&A
Discussion options

You must be logged in to vote

You can create your own custom createEventHandler like

export interface PrivateContext {
  user: Record<string, any>
}

export function definePrivateEventHandler<T>(
  handler: (event: H3Event, cxt: PrivateContext) => T,
  options: { requireAuth: boolean } = { requireAuth: true }
) {
  return defineEventHandler(async (event) => {
    // you can check request hmac, user, token, etc..
    const token = event.node.req.headers['authorization']
    const user = await getUser(token)

    if (options.requireAuth && !user) {
      throw createError({
        statusCode: 401,
        statusMessage: 'Unauthorized',
      })
    }

    return handler(event, {
      user,
    })
  })
})

then use it i…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by Cyrs2001
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants