---
name: lokalise-sdk-patterns-54d9a38cfacf
description: |
  Apply production-ready Lokalise SDK patterns for TypeScript and Node.js.
  Use when implementing Lokalise integrations, refactoring SDK usage,
  or establishing team coding standards for Lokalise.
  Trigger with phrases like "lokalise SDK patterns", "lokalise best practices",
  "lokalise code patterns", "idiomatic lokalise".
allowed-tools: Read, Write, Edit
version: 1.0.0
license: MIT
author: Jeremy Longshore <jeremy@intentsolutions.io>
---

# Lokalise SDK Patterns

## Overview
Production-ready patterns for Lokalise SDK usage in TypeScript and Node.js applications.

## Prerequisites
- Completed `lokalise-install-auth` setup
- Familiarity with async/await and TypeScript
- Understanding of error handling best practices

## Instructions

### Step 1: Implement Singleton Client Pattern
```typescript
// src/lokalise/client.ts
import { LokaliseApi } from "@lokalise/node-api";

let instance: LokaliseApi | null = null;

export function getLokaliseClient(): LokaliseApi {
  if (!instance) {
    const apiKey = process.env.LOKALISE_API_TOKEN;
    if (!apiKey) {
      throw new Error("LOKALISE_API_TOKEN environment variable is required");
    }

    instance = new LokaliseApi({
      apiKey,
      enableCompression: true,  // Enable gzip for large responses
    });
  }
  return instance;
}

// Reset for testing
export function resetLokaliseClient(): void {
  instance = null;
}
```

### Step 2: Add Error Handling Wrapper
```typescript
// src/lokalise/errors.ts
import { ApiError } from "@lokalise/node-api";

interface LokaliseResult<T> {
  data: T | null;
  error: LokaliseError | null;
}

interface LokaliseError {
  code: number;
  message: string;
  retryable: boolean;
}

export async function safeLokaliseCall<T>(
  operation: () => Promise<T>
): Promise<LokaliseResult<T>> {
  try {
    const data = await operation();
    return { data, error: null };
  } catch (err) {
    const error = parseLokaliseError(err);
    console.error("[Lokalise]", error);
    return { data: null, error };
  }
}

function parseLokaliseError(err: unknown): LokaliseError {
  if (err instanceof ApiError) {
    return {
      code: err.code,
      message: err.message,
      retryable: [429, 500, 502, 503, 504].includes(err.code),
    };
  }

  return {
    code: 0,
    message: err instanceof Error ? err.message : "Unknown error",
    retryable: false,
  };
}
```

### Step 3: Implement Rate-Limited Queue
```typescript
// src/lokalise/queue.ts
import PQueue from "p-queue";

// Lokalise: 6 requests/sec, 10 concurrent per project
const queue = new PQueue({
  concurrency: 5,  // Stay under concurrent limit
  interval: 1000,
  intervalCap: 5,  // Stay under rate limit
});

export async function queuedLokaliseCall<T>(
  operation: () => Promise<T>
): Promise<T> {
  return queue.add(operation) as Promise<T>;
}

// For batch operations
export async function batchLokaliseOperations<T, R>(
  items: T[],
  operation: (item: T) => Promise<R>
): Promise<R[]> {
  return Promise.all(
    items.map(item => queuedLokaliseCall(() => operation(item)))
  );
}
```

### Step 4: Add Retry Logic
```typescript
// src/lokalise/retry.ts
export async function withRetry<T>(
  operation: () => Promise<T>,
  maxRetries = 3,
  baseDelayMs = 1000
): Promise<T> {
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      return await operation();
    } catch (err: any) {
      const isRetryable = err.code === 429 || (err.code >= 500 && err.code < 600);

      if (!isRetryable || attempt === maxRetries) {
        throw err;
      }

      // Exponential backoff with jitter
      const delay = baseDelayMs * Math.pow(2, attempt - 1);
      const jitter = Math.random() * 500;

      console.log(`[Lokalise] Retry ${attempt}/${maxRetries} in ${delay}ms...`);
      await new Promise(r => setTimeout(r, delay + jitter));
    }
  }
  throw new Error("Unreachable");
}
```

### Step 5: Implement Cursor Pagination Helper
```typescript
// src/lokalise/pagination.ts
import { LokaliseApi, PaginatedResult } from "@lokalise/node-api";

export async function* paginateKeys(
  client: LokaliseApi,
  projectId: string,
  options: { limit?: number } = {}
): AsyncGenerator<any> {
  const limit = options.limit || 500;  // Max 500 as of 2025
  let cursor: string | undefined;

  do {
    const result = await client.keys().list({
      project_id: projectId,
      limit,
      pagination: "cursor",
      cursor,
    });

    for (const key of result.items) {
      yield key;
    }

    cursor = result.hasNextCursor() ? result.nextCursor : undefined;
  } while (cursor);
}

// Usage
async function getAllKeys(projectId: string) {
  const client = getLokaliseClient();
  const keys: any[] = [];

  for await (const key of paginateKeys(client, projectId)) {
    keys.push(key);
  }

  return keys;
}
```

## Output
- Type-safe client singleton with compression
- Robust error handling with retryable detection
- Rate-limited request queue
- Automatic retry with exponential backoff
- Cursor pagination for large datasets

## Error Handling
| Pattern | Use Case | Benefit |
|---------|----------|---------|
| Safe wrapper | All API calls | Prevents uncaught exceptions |
| Request queue | Bulk operations | Respects rate limits |
| Retry logic | Transient failures | Improves reliability |
| Pagination | Large datasets | Memory efficient |

## Examples

### Factory Pattern (Multi-Project)
```typescript
const clients = new Map<string, LokaliseApi>();

export function getClientForProject(projectId: string): LokaliseApi {
  if (!clients.has(projectId)) {
    // Could use different tokens per project if needed
    clients.set(projectId, new LokaliseApi({
      apiKey: process.env.LOKALISE_API_TOKEN!,
      enableCompression: true,
    }));
  }
  return clients.get(projectId)!;
}
```

### Typed Response Wrapper
```typescript
import { Key, Translation, Project } from "@lokalise/node-api";

interface LokaliseService {
  getProject(id: string): Promise<Project>;
  listKeys(projectId: string): Promise<Key[]>;
  updateTranslation(projectId: string, translationId: number, text: string): Promise<Translation>;
}

export const lokaliseService: LokaliseService = {
  async getProject(id) {
    const client = getLokaliseClient();
    return client.projects().get(id);
  },

  async listKeys(projectId) {
    const client = getLokaliseClient();
    const result = await client.keys().list({ project_id: projectId });
    return result.items;
  },

  async updateTranslation(projectId, translationId, text) {
    const client = getLokaliseClient();
    return client.translations().update(translationId, {
      project_id: projectId,
      translation: text,
    });
  },
};
```

### Branch-Aware Client
```typescript
export function getProjectWithBranch(projectId: string, branch?: string): string {
  // Lokalise branch syntax: projectId:branchName
  return branch ? `${projectId}:${branch}` : projectId;
}

// Usage
const projectId = getProjectWithBranch("123456.abcdef", "feature/new-ui");
const keys = await client.keys().list({ project_id: projectId });
```

## Resources
- [Node SDK Documentation](https://lokalise.github.io/node-lokalise-api/)
- [Pagination Guide](https://lokalise.github.io/node-lokalise-api/api/getting-started.html)
- [API Error Codes](https://developers.lokalise.com/reference/api-errors)

## Next Steps
Apply patterns in `lokalise-core-workflow-a` for real-world usage.


---
Source attribution: Dicklesworthstone
Original project: https://github.com/Dicklesworthstone/pi_agent_rust/blob/f28fc46ee0db8e710d95b8b55592cd38d60f2b26/tests/ext_conformance/artifacts/plugins-community/plugins/saas-packs/lokalise-pack/skills/lokalise-sdk-patterns/SKILL.md
License: MIT
License information: https://opensource.org/license/mit
Original upstream instructions; downloaded from Mega AI Hub.

## Upstream license notice

MIT License (with OpenAI/Anthropic Rider)

Copyright (c) 2026 Jeffrey Emanuel

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

ADDITIONAL RIDER / RESTRICTION (OpenAI / Anthropic):

This rider is part of the "conditions" of this License. In the event of any
conflict between this rider and any other portion of this License, this rider
controls.

"Restricted Parties" means OpenAI, L.L.C.; Anthropic, PBC; any of their
respective Affiliates; and any person or entity acting directly or indirectly
on behalf of, for the benefit of, or under the direction of any of the
foregoing (including any officer, director, employee, contractor, agent,
consultant, service provider, or representative).

Notwithstanding any other provision of this License, no rights are granted to
any Restricted Party. Any purported license, sublicense, assignment, transfer,
or other permission to any Restricted Party is null and void absent the
express prior written permission of Jeffrey Emanuel.

You may not provide, disclose, distribute, sublicense, sell, lease, lend,
host, make available, or otherwise permit access to the Software or any
derivative work of the Software (as defined in applicable copyright law)
(collectively, "Derivative Works") to or for any Restricted Party.

For purposes of this rider, "use" includes, without limitation: copying,
modifying, merging, publishing, distributing, sublicensing, selling,
transferring, making available, hosting, deploying, executing, benchmarking,
testing, analyzing, indexing, or incorporating the Software or any Derivative
Works into any dataset, training corpus, evaluation harness, or pipeline for
machine learning or other automated systems.

This rider applies to the Software and all Derivative Works. As a condition of
use, you agree that this rider is a precondition to exercising any rights
under this License, and you agree that any distribution of the Software or any
Derivative Works must include this rider provision unmodified.

Any breach of this rider automatically and immediately terminates the
permissions granted by this License. Upon termination, you must immediately
cease all use and distribution of the Software and any Derivative Works and
destroy all copies under your control.

You agree that a breach of this rider would cause irreparable harm and that
Jeffrey Emanuel may seek injunctive or other equitable relief to enforce this
rider, in addition to any other remedies available at law. To the maximum
extent permitted by applicable law, the prevailing party in any action to
enforce this rider shall be entitled to recover reasonable attorneys' fees and
costs.

For purposes of this rider, "Affiliate" means any entity that directly or
indirectly controls, is controlled by, or is under common control with the
specified party. "Control" means ownership of more than 50% of the voting
securities or other ownership interest, or the power to direct management or
policies by contract or otherwise.

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.



# Mega AI Hub resource metadata

Creator / publisher: Dicklesworthstone
Original project: https://github.com/Dicklesworthstone/pi_agent_rust/blob/f28fc46ee0db8e710d95b8b55592cd38d60f2b26/tests/ext_conformance/artifacts/plugins-community/plugins/saas-packs/lokalise-pack/skills/lokalise-sdk-patterns/SKILL.md
Attribution basis: Source repository record

Fields of work: Development & Engineering, Product Management
Roles: Backend Developer, Growth Product Manager, Product Manager
Specialties: API, Backend
Tools: Lokalise
Country applicability: Country not specified
Classification basis: Source catalog labels
Instruction SHA-256: 991e736dc8c4fa51e3c22e0edfbb9a860f940525add1e07aab43abedae439713
