Guide

Middleware

Run authentication, authorization, metadata, and logging middleware with typed context.

Middleware

Middleware receives { ctx, next, fail, event, metadata, clientInput }. It executes before input validation; treat clientInput as untrusted unknown. The handler receives validated parsedInput.

const contextualClient = actionClient
  .use(async ({ ctx, next, event }) => {
    const userAgent = getHeader(event, 'user-agent')
    return next({ ctx: { ...ctx, userAgent } })
  })
  .use(async ({ ctx, next, metadata }) => {
    console.info('Starting action:', metadata.name)
    const started = Date.now()
    const result = await next({ ctx: { ...ctx, started } })
    console.info('Completed in:', Date.now() - started)
    return result
  })

Context is replaced, not automatically merged, by next({ ctx }). Include ...ctx to retain earlier fields. The middleware's resulting context is inferred downstream.

Call next() exactly once on the path that continues the action. To stop, return fail(code) with a business error declared before the middleware (0.8.1+), throw ActionError for a public string message, or throw another error for a generic unexpected failure. Missing or repeated next() calls are rejected; the handler is not run a second time. Always return or await the continuation so your logging and cleanup follow the handler.

const authClient = actionClient
  .errors({ UNAUTHORIZED: 'Authentication required' })
  .use(async ({ ctx, event, next, fail }) => {
    const session = await getUserSession(event) // nuxt-auth-utils
    if (!session.user?.id) return fail('UNAUTHORIZED')
    return next({ ctx: { ...ctx, userId: session.user.id } })
  })

Install and configure nuxt-auth-utils and augment its session types before using that helper. Authentication proves identity; authorize access to each requested resource in the handler. See the complete recipe.

Metadata

export default contextualClient
  .metadata({ name: 'greet' })
  .schema(z.object({ name: z.string() }))
  .action(({ parsedInput }) => ({ greeting: `Hello, ${parsedInput.name}!` }))

Metadata is configuration attached by server code. It is available to middleware and merged when chaining .metadata(). The H3 event exposes cookies, headers, and request information using H3 helpers. Avoid logging sensitive raw input such as passwords.

Copyright © 2026