> ## Documentation Index
> Fetch the complete documentation index at: https://docs.youka.io/llms.txt
> Use this file to discover all available pages before exploring further.

# 认证

> 使用你的 API key 配置 YoukaClient

SDK 会使用 bearer API key 对每个请求进行认证。你只需构建一次 `YoukaClient`，并在进程的整个生命周期内复用它。

## `new YoukaClient(options)`

```ts theme={null}
import { YoukaClient } from "@youka/zh/sdk";

const client = new YoukaClient({
  apiKey: process.env.YOUKA_API_KEY!,
});
```

### Options

<ParamField path="apiKey" type="string" required>
  你的 Youka API key。可在
  [online.youka.io/account](https://online.youka.io/account) 的 **API keys** 下创建。
</ParamField>

<ParamField path="fetch" type="typeof fetch">
  自定义 `fetch` 实现。默认使用全局 `fetch`。可用于注入日志、代理或自定义重试中间件。
</ParamField>

## 存储 API key

<Warning>
  API key 可访问你的计费信息。不要将其提交到源码仓库。
</Warning>

推荐模式：

<Tabs>
  <Tab title="Environment variable">
    ```ts theme={null}
    const client = new YoukaClient({
      apiKey: process.env.YOUKA_API_KEY!,
    });
    ```
  </Tab>

  <Tab title="Secret manager">
    ```ts theme={null}
    import { getSecret } from "./my-secret-manager";

    const client = new YoukaClient({
      apiKey: await getSecret("youka-api-key"),
    });
    ```
  </Tab>
</Tabs>

## 注入自定义 fetch

每个 SDK 方法都会使用你传给构造函数的 `fetch`。这让你很容易添加日志或中间件：

```ts theme={null}
import { YoukaClient } from "@youka/zh/sdk";

const instrumentedFetch: typeof fetch = async (input, init) => {
  const start = Date.now();
  const response = await fetch(input, init);
  console.log(
    `${init?.method ?? "GET"} ${input} ${response.status} in ${Date.now() - start}ms`,
  );
  return response;
};

const client = new YoukaClient({
  apiKey: process.env.YOUKA_API_KEY!,
  fetch: instrumentedFetch,
});
```

## 每个请求的选项

每个方法都接受一个可选的第二或第三个参数，用于传入请求级别的选项：

```ts theme={null}
await client.projects.create(body, {
  idempotencyKey: "import-2026-04-08-song-001",
  signal: abortController.signal,
});
```

<ParamField path="idempotencyKey" type="string">
  以 `Idempotency-Key` 请求头传递。对相同 payload 复用同一个 key 时，将返回原始结果而不是创建重复资源。参见 [API
  idempotency](/zh/api/idempotency)。
</ParamField>

<ParamField path="signal" type="AbortSignal">
  标准的 abort signal。可取消进行中的请求以及长时间运行的
  `client.tasks.wait(...)`, `client.projects.wait(...)`, 和
  `client.exports.wait(...)` 轮询。
</ParamField>

## 接下来

* [Projects](/zh/sdk/projects) — 创建你的第一个项目
* [Errors](/zh/sdk/errors) — 处理认证失败
* [API authentication](/zh/api/authentication) — 原始 HTTP header 细节
