> ## Documentation Index
> Fetch the complete documentation index at: https://komga-sdk.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Authentication

> Configure Basic Auth, API keys, headers, sessions, and Fetch credentials for Komga

`createKomgaClient` supports HTTP Basic credentials, Komga API keys, custom headers, and the platform Fetch credentials mode. Authentication is configured on the client; generated operations do not add a separate authentication layer.

> **Basic Auth**
>
> Use a Komga username and password for local development, scripts, or an integration that already has a protected server boundary.

> **API key**
>
> Use a revocable key for server-to-server jobs and long-running deployments. Keep it in a secret store and rotate it without changing application code.

## Basic Auth

```typescript theme={null}
import { createKomgaClient } from 'komga-sdk';

const client = createKomgaClient({
  baseUrl: 'https://komga.example.com',
  auth: {
    type: 'basic',
    username: process.env.KOMGA_USER!,
    password: process.env.KOMGA_PASSWORD!,
  },
});
```

The client sends `Authorization: Basic ...` on each request and performs the UTF-8 Base64 encoding. Use HTTPS whenever credentials leave a local development machine. In a production Node environment, the SDK warns when Basic Auth is configured with an `http:` base URL; the warning does not make HTTP safe.

Basic credentials are sent on every request made with this client. Create a separate client when a request must use a different account or server, rather than mutating shared credentials.

## API-key authentication

Use an API key generated by Komga:

```typescript theme={null}
import { createKomgaClient } from 'komga-sdk';

const client = createKomgaClient({
  baseUrl: 'https://komga.example.com',
  auth: {
    type: 'apiKey',
    key: process.env.KOMGA_API_KEY!,
  },
});
```

The client sends the key as `X-API-Key` on each request. Generate a key in Komga's user settings, give it a descriptive purpose, and store it in an environment variable or secrets manager. Replace the deployment secret during rotation, verify the new key, then revoke the old key.

## Unauthenticated or custom-header clients

`auth` is optional. Leave it out when the Komga server is unauthenticated or when your application owns authentication:

```typescript theme={null}
import { createKomgaClient } from 'komga-sdk';

const client = createKomgaClient({
  baseUrl: 'http://localhost:25600',
  headers: {
    'X-App-Name': 'library-dashboard',
    'X-Trace-Id': 'request-123',
  },
});
```

Headers supplied in `headers` are sent with every request except the auth-owned `Authorization` and `X-API-Key` headers. Configure `auth` for those mechanisms instead of trying to replace them manually. A per-operation `headers` option can add or override request metadata for that call.

## Browser credentials and sessions

Pass the standard Fetch `credentials` mode when a browser application needs to include cookies for its Komga origin:

```typescript theme={null}
import { createKomgaClient, getCurrentUser } from 'komga-sdk';

const client = createKomgaClient({
  baseUrl: 'https://komga.example.com',
  credentials: 'include',
});

const result = await getCurrentUser({ 'remember-me': true }, { client });
if (result.error === undefined) {
  console.log(`Signed in as ${result.data.email}`);
}
```

The SDK does not perform a login flow or exchange tokens. Your application must establish the session and configure the server's cookie and CORS policies. For cross-origin browser requests, the server must allow the exact request origin and credentials; `Access-Control-Allow-Origin: *` cannot be used with credentials. Use a same-origin or server-side proxy when private credentials must not reach the browser.

For integrations that receive a session through an `X-Auth-Token` header and need a cookie response, Komga exposes the generated operation below:

```typescript theme={null}
import { convertHeaderSessionToCookie } from 'komga-sdk';

const result = await convertHeaderSessionToCookie({ client });
const setCookie = result.response?.headers.get('set-cookie');
if (setCookie) {
  console.log('Forward this cookie through your server-side session boundary');
}
```

Do not expose a `Set-Cookie` value to untrusted browser code. Cookie storage and forwarding belong to the application boundary that owns the session.

## Check a session and log out

Use generated operations for session checks and logout; there is no SDK-wide auth state:

```typescript theme={null}
import { getCurrentUser, postLogout1 } from 'komga-sdk';

const current = await getCurrentUser({}, { client });
if (current.response?.status === 401) {
  console.log('Session is not authenticated');
}

const logout = await postLogout1({ client });
if (logout.error) {
  console.error('Logout failed', logout.response?.status, logout.error);
}
```

`postLogout1` is the generated POST operation for `/api/logout`. The generated `postLogout` operation is also present for Komga's GET variant; prefer POST when the server and integration allow it.

## Custom Fetch

The client accepts a Fetch implementation for wrappers, tracing, a proxy, or a different transport:

```typescript theme={null}
import { createKomgaClient } from 'komga-sdk';

const fetchWithLogging: typeof fetch = async (input, init) => {
  const response = await fetch(input, init);
  console.log(response.status, input.toString());
  return response;
};

const client = createKomgaClient({
  baseUrl: 'https://komga.example.com',
  auth: { type: 'apiKey', key: process.env.KOMGA_API_KEY! },
  fetch: fetchWithLogging,
});
```

Treat `input` and `init` as potentially sensitive: do not log `Authorization`, `X-API-Key`, cookies, or response bodies in production. This is a native Fetch hook; the core client does not expose retry, timeout, or debug options.

## Handle authentication failures

Generated operations return structured results instead of throwing by default. Inspect the response status and error body:

```typescript theme={null}
import { getLibraries } from 'komga-sdk';

const result = await getLibraries({ client });

if (result.response?.status === 401) {
  console.error('Credentials were rejected', result.error);
} else if (result.response?.status === 403) {
  console.error('The authenticated user lacks permission', result.error);
} else if (result.error) {
  console.error('Komga request failed', result.error);
}
```

A `401` means the server did not accept the credentials or session. A `403` usually means the user is authenticated but lacks the required library or administrative role. Inspect the generated operation's documentation and Komga permissions before retrying; retrying unchanged credentials will not repair either condition.

If your application prefers exceptions, use `unwrap` and handle `KomgaApiError`:

```typescript theme={null}
import { KomgaApiError, getLibraries, unwrap } from 'komga-sdk';

try {
  const libraries = unwrap(await getLibraries({ client }));
  console.log(libraries.length);
} catch (error) {
  if (error instanceof KomgaApiError) {
    console.error(error.status, error.body);
  }
  throw error;
}
```

## Environment variables and deployment

```dotenv title=".env" theme={null}
KOMGA_URL=https://komga.example.com
KOMGA_USER=admin@example.com
KOMGA_PASSWORD=replace-me
KOMGA_API_KEY=replace-me
```

```typescript title="komga-client.ts" theme={null}
import { createKomgaClient } from 'komga-sdk';

export const client = createKomgaClient({
  baseUrl: process.env.KOMGA_URL!,
  auth: {
    type: 'apiKey',
    key: process.env.KOMGA_API_KEY!,
  },
});
```

Do not commit `.env` files, put secrets in a public frontend bundle, or print the client configuration. Prefer an API key over a password for automation, grant the Komga account only the permissions the integration needs, and rotate or revoke credentials through Komga when a deployment or operator changes.

## Next steps

> **[Quickstart](/quickstart)**
>
> Install the SDK and make a first request.

> **[Fetch configuration](/reference/configuration)**
>
> Review headers, credentials, custom Fetch, and generated options.

> **[Quick reference](/quick-reference)**
>
> Review flat operation signatures and result handling.

> **[Request customization](/interceptors)**
>
> Observe and modify low-level request lifecycles safely.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.