Skip to main content

Overview

The official Postiz Node.js SDK provides a simple, type-safe interface for interacting with the Postiz API. Built with TypeScript, it offers full IntelliSense support and automatic type checking.

Installation

Install the SDK using npm or yarn:
npm install @postiz/node

Quick Start

import Postiz from '@postiz/node';

// Initialize the client
const postiz = new Postiz('YOUR_API_KEY');

// List connected integrations
const integrations = await postiz.integrations();
console.log(integrations);

// Create a scheduled post
const post = await postiz.post({
  type: 'schedule',
  date: '2024-12-31T12:00:00Z',
  shortLink: true,
  tags: [],
  posts: [{
    integration: { id: 'integration-id' },
    value: [{
      content: 'Hello from Postiz SDK!',
      image: []
    }]
  }]
});

console.log('Post created:', post);

Initialization

Basic Initialization

import Postiz from '@postiz/node';

const postiz = new Postiz('YOUR_API_KEY');

Custom API URL (Self-Hosted)

const postiz = new Postiz(
  'YOUR_API_KEY',
  'https://your-domain.com'  // Custom API URL
);

Environment Variables

// .env file
POSTIZ_API_KEY=your_api_key_here
POSTIZ_API_URL=https://api.postiz.com  // Optional

// Load with dotenv
import 'dotenv/config';
import Postiz from '@postiz/node';

const postiz = new Postiz(
  process.env.POSTIZ_API_KEY,
  process.env.POSTIZ_API_URL
);

Methods

integrations()

Get all connected integrations.
const integrations = await postiz.integrations();

// Returns array of integration objects
[
  {
    id: 'integration-123',
    name: 'Twitter (@johndoe)',
    identifier: 'twitter',
    picture: 'https://...',
    disabled: false,
    profile: '@johndoe'
  },
  // ...
]

post(data)

Create a new post.
const result = await postiz.post({
  type: 'schedule',              // 'schedule' | 'draft' | 'now' | 'update'
  date: '2024-12-31T12:00:00Z',  // ISO 8601 date string
  shortLink: true,               // Use short links
  tags: [],                      // Array of tags
  posts: [                       // Array of post objects
    {
      integration: { id: 'integration-id' },
      value: [
        {
          content: 'Post content',
          image: []
        }
      ]
    }
  ]
});

postList(filters)

Get posts within a date range.
const result = await postiz.postList({
  startDate: '2024-01-01T00:00:00Z',
  endDate: '2024-12-31T23:59:59Z',
  customer: 'customer-id'  // Optional
});

// Returns
{
  posts: [
    {
      id: 'post-123',
      group: 'group-abc',
      publishDate: '2024-12-31T12:00:00Z',
      status: 'scheduled',
      content: 'Post content',
      integration: { ... },
      media: [ ... ]
    },
    // ...
  ]
}

deletePost(id)

Delete a post by ID.
await postiz.deletePost('post-123');

upload(fileBuffer, filename)

Upload a media file.
import { readFileSync } from 'fs';

const fileBuffer = readFileSync('/path/to/image.jpg');
const media = await postiz.upload(fileBuffer, 'image.jpg');

// Returns
{
  id: 'media-abc123',
  path: 'https://cdn.postiz.com/uploads/...',
  name: 'image.jpg'
}

TypeScript Support

The SDK is written in TypeScript and exports all necessary types:
import Postiz, { 
  CreatePostDto,
  GetPostsDto,
  PostContent,
  Integration
} from '@postiz/node';

const postiz = new Postiz(process.env.POSTIZ_API_KEY!);

// Type-safe post creation
const postData: CreatePostDto = {
  type: 'schedule',
  date: '2024-12-31T12:00:00Z',
  shortLink: true,
  tags: [],
  posts: [
    {
      integration: { id: 'integration-id' },
      value: [
        {
          content: 'Hello TypeScript!',
          image: []
        }
      ]
    }
  ]
};

const result = await postiz.post(postData);

Common Patterns

Post with Media

import Postiz from '@postiz/node';
import { readFileSync } from 'fs';

const postiz = new Postiz(process.env.POSTIZ_API_KEY);

// Upload media
const file = readFileSync('./photo.jpg');
const media = await postiz.upload(file, 'photo.jpg');

// Create post with media
await postiz.post({
  type: 'schedule',
  date: '2024-12-31T12:00:00Z',
  shortLink: true,
  tags: [],
  posts: [{
    integration: { id: 'twitter-id' },
    value: [{
      content: 'Check out this photo!',
      image: [{
        id: media.id,
        path: media.path
      }]
    }]
  }]
});

Multi-Platform Post

const integrations = await postiz.integrations();

const twitter = integrations.find(i => i.identifier === 'twitter');
const linkedin = integrations.find(i => i.identifier === 'linkedin');
const facebook = integrations.find(i => i.identifier === 'facebook');

await postiz.post({
  type: 'schedule',
  date: '2024-12-31T12:00:00Z',
  shortLink: true,
  tags: [],
  posts: [
    {
      integration: { id: twitter.id },
      value: [{ content: 'Hello Twitter!', image: [] }]
    },
    {
      integration: { id: linkedin.id },
      value: [{ content: 'Hello LinkedIn!', image: [] }]
    },
    {
      integration: { id: facebook.id },
      value: [{ content: 'Hello Facebook!', image: [] }]
    }
  ]
});

Twitter Thread

await postiz.post({
  type: 'schedule',
  date: '2024-12-31T12:00:00Z',
  shortLink: true,
  tags: [],
  posts: [{
    integration: { id: 'twitter-id' },
    value: [
      {
        content: '1/3 This is the first tweet in the thread...',
        image: []
      },
      {
        content: '2/3 This is the second tweet...',
        image: [],
        delay: 2000  // 2 second delay
      },
      {
        content: '3/3 This is the final tweet!',
        image: [],
        delay: 2000
      }
    ]
  }]
});

Bulk Delete Failed Posts

const { posts } = await postiz.postList({
  startDate: '2024-01-01T00:00:00Z',
  endDate: '2024-12-31T23:59:59Z'
});

const failedPosts = posts.filter(p => p.status === 'failed');

for (const post of failedPosts) {
  await postiz.deletePost(post.id);
  console.log(`Deleted failed post: ${post.id}`);
}

Error Handling

try {
  const result = await postiz.post({
    type: 'schedule',
    date: '2024-12-31T12:00:00Z',
    shortLink: true,
    tags: [],
    posts: [{
      integration: { id: 'invalid-id' },
      value: [{ content: 'Test', image: [] }]
    }]
  });
} catch (error) {
  if (error.message.includes('401')) {
    console.error('Authentication failed. Check your API key.');
  } else if (error.message.includes('429')) {
    console.error('Rate limit exceeded. Wait before retrying.');
  } else if (error.message.includes('400')) {
    console.error('Validation error:', error.message);
  } else {
    console.error('Unexpected error:', error);
  }
}

Rate Limiting with Retry

async function createPostWithRetry(postData, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await postiz.post(postData);
    } catch (error) {
      if (error.message.includes('429') && i < maxRetries - 1) {
        const waitTime = Math.pow(2, i) * 1000; // Exponential backoff
        console.log(`Rate limited. Waiting ${waitTime}ms...`);
        await new Promise(resolve => setTimeout(resolve, waitTime));
        continue;
      }
      throw error;
    }
  }
}

const result = await createPostWithRetry({
  type: 'schedule',
  date: '2024-12-31T12:00:00Z',
  shortLink: true,
  tags: [],
  posts: [{
    integration: { id: 'twitter-id' },
    value: [{ content: 'Hello!', image: [] }]
  }]
});

Source Code

The SDK is open source and available in the Postiz repository:
apps/sdk/src/index.ts
Key implementation details:
export default class Postiz {
  constructor(
    private _apiKey: string,
    private _path = 'https://api.postiz.com'
  ) {}

  async post(posts: CreatePostDto) {
    return (await fetch(`${this._path}/public/v1/posts`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: this._apiKey,
      },
      body: JSON.stringify(posts),
    })).json();
  }

  async postList(filters: GetPostsDto) {
    return (await fetch(
      `${this._path}/public/v1/posts?${toQueryString(filters)}`,
      {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          Authorization: this._apiKey,
        },
      }
    )).json();
  }

  // ... other methods
}

Next Steps

API Reference

Full API documentation

CLI Tool

Use the command-line interface

API Endpoints

View all available endpoints

GitHub

View source code

Build docs developers (and LLMs) love