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

# Type Definitions

Complete TypeScript type definitions for the `@ogify/core` library. These types provide full type safety when creating templates and configuring renderers.

## Core Types

### OgTemplateParams

Base type for template parameters. All template parameter types should extend this.

```typescript theme={null}
type OgTemplateParams = Record<string, string | string[] | number | boolean>;
```

Parameters are the data that gets injected into templates to create personalized OG images. Values can be:

* **Strings**: Text content (titles, descriptions, names)
* **String Arrays**: Lists of tags, categories
* **Numbers**: Counts, dates, metrics
* **Booleans**: Flags, toggles, states

<CodeGroup>
  ```typescript Example theme={null}
  const params: OgTemplateParams = {
    title: "My Blog Post",
    author: "John Doe",
    views: 1234,
    published: true,
    tags: ["typescript", "web development"],
  };
  ```
</CodeGroup>

***

### OgTemplate

Complete definition of an Open Graph image template. A template is a reusable blueprint for generating OG images.

```typescript theme={null}
type OgTemplate<TParams = OgTemplateParams> = {
  renderer: (
    props: OgTemplateOptions & { params: TParams }
  ) => string | ReactNode | Promise<string | ReactNode>;
  fonts: OgFontConfig[];
  emojiProvider?: OgEmojiProvider;
};
```

<ParamField path="renderer" type="function" required>
  Function that generates the template output. Receives `OgTemplateOptions & { params: TParams }` and can return:

  * **`ReactNode`** — JSX element tree passed directly to Satori (**recommended**)
  * **`string`** — HTML string parsed with [`satori-html`](/api-reference/core/html-string-rendering) before Satori
  * **`Promise`** of either — async renderers are fully supported

  **Renderer context props:**

  | Prop            | Type              | Default          | Description                                                                             |
  | --------------- | ----------------- | ---------------- | --------------------------------------------------------------------------------------- |
  | `params`        | `TParams`         | —                | Merged template parameters                                                              |
  | `width`         | `number`          | `1200`           | Canvas width (original, not scaled)                                                     |
  | `height`        | `number`          | `630`            | Canvas height (original, not scaled)                                                    |
  | `fonts`         | `OgFontConfig[]`  | template fonts   | Font override from render options                                                       |
  | `emojiProvider` | `OgEmojiProvider` | template default | Emoji provider override                                                                 |
  | `isRTL`         | `boolean`         | `false`          | Right-to-left layout                                                                    |
  | `scale`         | `number`          | `1`              | Supersampling factor ([do not use for layout](/api-reference/core/scale-supersampling)) |

  See [Rendering Pipeline](/api-reference/core/rendering-pipeline) for details.

  <Warning>
    Returning `null` or `undefined` at the root will throw a clear error instead
    of silently failing later in the Satori pipeline.
  </Warning>

  <Note>
    Satori does not support `dangerouslySetInnerHTML`. For inline styled text in
    JSX templates, use [`htmlSnippet`](/api-reference/core/html-snippet) to parse
    trusted HTML fragments into Satori-compatible flex word containers.
  </Note>
</ParamField>

<ParamField path="fonts" type="OgFontConfig[]" required>
  Custom fonts to use in this template. Must be a non-empty array — `validateTemplate`
  throws at registration time if `fonts` is missing.
</ParamField>

<ParamField path="emojiProvider" type="OgEmojiProvider">
  Optional emoji provider to use in this template. If not specified, defaults to
  `'noto'`.
</ParamField>

***

### OgTemplateRenderer

Configuration for the TemplateRenderer class. Defines available templates, global defaults, and lifecycle hooks.

```typescript theme={null}
type OgTemplateRenderer<
  TMap extends Record<string, OgTemplateParams> = Record<
    string,
    OgTemplateParams
  >
> = {
  templates: { [K in keyof TMap]: OgTemplate<TMap[K]> };
  sharedParams?:
    | Partial<TMap[keyof TMap]>
    | (() => Promise<Partial<TMap[keyof TMap]>>);
  cache?: OgCacheConfig;
  beforeRender?: (
    templateId: keyof TMap,
    params: TMap[keyof TMap]
  ) => void | Promise<void>;
  afterRender?: (
    templateId: keyof TMap,
    params: TMap[keyof TMap],
    imageBuffer: Buffer
  ) => void | Promise<void>;
};
```

<ParamField path="templates" type="object" required>
  Map of template definitions to register, keyed by template ID
</ParamField>

<ParamField path="sharedParams" type="object | function">
  Shared parameter values applied to all templates. These values are merged with
  user-provided parameters, with user values taking precedence.
</ParamField>

<ParamField path="cache" type="OgCacheConfig">
  Cache configuration for fonts and icons. When provided, enables LRU caching to
  improve performance by reducing redundant network requests.
</ParamField>

<ParamField path="beforeRender" type="function">
  Hook called before rendering. Useful for logging, analytics, parameter
  validation, authentication checks, and rate limiting.
</ParamField>

<ParamField path="afterRender" type="function">
  Hook called after rendering. Useful for caching generated images, cleanup
  operations, sending notifications, and updating metrics.
</ParamField>

***

## Font Configuration

### OgFontConfig

Configuration for a font used in OG image templates. Fonts can be loaded from three sources (in priority order):

1. Pre-loaded binary data (via `data` property)
2. Remote URL (via `url` property)
3. Google Fonts API (automatic detection based on `name`)

```typescript theme={null}
type OgFontConfig = {
  name: string;
  weight?: FontWeight;
  style?: FontStyle;
  url?: string;
  data?: Buffer | ArrayBuffer;
  format?: OgFontFormat;
};
```

<ParamField path="name" type="string" required>
  The font family name (e.g., 'Inter', 'Roboto', 'Merriweather')
</ParamField>

<ParamField path="weight" type="number" default={400}>
  Font weight (100-900)
</ParamField>

<ParamField path="style" type="'normal' | 'italic'" default="normal">
  Font style
</ParamField>

<ParamField path="url" type="string">
  URL to the font file (for custom/self-hosted fonts)
</ParamField>

<ParamField path="data" type="Buffer | ArrayBuffer">
  Pre-loaded font binary data
</ParamField>

<ParamField path="format" type="'woff' | 'ttf'" default="woff">
  Font file format
</ParamField>

<CodeGroup>
  ```typescript Google Fonts (Automatic) theme={null}
  const font1: OgFontConfig = {
    name: "Inter",
    weight: 400,
    style: "normal",
  };
  ```

  ```typescript Custom URL theme={null}
  const font2: OgFontConfig = {
    name: "CustomFont",
    url: "https://example.com/font.woff2",
    weight: 700,
  };
  ```

  ```typescript Pre-loaded Data theme={null}
  const font3: OgFontConfig = {
    name: "MyFont",
    data: fontBuffer,
    weight: 400,
  };
  ```
</CodeGroup>

***

### OgFontFormat

Supported font file formats.

```typescript theme={null}
type OgFontFormat = "woff" | "ttf";
```

* **`woff`**: Web Open Font Format (modern, compressed)
* **`ttf`**: TrueType Font (legacy, larger file size)

***

## Template Options

### OgTemplateOptions

Props passed to the template `renderer` function, merged with `params`. Also available as options in `renderToImage`.

```typescript theme={null}
type OgTemplateOptions = {
  fonts?: OgFontConfig[];
  emojiProvider?: OgEmojiProvider;
  width?: number;
  height?: number;
  isRTL?: boolean;
  scale?: number;
};
```

The renderer is always called as:

```typescript theme={null}
template.renderer({ params, ...options, width, height });
```

Templates always receive the **original** `width`/`height` values. The `scale` option only affects Resvg rasterization — not Satori layout. See [Scale & Supersampling](/api-reference/core/scale-supersampling).

<ParamField path="fonts" type="OgFontConfig[]">
  Custom fonts to use in this template
</ParamField>

<ParamField path="emojiProvider" type="OgEmojiProvider">
  Optional emoji provider to use in this template
</ParamField>

<ParamField path="width" type="number" default={1200}>
  Optional custom width in pixels. Templates always receive the original
  `width`/`height` values — `scale` is applied at the rasterisation step.
</ParamField>

<ParamField path="height" type="number" default={630}>
  Optional custom height in pixels
</ParamField>

<ParamField path="isRTL" type="boolean" default={false}>
  Enable Right-to-Left text direction
</ParamField>

<ParamField path="scale" type="number" default={1}>
  Supersampling scale factor for higher-quality PNG output. Satori renders the
  SVG at the original `width × height`; Resvg then rasterises it at
  `width × scale` pixels wide.

  | `scale`         | Output dimensions | Notes                                 |
  | --------------- | ----------------- | ------------------------------------- |
  | `1` *(default)* | 1200 × 630        | No change — fully backward compatible |
  | `1.25`          | 1500 × 787        | Mild quality boost                    |
  | `1.5`           | 1800 × 945        | Good quality / size balance           |
  | `2`             | 2400 × 1260       | **Recommended** — @2x retina          |
  | `3`             | 3600 × 1890       | @3x ultra                             |
  | `4`             | 4800 × 2520       | Maximum (clamped)                     |

  **Constraints:**

  * Float values are supported (`1.25`, `1.5`, etc.)
  * Values below `1` are clamped to `1`
  * Values above `4` are clamped to `4` (prevents OOM)
  * Output PNG file size increases proportionally to `scale²`
</ParamField>

<CodeGroup>
  ```tsx JSX Renderer (Recommended) theme={null}
  renderer: ({ params, width, height, isRTL }) => (
    <div
      tw="flex flex-col w-full h-full"
      style={{ width, height }}
    >
      <div tw="text-[64px] font-bold">{params.title}</div>
      <div tw="text-[28px]">{params.description}</div>
    </div>
  ),
  ```

  ```typescript HTML String Renderer theme={null}
  renderer: ({ params, width, height }) => `
    <div style="width: ${width}px; height: ${height}px">
      <h1>${params.title}</h1>
      <p>${params.description}</p>
    </div>
  `,
  ```
</CodeGroup>

***

## Emoji Providers

### OgEmojiProvider

Supported emoji providers for rendering emoji characters in OG images. Each provider offers a different visual style.

```typescript theme={null}
type OgEmojiProvider =
  | "twemoji"
  | "fluent"
  | "fluentFlat"
  | "noto"
  | "blobmoji"
  | "openmoji";
```

<AccordionGroup>
  <Accordion icon="twitter" title="twemoji">
    Twitter's emoji set - colorful, rounded style
  </Accordion>

  <Accordion icon="microsoft" title="fluent">
    Microsoft's Fluent emoji - 3D style with color
  </Accordion>

  <Accordion icon="microsoft" title="fluentFlat">
    Microsoft's Fluent emoji - flat 2D style
  </Accordion>

  <Accordion icon="google" title="noto">
    Google's Noto Color Emoji - current standard (default)
  </Accordion>

  <Accordion icon="google" title="blobmoji">
    Google's blob-style emoji - deprecated but still available
  </Accordion>

  <Accordion icon="palette" title="openmoji">
    Open-source emoji with outlined style
  </Accordion>
</AccordionGroup>

***

## Utility Types

### OgTemplateRenderResult

Return type of a template `renderer` function.

```typescript theme={null}
type OgTemplateRenderResult = string | ReactNode;
```

* **`ReactNode`** — passed directly to Satori (JSX templates)
* **`string`** — parsed with [`satori-html`](/api-reference/core/html-string-rendering), then passed to Satori

### HtmlSnippetOptions

Options for [`htmlSnippet`](/api-reference/core/html-snippet) word-container layout.

```typescript theme={null}
type HtmlSnippetOptions = {
  justify?: "flex-start" | "center" | "flex-end";
  gap?: number;
  fontSize?: number;
};
```

<ParamField path="justify" type="'flex-start' | 'center' | 'flex-end'" default="flex-start">
  Flex main-axis alignment for the word container.
</ParamField>

<ParamField path="gap" type="number">
  Gap between word items in pixels. Overrides the font-size-derived default.
</ParamField>

<ParamField path="fontSize" type="number">
  Font size in pixels. Used to derive gap when `gap` is omitted (\~29% of font size).
</ParamField>

***

## Caching

### OgCacheConfig

Cache configuration for fonts and icons. Supports two caching strategies: memory and filesystem.

```typescript theme={null}
type OgCacheConfig =
  | {
      type: "memory";
      ttl?: number;
      max?: number;
    }
  | {
      type: "filesystem";
      dir?: string;
      ttl?: number;
      max?: number;
    };
```

<Tabs>
  <Tab title="Memory Cache">
    Fast in-memory cache with LRU eviction

    <ParamField path="type" type="'memory'" required>
      Memory-based caching strategy
    </ParamField>

    <ParamField path="ttl" type="number" default={3600000}>
      Time-to-live in milliseconds (default: 1 hour)
    </ParamField>

    <ParamField path="max" type="number" default={100}>
      Maximum number of items to cache
    </ParamField>

    ```typescript theme={null}
    const cache: OgCacheConfig = {
      type: 'memory',
      ttl: 3600000, // 1 hour
      max: 100
    };
    ```
  </Tab>

  <Tab title="Filesystem Cache">
    Persistent cache stored on disk

    <ParamField path="type" type="'filesystem'" required>
      Filesystem-based caching strategy
    </ParamField>

    <ParamField path="dir" type="string" default=".ogify-cache">
      Directory to store cache files
    </ParamField>

    <ParamField path="ttl" type="number" default={3600000}>
      Time-to-live in milliseconds (default: 1 hour)
    </ParamField>

    <ParamField path="max" type="number" default={100}>
      Maximum number of items to cache
    </ParamField>

    ```typescript theme={null}
    const cache: OgCacheConfig = {
      type: 'filesystem',
      dir: '.cache/ogify',
      ttl: 7200000, // 2 hours
      max: 200
    };
    ```
  </Tab>
</Tabs>
