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

# Nomiq Node.js SDK — Complete Installation and Usage Guide

> Install and use the official Nomiq Node.js SDK to integrate AI-powered brand generation into your JavaScript and TypeScript applications.

The `@nomiq/node` package is the official SDK for integrating Nomiq's AI brand generation engine into Node.js applications. It wraps the Nomiq REST API with a fully typed interface, handles authentication, provides automatic retries, and includes built-in utilities for verifying webhook signatures — so you can focus on building rather than managing HTTP boilerplate.

<Steps>
  <Step title="Install the SDK">
    Add `@nomiq/node` to your project using your preferred package manager.

    <CodeGroup>
      ```bash npm theme={null}
      npm install @nomiq/node
      ```

      ```bash yarn theme={null}
      yarn add @nomiq/node
      ```

      ```bash pnpm theme={null}
      pnpm add @nomiq/node
      ```
    </CodeGroup>

    <Tip>
      Store your API key in an environment variable (e.g., `NOMIQ_API_KEY`) and load it with a tool like `dotenv`. Never hardcode secrets directly in your source code or commit them to version control.
    </Tip>
  </Step>

  <Step title="Initialize the Client">
    Import the `Nomiq` class and create a client instance by passing your API key. The client is the single entry point for every SDK method.

    <CodeGroup>
      ```typescript TypeScript theme={null}
      import { Nomiq } from '@nomiq/node';

      const nomiq = new Nomiq({
        apiKey: process.env.NOMIQ_API_KEY as string,
      });
      ```

      ```javascript JavaScript theme={null}
      const { Nomiq } = require('@nomiq/node');

      const nomiq = new Nomiq({
        apiKey: process.env.NOMIQ_API_KEY,
      });
      ```
    </CodeGroup>

    The SDK authenticates every request using the `apiKey` you pass to the constructor, attaching it as a `Bearer` token to the `Authorization` header automatically. All requests are routed to `https://api.nomiq.com/v1`.
  </Step>

  <Step title="Create a Project">
    Before you can generate a brand, you need a Project. Projects are top-level containers that store all generated assets, strategy data, and history nodes associated with a client or campaign.

    ```typescript theme={null}
    const project = await nomiq.projects.create({
      name: 'Acme Corp Rebrand',
      description: 'Enterprise software client — Q3 rebrand initiative.',
    });

    console.log(project.id); // "proj_1A2b3C4d5E"
    ```

    A successful call returns a `Project` object. Save the `project.id` — you will need it to dispatch generation jobs.

    ```json theme={null}
    {
      "id": "proj_1A2b3C4d5E",
      "object": "project",
      "name": "Acme Corp Rebrand",
      "description": "Enterprise software client — Q3 rebrand initiative.",
      "created_at": 1677649420,
      "metadata": {}
    }
    ```
  </Step>

  <Step title="Generate a Brand">
    Call `nomiq.brands.generate()` with your `project_id` and a semantic prompt describing the brand. Because AI generation is computationally intensive, this endpoint returns a `202 Accepted` immediately with a job object. The final assets are delivered via webhook when the job completes.

    ```typescript theme={null}
    const job = await nomiq.brands.generate({
      project_id: 'proj_1A2b3C4d5E',
      prompt:
        'A modern coffee shop in Brooklyn specializing in cold brew. The logo should feature a minimalistic cold brew glass with a deep indigo and cream color palette. Typography should be a clean sans-serif.',
    });

    console.log(job.status); // "queued"
    console.log(job.id);     // "job_9x8y7z6w"
    ```

    The returned job object confirms the request was accepted:

    ```json theme={null}
    {
      "object": "job",
      "id": "job_9x8y7z6w",
      "project_id": "proj_1A2b3C4d5E",
      "status": "queued",
      "created_at": 1677649420
    }
    ```
  </Step>

  <Step title="Handle the Webhook">
    Configure a webhook endpoint in your **Workspace Settings** and listen for `generation.success` or `generation.failed` events. Nomiq signs every webhook request with an HMAC-SHA256 signature in the `Nomiq-Signature` header — always verify this before processing the payload.

    The example below shows a complete Express.js webhook handler. Note that `express.raw()` is required to access the raw request body for signature verification.

    ```typescript theme={null}
    import express from 'express';
    import crypto from 'crypto';

    const app = express();
    const webhookSecret = process.env.NOMIQ_WEBHOOK_SECRET as string;

    app.post(
      '/webhook/nomiq',
      express.raw({ type: 'application/json' }),
      (req, res) => {
        const incomingSig = req.headers['nomiq-signature'] as string;
        const rawBody = req.body as Buffer;

        // Compute the expected HMAC-SHA256 signature
        const expectedSig = crypto
          .createHmac('sha256', webhookSecret)
          .update(rawBody)
          .digest('hex');

        if (
          !crypto.timingSafeEqual(
            Buffer.from(incomingSig, 'hex'),
            Buffer.from(expectedSig, 'hex')
          )
        ) {
          console.error('Webhook signature mismatch — request rejected.');
          return res.status(400).send('Invalid signature.');
        }

        const event = JSON.parse(rawBody.toString());

        if (event.type === 'generation.success') {
          const { job_id, project_id, assets } = event.data;
          console.log(`Job ${job_id} complete for project ${project_id}`);
          console.log('Logo SVG:', assets.logo_svg);
          console.log('Primary color:', assets.primary_color);
          console.log('Font family:', assets.font_family);

          // Queue further processing asynchronously; do not block this handler.
        } else if (event.type === 'generation.failed') {
          console.error(`Job ${event.data.job_id} failed:`, event.data.error.message);
        }

        // Return 200 immediately to acknowledge receipt.
        return res.status(200).send();
      }
    );

    app.listen(3000, () => console.log('Webhook listener running on port 3000'));
    ```
  </Step>
</Steps>

***

## Projects

The `nomiq.projects` namespace exposes the full Projects API. Use these methods to manage your project containers programmatically.

### Create a Project

```typescript theme={null}
const project = await nomiq.projects.create({
  name: 'Velocity Fitness App',
  description: 'Brand identity for a B2C fitness tracking startup.',
});
```

### Retrieve a Project

Fetch the details of any existing project by its ID.

```typescript theme={null}
const project = await nomiq.projects.retrieve('proj_1A2b3C4d5E');

console.log(project.name);       // "Velocity Fitness App"
console.log(project.created_at); // 1677649420
```

### List Projects

Returns all projects in your workspace, sorted newest-first. The response supports cursor-based pagination via `limit` and `starting_after`.

```typescript theme={null}
const { data: projects } = await nomiq.projects.list({
  limit: 20,
});

for (const project of projects) {
  console.log(`${project.id}: ${project.name}`);
}

// Paginate to the next page using the last item's ID as the cursor.
const { data: nextPage } = await nomiq.projects.list({
  limit: 20,
  starting_after: projects[projects.length - 1].id,
});
```

### Delete a Project

```typescript theme={null}
await nomiq.projects.delete('proj_1A2b3C4d5E');
```

<Warning>
  Deleting a project is permanent and irreversible. All associated generated assets, history nodes, and memory data are immediately removed from the database.
</Warning>

***

## Brand Generation

Dispatch a brand generation job by providing a `project_id` and a descriptive `prompt`. You can optionally override the webhook delivery URL on a per-request basis.

```typescript theme={null}
const job = await nomiq.brands.generate({
  project_id: 'proj_1A2b3C4d5E',
  prompt:
    'A boutique law firm in Chicago focused on intellectual property. Professional and authoritative tone. Navy blue and gold color palette with a classic serif typeface.',
  webhook_url: 'https://your-app.com/webhooks/nomiq', // optional override
});

console.log(job.id);     // "job_9x8y7z6w"
console.log(job.status); // "queued"
```

Generation jobs typically complete within 3–10 seconds. Do not poll the API for status — listen for the `generation.success` webhook event instead.

***

## Handling Webhooks

Nomiq delivers the completed brand assets to your webhook endpoint via a `POST` request. The full webhook payload for a `generation.success` event contains the SVG markup, primary color hex value, and font family recommendation:

```json theme={null}
{
  "event_id": "evt_5k6l7m8n",
  "type": "generation.success",
  "created_at": 1677649428,
  "data": {
    "job_id": "job_9x8y7z6w",
    "project_id": "proj_1A2b3C4d5E",
    "memory_id": "mem_X1y2Z3w4",
    "assets": {
      "logo_svg": "<svg>...</svg>",
      "primary_color": "#4f46e5",
      "font_family": "Inter"
    }
  }
}
```

The `memory_id` field in the payload identifies the Memory Node created for this generation. Persist it alongside your job record — you can pass it back to `nomiq.brands.generate()` as the `memory_id` parameter to refine this brand in a future iteration rather than starting from scratch.

Always return a `200 OK` response within 5 seconds of receiving a webhook. Offload any heavy processing (database writes, image transforms, notifications) to an asynchronous queue such as BullMQ or a background worker. If Nomiq does not receive a `200` within the timeout window, it retries using an exponential backoff strategy.

***

## TypeScript Support

The `@nomiq/node` SDK is written in TypeScript and ships with complete type definitions — no `@types/` package required. Every method parameter, response shape, and error object is fully typed, giving you autocomplete and compile-time safety out of the box.

```typescript theme={null}
import { Nomiq, NomiqProject, NomiqJob } from '@nomiq/node';

const nomiq = new Nomiq({ apiKey: process.env.NOMIQ_API_KEY as string });

async function createAndGenerate(
  clientName: string,
  brandPrompt: string
): Promise<NomiqJob> {
  const project: NomiqProject = await nomiq.projects.create({
    name: clientName,
  });

  const job: NomiqJob = await nomiq.brands.generate({
    project_id: project.id,
    prompt: brandPrompt,
  });

  return job;
}
```

***

## Error Handling

The SDK throws structured error objects when the API returns a non-2xx response. Wrap your calls in `try/catch` and inspect the `error.code` property to branch your error handling logic.

```typescript theme={null}
import { Nomiq, NomiqAPIError } from '@nomiq/node';

const nomiq = new Nomiq({ apiKey: process.env.NOMIQ_API_KEY as string });

async function safeGenerate(projectId: string, prompt: string) {
  try {
    const job = await nomiq.brands.generate({
      project_id: projectId,
      prompt,
    });
    return job;
  } catch (error) {
    if (error instanceof NomiqAPIError) {
      switch (error.code) {
        case 'authentication_error':
          console.error('Invalid API key. Check your NOMIQ_API_KEY env var.');
          break;
        case 'rate_limit_exceeded':
          console.error('Rate limit hit. Back off and retry after a delay.');
          break;
        case 'invalid_project':
          console.error('Project not found:', projectId);
          break;
        default:
          console.error(`Nomiq API error [${error.code}]:`, error.message);
      }
    } else {
      // Network or unexpected error
      throw error;
    }
  }
}
```

***

<CardGroup cols={2}>
  <Card title="Python SDK" icon="python" href="/sdks/python">
    Use the official Nomiq Python SDK to integrate brand generation into automation pipelines and backend services.
  </Card>

  <Card title="API Reference" icon="code" href="/api-reference/generation">
    Explore the full REST API reference, including all endpoints, request parameters, and response schemas.
  </Card>
</CardGroup>
