---
title: "Hooks"
description: "Extend API system behavior via Nuxt runtime hooks — global request interception, error handling and custom 401 logic."
canonical_url: "https://nuxt.mhaibaraai.me/en/docs/api/hooks"
---
# Hooks

> Extend API system behavior via Nuxt runtime hooks — global request interception, error handling and custom 401 logic.

## Introduction

The Movk Nuxt API system exposes 4 extension points via Nuxt runtime hooks, allowing you to extend and customize API behavior without modifying source code.

All hook types are automatically registered into `RuntimeNuxtHooks` via module declaration; in your editor, `nuxtApp.hook('movk:api:')` provides full auto-completion.

## Available Hooks

### `movk:api:request`

**When triggered**: After auth token injection, before the request is actually sent.

```ts
'movk:api:request': (context: FetchContext) => void | Promise<void>
```

Typical use cases: Adding extra request headers, request logging, modifying request parameters.

```ts [plugins/api-logger.ts]
export default defineNuxtPlugin((nuxtApp) => {
  nuxtApp.hook('movk:api:request', (context) => {
    console.log(`[API] ${context.options.method || 'GET'} ${context.request}`)
  })
})
```

### `movk:api:response`

**When triggered**: After business status code validation passes and data unwrapping is complete.

```ts
'movk:api:response': (
  context: FetchContext & { response: FetchResponse<any> }
) => void | Promise<void>
```

At this point, `context.response._data` is already the unwrapped business data.

Typical use cases: Global data transformation, response logging, performance analysis.

```ts [plugins/api-analytics.ts]
export default defineNuxtPlugin((nuxtApp) => {
  nuxtApp.hook('movk:api:response', (context) => {
    analytics.track('api_success', {
      url: context.request,
      method: context.options.method || 'GET'
    })
  })
})
```

### `movk:api:error`

**When triggered**: On business status code validation failure, HTTP error (4xx/5xx), network failure or timeout. Fires **only once**, after ofetch retries finish; aborts never fire it. For 401 errors, this fires after `movk:api:unauthorized` and is skipped when the business side handled it.

```ts
'movk:api:error': (
  context: FetchContext,
  error: ApiError
) => void | Promise<void>
```

`error` is the normalized [`ApiError`](https://nuxt.mhaibaraai.me/en/docs/api/api-plugin#apierror); `error.data` carries the category, endpoint, business code and raw response body. Typical use cases: Global error reporting (Sentry, etc.), error analytics.

```ts [plugins/error-reporter.ts]
export default defineNuxtPlugin((nuxtApp) => {
  nuxtApp.hook('movk:api:error', (context, error) => {
    if (error.data?.kind === 'network') return

    Sentry.captureException(error, {
      extra: {
        url: context.request,
        endpoint: error.data?.endpoint,
        response: error.data?.response
      }
    })
  })
})
```

### `movk:api:unauthorized`

**When triggered**: When an HTTP 401 response is received, or the business code in the response body (`codeKey`, string values included) is 401, **before** `movk:api:error`. Upload / download progress requests are covered as well.

```ts
'movk:api:unauthorized': (
  context: FetchContext,
  result: { handled: boolean }
) => void | Promise<void>
```

Setting `result.handled = true` **skips the default 401 handling** (clearing the session and redirecting to the login page), as well as `movk:api:error` and the error Toast (the failed request itself still rejects with `ApiError`).

> [!WARNING]
> 
> If multiple handlers listen to this hook, any handler setting 
> 
> result.handled = true
> 
>  will prevent the default behavior.

#### Token Refresh Pattern

```ts [app/plugins/token-refresh.ts]
export default defineNuxtPlugin((nuxtApp) => {
  let refreshing: Promise<void> | null = null

  nuxtApp.hook('movk:api:unauthorized', async (_context, result) => {
    // Run cookie-based session refresh on the client only
    if (import.meta.server) return

    try {
      // Share one in-flight promise across concurrent 401s so all of them await & set handled
      refreshing ??= $fetch('/api/auth/refresh', { method: 'POST' })
        .then(() => useUserSession().fetch())
        .finally(() => { refreshing = null })

      await refreshing
      result.handled = true
      // Re-run active useApiFetch / useAsyncData queries on the current page
      await refreshNuxtData()
    }
    catch {
      // Leave handled = false so Movk clears the session and redirects to login
    }
  })
})
```

## Registration

### In a Nuxt Plugin (Recommended)

Suitable for global logic that is automatically registered at app startup:

```ts [plugins/api-hooks.ts]
export default defineNuxtPlugin((nuxtApp) => {
  nuxtApp.hook('movk:api:request', (context) => {
    // Global request handling
  })

  nuxtApp.hook('movk:api:error', (context, error) => {
    // Global error handling
  })
})
```

### In a Component

Suitable for page-scoped logic:

```vue
<script setup>
const nuxtApp = useNuxtApp()

// Only active on the current page
const unregister = nuxtApp.hook('movk:api:error', (context, error) => {
  // Page-level error handling
})

onUnmounted(() => {
  unregister() // Clean up when the component is destroyed
})
</script>
```

> [!NOTE]
> 
> When registering hooks inside a component, always call the returned unregister function in 
> 
> onUnmounted
> 
>  to avoid memory leaks.

## Execution Order

```text
Request initiated
  │
  ├── Auth token injection
  ├── Debug logging
  ├── movk:api:request             <-- user extension point
  │
  ├── Network request sent ─────────────>
  │
  ├── HTTP 2xx response
  │   ├── Business success (code in successCodes, or businessCheck disabled)
  │   │   ├── Data unwrap (extract dataKey, skipped when unwrap is disabled)
  │   │   ├── movk:api:response    <-- user extension point
  │   │   └── Success Toast
  │   │
  │   └── Business failure → throw ApiError(kind: business), go to exit
  │
  ├── HTTP 4xx/5xx → ofetch retries per retry option, still failing goes to exit
  ├── Network failure / timeout → go to exit
  │
  └── Exit (runs once per request, skipped on abort)
      ├── Normalize to ApiError
      ├── [HTTP or business code 401] movk:api:unauthorized  <-- user extension point
      │       └── (if not handled) clear session + redirect to login
      ├── movk:api:error           <-- user extension point (skipped for handled 401)
      ├── Error Toast              <-- skipped for handled 401
      └── throw ApiError
```

## TypeScript Support

Hook types are automatically registered via module declaration:

```ts [src/runtime/types/module.ts]
declare module 'nuxt/app' {
  interface RuntimeNuxtHooks {
    'movk:api:request': (context: FetchContext) => void | Promise<void>
    'movk:api:response': (context: FetchContext & { response: FetchResponse<any> }) => void | Promise<void>
    'movk:api:error': (context: FetchContext, error: ApiError) => void | Promise<void>
    'movk:api:unauthorized': (
      context: FetchContext,
      result: { handled: boolean }
    ) => void | Promise<void>
  }
}
```

No additional configuration is needed — `nuxtApp.hook('movk:api:...')` provides full type inference and auto-completion out of the box.


## Sitemap

See the full [sitemap](https://nuxt.mhaibaraai.me/sitemap.md) for all pages.
