Skip to main content

N8nClient API

N8nClient is the root entry point. It creates an HTTP client and provides access to all 15 resource clients.

Use this page when you want to understand the shape of the client itself: configuration, collection client access, low-level request helpers, and error behavior.

Constructor

import N8nClient from '@egose/n8n-client';

const client = new N8nClient({
baseUrl: 'http://localhost:5678',
apiKey: process.env.N8N_API_KEY,
});

Config Options

PropertyTypeRequiredDescription
baseUrlstringYesn8n instance URL (e.g. http://localhost:5678)
apiKeystringNo*n8n API key (sent as X-N8N-API-KEY header)
bearerTokenstringNo*JWT token (sent as Authorization: Bearer header)

*Either apiKey or bearerToken must be provided.

Minimal Example

import N8nClient from '@egose/n8n-client';

const client = new N8nClient({
baseUrl: 'http://localhost:5678',
apiKey: process.env.N8N_API_KEY!,
});

const { data: workflows } = await client.workflows().list({ limit: 10 });

Resource Clients

MethodReturnsDescription
workflows()WorkflowClientWorkflow management
executions()ExecutionClientExecution monitoring
credentials()CredentialClientCredential management
tags()TagClientTag management
users()UserClientUser management
variables()VariableClientVariable management
projects()ProjectClientProject management
dataTables()DataTableClientData table management
folders(projectId)FolderClientFolder management (project-scoped)
communityPackages()CommunityPackageClientCommunity package management
audit()AuditClientAudit report generation
insights()InsightsClientExecution insights
sourceControl()SourceControlClientSource control operations
discover()DiscoverClientResource discovery
n8nPackage()N8nPackageClientPackage import/export

Choosing Between Handles And Low-Level Requests

Prefer a resource client when the library already exposes the endpoint you need:

await client.workflows().archive('wf-123');
await client.executions().retry(42, { loadWorkflow: true });

Use the low-level helpers when:

  • you need to experiment against a newly added endpoint before the library wraps it
  • you want to attach custom headers for a one-off request
  • you are intentionally working at the HTTP layer

Plain Objects Vs Resources

Collection client methods like list() and get() return plain API DTOs.

When you want an instance with bound methods, use the opt-in resource methods:

const project = await client.projects().getResource('proj-1');
await project.update({ name: 'Ops' });

const workflow = await client.workflows().getResource('wf-1');
await workflow.activate();

const folders = await project.folders().listResources({ take: '10' });
await folders.data[0]?.update({ name: 'Archived Workflows' });

const renamedFolder = await project.folders().updateResource('folder-id', { name: 'Archived Workflows' });

await project.variables().create({ key: 'API_URL', value: 'https://example.com' });

const createdWorkflow = await project.workflows().create({
name: 'Sync',
nodes: [],
connections: {},
settings: {},
});

const createdFolder = await project.folders().create({ name: 'Operations' });

const table = await project.dataTables().createResource({
name: 'Users',
columns: [{ name: 'email', type: 'string' }],
});

await table.createColumn({ name: 'active', type: 'boolean' });

const recentRuns = await project.executions().listResources({ limit: 10, status: 'success' });
await recentRuns.data[0]?.getTags();

const workflowResource = await client.workflows().getResource('wf-1');
const workflowRuns = await workflowResource.executions().listResources({ limit: 10 });

The current resource layer covers:

  • CommunityPackageResource
  • ProjectResource
  • WorkflowResource
  • CredentialResource
  • DataTableResource
  • ExecutionResource
  • FolderResource
  • TagResource
  • UserResource
  • VariableResource

Nested Collections

Some bound resources expose nested collections for related resources:

const project = await client.projects().getResource('proj-1');

const workflow = await project.workflows().get('wf-1');
const workflowResource = await project.workflows().getResource('wf-1');
const patchedWorkflow = await project.workflows().patch('wf-1', { name: 'Archive Sync' });

const updatedFolder = await project.folders().update('folder-id', { name: 'Archive' });
const updatedFolderResource = await project.folders().updateResource('folder-id', { name: 'Archive' });
const movedFolder = await project.folders().patchResource('folder-id', { parentFolderId: 'new-parent' });

const run = await workflowResource.executions().get(123);
const runResource = await workflowResource.executions().getResource(123);

Rule of thumb:

  • raw nested methods mirror the underlying client/API return type
  • getResource() / createResource() / updateResource() / patchResource() return bound resource instances
  • nested collections only expose the pairs the API can support honestly

Some nested collections are true scoped relationships, while others are filtered or verified convenience relationships:

  • project.folders() is truly project-scoped by endpoint path
  • project.workflows(), project.variables(), and project.executions() use project filters and explicit membership checks where needed
  • project.dataTables() currently supports project-scoped creation plus guarded single-resource access

When a create endpoint returns the created entity, the matching client also exposes createResource():

const workflow = await client.workflows().createResource({
name: 'Sync',
nodes: [],
connections: {},
settings: {},
});

const folder = await client.folders('proj-1').createResource({
name: 'Operations',
});

Rule of thumb:

  • create() mirrors the underlying API/client return type
  • createResource() returns a bound resource instance when the API returns the created entity
  • updateResource() follows the same rule for update endpoints that return the updated entity

projects().createResource() is intentionally not available because the n8n public API returns no project ID or entity body from POST /projects.

For community packages, the equivalent opt-in method is installResource() because the public API uses install/uninstall verbs.

Low-Level Requests

If you need an endpoint or option that is not covered by a resource client yet, N8nClient exposes thin request helpers without exposing the transport object itself:

// GET
const data = await client.get('/workflows', { limit: 5 });

// POST
await client.post('/workflows', { name: 'New Workflow', nodes: [], connections: {}, settings: {} });

// PUT
await client.put('/variables/var-1', { key: 'MY_VAR', value: 'new-value' });

// PATCH
await client.patch('/projects/proj-1', { name: 'Updated Name' });

// DELETE
await client.delete('/workflows/wf-1');

All five helpers (get, post, put, patch, delete) accept an optional headers parameter as the last argument. For full control, use request() with a RequestOptions object:

const result = await client.request<Workflow>({
method: 'GET',
path: '/workflows',
query: { limit: 5 },
headers: { 'X-Custom': 'value' },
});

These helpers still use the same authentication, retry, and response parsing rules as the typed clients.

Error Handling

The client throws HttpError for non-2xx responses:

import { HttpError } from '@egose/n8n-client';

try {
await client.workflows().get('nonexistent');
} catch (error) {
if (error instanceof HttpError) {
console.log(error.status); // 404
console.log(error.message); // "Workflow not found"
console.log(error.data); // Full error response body
}
}

Retry Behavior

Transient errors are retried automatically with exponential backoff:

  • 408 Request Timeout
  • 429 Too Many Requests
  • 500 Internal Server Error
  • 502 Bad Gateway
  • 503 Service Unavailable
  • 504 Gateway Timeout

Non-transient failures are surfaced immediately as HttpError.

Client Scope

Most resource clients are unscoped:

client.workflows()
client.executions()
client.projects()

folders() is the exception because folder endpoints are project-scoped in the n8n API:

const folder = client.folders('project-id');
await folder.list();

Exports

import N8nClient, { HttpClient, HttpError } from '@egose/n8n-client';

// Resource classes
import { WorkflowResource, ExecutionResource, CredentialResource } from '@egose/n8n-client';
import { ProjectResource, FolderResource, DataTableResource } from '@egose/n8n-client';
import { TagResource, UserResource, VariableResource, CommunityPackageResource } from '@egose/n8n-client';

// Collection interfaces (for typing nested collections)
import type {
ProjectWorkflowResourceCollection,
ProjectFolderResourceCollection,
ProjectVariableResourceCollection,
ProjectDataTableResourceCollection,
ProjectExecutionResourceCollection,
WorkflowExecutionResourceCollection,
} from '@egose/n8n-client';

// All API types
import type { RequestOptions, PaginationParams, PaginatedResponse } from '@egose/n8n-client';
import type { Workflow, WorkflowCreate, WorkflowUpdate, Execution, Credential, ... } from '@egose/n8n-client';