coolify.ts
v0.1.0
Published
coolify pro max
Maintainers
Readme
coolify.ts
coolify pro max
installation
bun add coolify.ts
# or npm, pnpm, yarnles goooo
import { Coolify } from 'coolify.ts'
// Initialize the client
const coolify = new Coolify({
token: process.env.COOLIFY_TOKEN,
baseUrl: 'https://app.coolify.io', // or your self-hosted URL
})
// Use entity methods (recommended - better DX)
const apps = await coolify.getAllApplications()
console.log(`You have ${apps.length} applications`)
// Navigate relations and perform actions
const app = apps[0]
const deployments = await app.deployments()
await app.start()
// Or use direct API methods for raw operations
const appData = await coolify.api.applications.list()
await coolify.api.applications.start(app.uuid)
// Deploy and wait for completion
const deployment = await coolify.api.deployments.deployAndWait(app.uuid, {
timeout: 600000,
onProgress: (d) => console.log(`Status: ${d.status}`),
})features
entity access (recommended uwu)
work with relational, connected entities for the best dx:
// Get applications as entities
const apps = await coolify.getAllApplications()
// Navigate relations
const app = apps[0]
const deployments = await app.deployments()
const project = await app.project()
const server = await app.server()
// Perform actions directly on entities
await app.start()
await app.deploy({ force_rebuild: true })
await app.restart()
// Get specific entities by UUID
const app = await coolify.getApplicationByUUID('app-uuid')
const db = await coolify.getDatabaseByUUID('db-uuid')
const deployment = await coolify.getDeploymentByUUID('deployment-uuid')direct api access
use coolify.api.* for raw api operations when you need em:
// Applications
const apps = await coolify.api.applications.list()
const app = await coolify.api.applications.getById('app-uuid')
await coolify.api.applications.start('app-uuid')
await coolify.api.applications.restart('app-uuid')
// Databases
const dbs = await coolify.api.databases.list()
const db = await coolify.api.databases.createPostgreSQL({
project_uuid: 'proj-uuid',
server_uuid: 'server-uuid',
environment_name: 'production',
postgres_password: 'secure-password',
})
// Services
const services = await coolify.api.services.list()
const service = await coolify.api.services.create({
type: 'n8n',
project_uuid: 'proj-uuid',
server_uuid: 'server-uuid',
environment_name: 'production',
})
// Unified resource access
const allResources = await coolify.api.resources.listAll()
const counts = await coolify.api.resources.getCounts()
const prodApps = await coolify.api.resources.search('production')env vars
env var management that actually works:
// List environment variables
const envVars = await coolify.api.applications.envVars.list('app-uuid')
// Create or update
await coolify.api.applications.envVars.upsert('app-uuid', 'DATABASE_URL', 'postgres://...')
// Bulk operations
await coolify.api.applications.envVars.updateBulk('app-uuid', {
data: [
{ key: 'NODE_ENV', value: 'production' },
{ key: 'PORT', value: '3000' },
],
})
// Sync from .env file
import { EnvUtils } from 'coolify.ts'
await EnvUtils.syncFromEnvFile(coolify, 'app-uuid', '.env.production')
// Export to .env file
await EnvUtils.exportToEnvFile(coolify, 'app-uuid', '.env.backup')
// Validate required variables
const validation = EnvUtils.validateEnvVars(envVars, {
DATABASE_URL: [EnvUtils.validators.required(), EnvUtils.validators.url()],
PORT: [EnvUtils.validators.required(), EnvUtils.validators.integer()],
})deployments
real-time deployment management with streaming and workflows:
// Deploy with retry on failure
const deployment = await coolify.api.deployments.deployWithRetry('app-uuid', {
maxRetries: 3,
retryDelay: 5000,
})
// Stream logs in real-time
const cancel = coolify.api.deployments.streamLogs('deployment-uuid', (log) => {
console.log(`[${log.timestamp}] ${log.message}`)
})
// Canary deployment
await coolify.api.deployments.canaryDeploy('app-uuid', {
canaryWeight: 10, // 10% of traffic
canaryDuration: 300000, // 5 minutes
healthCheck: async () => {
const res = await fetch('https://app.example.com/health')
return res.ok
},
})
// Blue-green deployment
await coolify.api.deployments.blueGreenDeploy('app-uuid', {
healthCheck: async () => true,
switchDelay: 30000,
})
// Rollback to previous version
await coolify.api.deployments.rollback('app-uuid')pagination & caching
efficient data handling with automatic pagination and caching:
import { getAllPages, iterateItems } from 'coolify.ts'
// Get all pages automatically
const allApps = await getAllPages(
(opts) => coolify.api.applications.list(opts),
{ perPage: 50 }
)
// Iterate through items one by one
for await (const app of iterateItems((opts) => coolify.api.applications.list(opts))) {
console.log(app.name)
}
// Enable caching for better performance
const coolify = new Coolify({
token: process.env.COOLIFY_TOKEN,
cache: {
enabled: true,
ttl: 300000, // 5 minutes
maxSize: 100,
},
})
// Check cache statistics
const stats = coolify.client.getCacheStats()
console.log(`Cache hit rate: ${(stats.hitRate * 100).toFixed(2)}%`)webhooks
import { Webhooks } from 'coolify.ts'
// Create webhook handler
const handler = Webhooks.createWebhookHandler({
secret: process.env.WEBHOOK_SECRET!,
})
// Register event handlers
handler.on('application.deployed', async (event) => {
console.log(`${event.data.application_name} deployed!`)
await notifySlack(event.data)
})
handler.on('server.unreachable', async (event) => {
console.error(`Server ${event.data.server_name} is down!`)
await triggerAlert(event.data)
})
// Express integration
import express from 'express'
app.post('/webhooks/coolify', async (req, res) => {
await handler.handle(req.body, req.headers)
res.json({ success: true })
})
// Next.js integration
import { Webhooks } from 'coolify.ts'
export const POST = Webhooks.createNextWebhookHandler(
{ secret: process.env.WEBHOOK_SECRET! },
{
'application.deployed': async (event) => {
// Handle deployment
},
}
)config
import { Coolify } from 'coolify.ts'
const coolify = new Coolify({
// Required: API token
token: process.env.COOLIFY_TOKEN,
// Optional: Base URL (defaults to Coolify Cloud)
baseUrl: 'https://app.coolify.io',
// Optional: Request timeout in ms
timeout: 30000,
// Optional: Max retry attempts
maxRetries: 3,
// Optional: Custom headers
headers: {
'X-Custom-Header': 'value',
},
// Optional: Enable debug logging
debug: true,
// Optional: Enable caching
cache: {
enabled: true,
ttl: 300000,
maxSize: 100,
},
})error handling
import {
CoolifyAPIError,
CoolifyAuthenticationError,
CoolifyNotFoundError,
CoolifyValidationError,
CoolifyRateLimitError,
CoolifyTimeoutError,
} from 'coolify.ts'
try {
const app = await coolify.applications.getById('invalid-uuid')
} catch (error) {
if (error instanceof CoolifyNotFoundError) {
console.error('Application not found')
} else if (error instanceof CoolifyAuthenticationError) {
console.error('Invalid API token')
} else if (error instanceof CoolifyValidationError) {
console.error('Validation errors:', error.errors)
} else if (error instanceof CoolifyRateLimitError) {
console.error(`Rate limited. Retry after ${error.retryAfter}ms`)
}
}typescript support
full type safety with auto-generated types from openapi:
import type {
operations,
components,
ApplicationUUID,
ServerUUID,
} from 'coolify.ts'
// Branded UUIDs prevent mixing different resource types
const appId: ApplicationUUID = '...'
const serverId: ServerUUID = '...'
// Fully typed API operations
type CreateAppRequest =
operations['create-public-application']['requestBody']['content']['application/json']
// Component schemas
type Application = components['schemas']['Application']advanced stuffs
github apps
// Create GitHub App
const app = await coolify.api.githubApps.create({
name: 'My GitHub App',
api_url: 'https://api.github.com',
html_url: 'https://github.com',
app_id: '123456',
installation_id: '789012',
client_id: 'Iv1.abc123',
client_secret: 'secret',
webhook_secret: 'webhook_secret',
private_key_uuid: 'key-uuid',
})
// Load repositories
const repos = await coolify.api.githubApps.loadRepositories(app.uuid)private keys
// Create SSH key
const key = await coolify.api.privateKeys.create({
name: 'Production Server Key',
private_key: '-----BEGIN OPENSSH PRIVATE KEY-----\n...\n-----END OPENSSH PRIVATE KEY-----',
description: 'Key for production servers',
})
// Validate key format
const isValid = coolify.api.privateKeys.validateFormat(keyString)request interceptors
// Add custom request interceptor
coolify.client.addRequestInterceptor(async (url, options) => {
console.log(`Making request to ${url}`)
})
// Add response interceptor
coolify.client.addResponseInterceptor(async (response) => {
console.log(`Response status: ${response.status}`)
})examples
check out the /examples directory for more:
development
# install dependencies
bun install
# run tests
bun test
# build
bun run build
# type check
bun run typecheck
# generate types from openapi
bun run generate:typescontributing
contributions are welcome uwu! check out the contributing guide for details.
license
MIT
