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

# Pagination

> Paginate X API responses in TypeScript using UserPaginator and generic paginator utilities with manual fetchNext loops or async iteration for any list endpoint.

The SDK provides generic paginator utilities you can use with any endpoint that returns paginated responses. Methods return plain responses; you wrap them with a paginator.

### Basic Pagination

<CodeGroup dropdown>
  ```typescript quick-start.ts theme={null} theme={null}
  import { Client, UserPaginator, PaginatedResponse, Schemas } from '@xdevplatform/xdk';

  const client: Client = new Client({ bearerToken: 'your-bearer-token' });

  // Wrap any list endpoint with proper typing
  const followers: UserPaginator = new UserPaginator(
    async (token?: string): Promise<PaginatedResponse<Schemas.User>> => {
      const res = await client.users.getFollowers('<userId>', {
        maxResults: 100,
        paginationToken: token,
        userFields: ['id','name','username'],
      });
      return { 
        data: res.data ?? [], 
        meta: res.meta, 
        includes: res.includes, 
        errors: res.errors 
      };
    }
  );
  ```

  ```javascript quick-start.js theme={null} theme={null}
  import { Client } from '@xdevplatform/xdk';
  import { UserPaginator } from '@xdevplatform/xdk';

  const client = new Client({ bearerToken: 'your-bearer-token' });

  const followers = new UserPaginator(async (token) => {
    const res = await client.users.getFollowers('<userId>', {
      maxResults: 100,
      paginationToken: token,
      userFields: ['id','name','username'],
    });
    return { data: res.data ?? [], meta: res.meta, includes: res.includes, errors: res.errors };
  });
  ```
</CodeGroup>

### Manual paging

<CodeGroup>
  ```typescript manual.ts theme={null} theme={null}
  import { UserPaginator, Schemas } from '@xdevplatform/xdk';

  await followers.fetchNext();          // first page
  while (!followers.done) {
    await followers.fetchNext();        // subsequent pages
  }

  const userCount: number = followers.users.length;  // all fetched users
  const firstUser: Schemas.User | undefined = followers.users[0];
  const nextToken: string | undefined = followers.meta?.nextToken;
  ```

  ```javascript manual.js theme={null} theme={null}
  await followers.fetchNext();
  while (!followers.done) await followers.fetchNext();
  console.log(followers.items.length);
  ```
</CodeGroup>

### Async iteration

<CodeGroup>
  ```typescript async.ts theme={null} theme={null}
  import { Schemas } from '@xdevplatform/xdk';

  for await (const user of followers) {
    const typedUser: Schemas.User = user;
    console.log(typedUser.username);  // fully typed access
  }
  ```

  ```javascript async.js theme={null} theme={null}
  for await (const user of followers) {
    console.log(user.username);
  }
  ```
</CodeGroup>

### Next page as a new instance

<CodeGroup>
  ```typescript next.ts theme={null} theme={null}
  import { UserPaginator } from '@xdevplatform/xdk';

  await followers.fetchNext();
  if (!followers.done) {
    const page2: UserPaginator = await followers.next(); // independent paginator starting at next page
    await page2.fetchNext();
    console.log(page2.users.length);  // items from second page
  }
  ```

  ```javascript next.js theme={null} theme={null}
  await followers.fetchNext();
  if (!followers.done) {
    const page2 = await followers.next();
    await page2.fetchNext();
  }
  ```
</CodeGroup>

### Error handling and rate limits

<CodeGroup>
  ```typescript errors.ts theme={null} theme={null}
  import { UserPaginator, Schemas } from '@xdevplatform/xdk';

  try {
    for await (const item of followers) {
      const user: Schemas.User = item;
      // process user...
    }
  } catch (err: unknown) {
    if (followers.rateLimited) {
      console.error('Rate limited, backoff required');
      // backoff / retry later
    } else {
      console.error('Pagination error:', err);
      throw err;
    }
  }
  ```

  ```javascript errors.js theme={null} theme={null}
  try {
    for await (const item of followers) {
      // ...
    }
  } catch (err) {
    if (followers.rateLimited) {
      // backoff / retry later
    } else {
      throw err;
    }
  }
  ```
</CodeGroup>

<Info>
  For detailed code examples using the Javascript/TypeScript XDK, check out our [code samples GitHub repo](https://github.com/xdevplatform/samples/tree/main/javascript).
</Info>
