npm package: @i.un/nuxt-api
Description: A robust, production-ready API client module for Nuxt 4. Designed for enterprise-grade authentication handling, SSR compatibility, and seamless token refreshing.
Latest version: 1.0.28

# @i.un/nuxt-api

[![npm version][npm-version-src]][npm-version-href]
[![npm downloads][npm-downloads-src]][npm-downloads-href]
[![License][license-src]][license-href]
[![Nuxt][nuxt-src]][nuxt-href]

A robust, production-ready API client module for Nuxt 4. Designed for enterprise-grade authentication handling, SSR compatibility, and seamless token refreshing.

## Features

- 🔐 **Smart Token Refresh**:
  - Automatic 401 interception and token refreshing.
  - **Request Queueing**: Prevents multiple refresh requests; pending requests retry automatically with the new token.
  - **SSR Support**: Perfectly handles cookie passing between SSR server and backend API.
  - **Cross-Domain & Subdomain Support**: Auto-detects and fixes cookie domains for seamless cross-subdomain authentication.
- 🛡 **Security First**:
  - Respects `HttpOnly` cookies.
  - Does not overwrite backend security flags unless necessary.
- 🛠 **Developer Friendly**:
  - Full TypeScript support with `UseApiOptions`.
  - Configurable Debug Logging.
  - Return full response or just data.

## Installation

```bash
# npm
npm install @i.un/nuxt-api

# pnpm
pnpm add @i.un/nuxt-api

# yarn
yarn add @i.un/nuxt-api
```

## Configuration

Add the module to your `nuxt.config.ts`:

```typescript
export default defineNuxtConfig({
  modules: ['@i.un/nuxt-api'],

  iunApi: {
    // Backend API URL
    apiBase: 'https://api.example.com',
    // Optional: Different URL for SSR (e.g. internal docker network)
    apiBaseServer: 'http://backend-service:8080',

    // Authentication
    cookieName: 'access_token', // Default

    // Endpoints
    endpoints: {
      // Set to false to disable token refresh
      // Or provide a custom refresh endpoint path (e.g. '/auth/refresh')
      refresh: false, // default
    },
    // Redirects
    redirects: {
      // Set to false to disable redirect
      // Or provide a custom redirect path (e.g. '/auth/login')
      login: false, // default
    },

    // Response Parsing default:
    responseConfig: {
      codeKey: 'code',
      dataKey: 'data',
      messageKey: 'message',
      successCode: 0,
      unauthorizedCode: 401,
    },

    // Debugging
    debug: process.env.NODE_ENV === 'development', // Enable detailed logs
  },
});
```

## Usage

### 1. Basic Requests (`useApi`)

`useApi` provides a wrapper around Nuxt's `$fetch` with auto-auth and error handling.

```typescript
<script setup lang="ts">
const api = useApi();

// GET request (returns dataKey directly by default)
const users = await api.get<User[]>('/users');

// POST request
await api.post('/posts', { title: 'Hello' });

// Custom Options (TypeScript supported)
const profile = await api.get('/profile', {}, {
  headers: { 'X-Custom': 'value' },
  timeout: 5000
});
</script>
```

### 2. Get Full Response

Sometimes you need the status code or message, not just the data.

```typescript
const res = await api.post('/submit', formData, {
  returnFullResponse: true,
});

if (res.code === 0) {
  console.log(res.message); // "Success"
  console.log(res.data); // { ... }
}
```

### 3. Manual Token Management (`useTokenRefresh`)

Usually handled automatically, but exposed if needed.

```typescript
const { refreshToken } = useTokenRefresh();

const doRefresh = async () => {
  const newToken = await refreshToken();
  if (newToken) {
    console.log('Token refreshed manually');
  }
};
```

## License

MIT

[npm-version-src]: https://img.shields.io/npm/v/@i.un/nuxt-api.svg?style=flat&colorA=002438&colorB=3B82F6
[npm-version-href]: https://www.npmjs.com/package/@i.un/nuxt-api
[npm-downloads-src]: https://img.shields.io/npm/dm/@i.un/nuxt-api.svg?style=flat&colorA=002438&colorB=4c1
[npm-downloads-href]: https://www.npmjs.com/package/@i.un/nuxt-api
[license-src]: https://img.shields.io/npm/l/@i.un/nuxt-api.svg?style=flat&colorA=002438&colorB=8B5CF6
[license-href]: https://www.npmjs.com/package/@i.un/nuxt-api
[nuxt-src]: https://img.shields.io/badge/Nuxt-00C58E?logo=nuxt.js&style=flat&logoColor=fff
[nuxt-href]: https://nuxt.com/