Skip to content

Node.js Connector

The Node.js connector is an NPM package that integrates your Node.js applications with Patcherly for automated error detection and fixing.

Registry: npm - @patcherly/nodejs-connector - use @latest; Node.js versions independently from other stacks (see Connectors overview: Package registries).

Easiest setup: if you have terminal access, use the Universal Installer - no need to configure anything manually. The steps below are for manual package installation.

Quick Start

Get up and running in minutes:

# 1. Install the package
npm install @patcherly/nodejs-connector@latest

# 2. Pair with your Patcherly site (OAuth Device Authorization Grant)
npx patcherly login

# 3. Initialize and start the agent
node -e "require('@patcherly/nodejs-connector').NodeConnector.start()"

patcherly login prints a verification_uri and a short user code. Open the URL in any browser, sign in to your Patcherly dashboard, select the site or app, and confirm the code. Credentials are saved to ~/.patcherly/credentials.json.

Default is full (WordPress defaults to off until chosen in WP admin).

npx patcherly context get
npx patcherly context set full|minimal|off
npx patcherly context upload

Env PATCHERLY_CONTEXT_CONSENT overrides {PATCHERLY_CACHE_DIR}/context_consent.

The connector will automatically: - Read OAuth credentials from ~/.patcherly/credentials.json - Start monitoring your application logs - Sign requests with the per-token HMAC secret from the credential file

Installation

Step 1: Install the Package

npm install @patcherly/nodejs-connector@latest

Or using yarn:

yarn add @patcherly/nodejs-connector

Step 2: Pair with a Site (OAuth)

Run the login command once per site server:

npx patcherly login

Follow the prompt: open the printed URL in any browser, sign in, and confirm the user code. Credentials are saved to ~/.patcherly/credentials.json. To log out and revoke the token, run npx patcherly logout - Patcherly also flips the site row on the dashboard from healthy/stale to inactive immediately on the same call (no more "still says healthy three days after I logged out" surprises).

If you want to customise paths, create a .env file:

# OPTIONAL: Custom paths
PATCHERLY_BACKUP_ROOT=.patcherly_backups
PATCHERLY_QUEUE_PATH=patcherly_queue.jsonl
PATCHERLY_IDS_PATH=patcherly_ids.json

Step 3: Initialize the Agent

In your application's main file:

const { NodeConnector } = require('@patcherly/nodejs-connector');

// Credentials are read from ~/.patcherly/credentials.json
const connector = new NodeConnector({
    logFile: 'logs/error.log'
});

// Start monitoring
connector.start();

Alternative Installation: Direct File Upload

If you prefer to upload the connector files directly to your environment instead of using npm:

Step 1: Download and Upload Connector Files

  1. Download the Node.js Connector Files
  2. Download nodejs-connector.tar.gz from the Patcherly downloads CDN (see latest.json on the connectors feed for the current version).
  3. Extract it into your install directory - the universal installer's default is /opt/patcherly-connector/ on Linux/macOS and %USERPROFILE%\patcherly-connector\ on Windows; you can pick any path as long as you reference the same one in the start commands and systemd unit below. Use all files from the archive - the agent needs every module (OAuth client, auth provider, credential store, patcherly CLI, etc.) to pair and run; missing files break login or apply.

Tip: Most installs go through the universal installer instead (curl https://api.patcherly.com/install | bash) which downloads and extracts the right archive for you. The manual path above is for environments where the installer can't run.

  1. Install Required Dependencies
  2. The connector uses built-in Node.js modules (fs, path, http, url, crypto)
  3. Optional (for local approvals UI): npm install express or yarn add express
  4. Optional (for automatic .env file loading): npm install dotenv or yarn add dotenv
    • Note: If dotenv is not installed, the connector will manually parse .env files
  5. No other external dependencies required

Step 2: Pair with a Site and Configure

Run npx patcherly login (from the extracted connector directory) to complete OAuth pairing. Optionally, create a .env file for custom paths:

# OPTIONAL: Custom paths
PATCHERLY_BACKUP_ROOT=.patcherly_backups
PATCHERLY_QUEUE_PATH=patcherly_queue.jsonl
PATCHERLY_IDS_PATH=patcherly_ids.json

Step 3: Start the Agent

Option A: Run as Standalone Script (Recommended)

The connector can be run directly as a Node.js script:

# From the connector directory
cd /opt/patcherly-connector
node patcherly_agent.js

# Or with command-line options
node patcherly_agent.js --api  # Enable API server mode for file content retrieval
node patcherly_agent.js --approvals-port 8082  # Set port for local approvals UI

# Or from your project root
node /opt/patcherly-connector/patcherly_agent.js

Available Command-Line Options: - --api: Enable API server mode (for file content retrieval). The server binds to 127.0.0.1 only and requires Authorization: Bearer <oauth-access-token> plus an X-Patcherly-Signature + X-Patcherly-Timestamp (5-minute window). The signed JSON body must include error_id. File reads are constrained to PATCHERLY_TARGET_ROOTS (path-separator delimited list of allowed roots) or the connector's working directory, enforced after fs.realpathSync.native() so symlink escapes are blocked. - --approvals-port <port>: Port for local approvals UI (default: 8082). Binds to 127.0.0.1 only and requires Authorization: Bearer <oauth-access-token> on GET /local-approvals, POST /local-approvals/{id}/approve, and POST /local-approvals/{id}/reject-patch. The {id} path segment must match ^[A-Za-z0-9_-]{1,128}$. /reject-patch requires a resolution body (manual_suggestion, manual_own, or not_needed).

Option B: Import and Run in Your Application

// Add connector directory to require path
const path = require('path');
const connectorPath = path.join(__dirname, 'patcherly-connector');

// Import the connector functions
const { monitorLogs, processError, applyFix, rollback } = require(path.join(connectorPath, 'patcherly_agent'));

// Start monitoring (runs continuously)
monitorLogs();

// The connector automatically:
// - Reads OAuth credentials from ~/.patcherly/credentials.json
// - Reads configuration from environment variables / .env
// - Discovers workspace and site IDs
// - Monitors logs for errors
// - Processes fixes from the queue

Option C: Run as Background Process

# Run in background
cd /opt/patcherly-connector
nohup node patcherly_agent.js > ../logs/agent.log 2>&1 &

# Or using PM2 (recommended for Node.js)
cd /opt/patcherly-connector
pm2 start patcherly_agent.js --name patcherly-connector
pm2 save
pm2 startup

Option D: Run as Systemd Service (Linux)

Create /etc/systemd/system/patcherly-connector.service:

[Unit]
Description=Patcherly Node.js Agent
After=network.target

[Service]
Type=simple
User=your_user
WorkingDirectory=/opt/patcherly-connector
EnvironmentFile=/opt/patcherly-connector/.env
ExecStart=/usr/bin/node /opt/patcherly-connector/patcherly_agent.js
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target

Then enable and start:

sudo systemctl enable patcherly-connector
sudo systemctl start patcherly-connector

Configuration

Credentials (OAuth)

The connector reads authentication credentials from ~/.patcherly/credentials.json, created when you run patcherly login.

Optional Settings

  • SERVER_URL or PATCHERLY_API_BASE: Leave unset for normal use (the agent talks to https://api.patcherly.com). Only set one of these if Patcherly Support gives you a specific API host - use the same value for patcherly login --api-base and the running agent.
  • PATCHERLY_BACKUP_ROOT: Backup directory (default: .patcherly_backups)
  • PATCHERLY_QUEUE_PATH: Queue file path (default: patcherly_queue.jsonl)
  • PATCHERLY_IDS_PATH: Workspace/site IDs cache (default: patcherly_ids.json)

HMAC Signing

HMAC signing uses the per-token secret bundled in ~/.patcherly/credentials.json at OAuth issuance. You do not need to configure a secret manually: - Each OAuth token includes its own unique HMAC signing secret - The connector reads it from the credential file automatically - HMAC verification is always mandatory for fix payloads

Supported Applications & File Types

✅ Supported Applications

The Node.js connector is designed for server-side Node.js applications:

  • Express - Web application framework
  • Koa - Next-generation web framework
  • NestJS - Progressive Node.js framework
  • Next.js - Full-stack React framework (server-side code only)
  • Any Node.js backend application - Custom Node.js servers, APIs, microservices

The connector automatically detects which framework you're using and includes this information in error context.

✅ Supported File Types

The connector can patch and validate syntax for:

  • .js - Standard JavaScript files
  • .jsx - JavaScript with JSX (React server components)
  • .mjs - ES modules
  • .cjs - CommonJS modules

❌ Not Supported

Client-side JavaScript applications: - React apps running in the browser (use Next.js connector for server-side Next.js code) - Angular apps running in the browser - Vue.js apps running in the browser - Basic websites with client-side JavaScript

Why? The connector runs on your server and monitors server-side log files. It can only patch files on the server, not code that executes in the browser.

Note for Next.js users: The connector can fix server-side Next.js code (API routes, server components, middleware), but cannot fix client-side React components that run in the browser.

Features

Automatic Error Detection

The connector automatically:

  • Monitors log files for errors
  • Detects new error entries
  • Sends error context to Patcherly
  • Tracks error signatures and occurrences

Did you know? The Node.js agent runs separately from your app and only detects lines from log files it watches. If errors are missing in Patcherly, confirm your app writes failures to a monitored file and add any custom path under Sites → expand the site → Monitored Logs → Customize. See Custom log paths and the connectors overview.

Fix Application

When a fix is approved in the dashboard:

  • The agent polls for approved fixes on its next loop (about every 30 seconds)
  • Downloads the fix payload with HMAC signature verification
  • Creates a backup before applying
  • Applies the fix using unified diff patches
  • Validates syntax before and after application
  • Supports rollback if fix fails

Queue Management

  • Offline Queue: Stores errors when server is unavailable
  • Automatic Retry: Retries failed submissions
  • Queue Limits: Maximum 1000 entries (oldest-first eviction)
  • Dead Letter Queue: Tracks permanent failures

Backup System

  • Automatic Backups: Created before applying fixes (copies of all existing paths in the patch are written to your PATCHERLY_BACKUP_ROOT directory)
  • Versioned Backups: Timestamped and error ID tagged for restoring historical versions (kept until you delete them)
  • Compression: Gzip compression for storage efficiency
  • Integrity Checks: SHA256 checksum verification

Usage

Basic Error Monitoring

// Credentials are read from ~/.patcherly/credentials.json
const connector = new NodeConnector();

// Monitor a log file
agent.monitorLogs('logs/application.log');

Manual Error Submission

// Submit an error manually
await agent.processError({
    error_type: 'TypeError',
    error_message: 'Cannot read property of undefined',
    // Prefer the full multi-line event in log_line (header + stack).
    log_line: 'TypeError: Cannot read property of undefined\nat Object.processData (app.js:42:15)',
    severity: 'high'
});

Check Connection Status

// Check connection status
const status = await agent.checkConnection();
console.log('Connected:', status.connected);
console.log('Workspace ID:', status.tenant_id);
console.log('Site ID:', status.target_id);

Security

HMAC Signing

Each OAuth token carries its own per-token HMAC signing secret, returned at issuance and stored in ~/.patcherly/credentials.json. The connector uses this secret to sign every request with X-Patcherly-Timestamp + X-Patcherly-Signature:

  • Per-token secret: bound to the OAuth credential - no global shared secret
  • Mandatory verification: HMAC verification is always required for fix payloads
  • No manual configuration: The secret is bundled into the credential file at OAuth issuance

To rotate, run patcherly logout then patcherly login to issue a new token and secret.

OAuth Credential Management

  • Credentials are stored in ~/.patcherly/credentials.json
  • Never commit this file to version control
  • To revoke: patcherly logout (revokes the token server-side)
  • To re-pair: patcherly login

Verify detection end-to-end with patcherly send-test

After pairing, you can prove the whole pipeline (connector → API → dashboard error feed) works without waiting for a real exception. Test events only flow while you've explicitly opened a Test Mode window from your Patcherly dashboard - this gate prevents an exposed connector credential, a curious script, or a CI run from spraying synthetic traffic into your real error feed and triggering notifications. The window is per-site and lasts 30 minutes; you stay in control.

  1. In your Patcherly dashboard, open Sites, click your site, and flip the Test Mode toggle ON: this opens a 30-minute window for this site only.
  2. On the server where you ran patcherly login, run:
    npx patcherly send-test
    
  3. The synthetic event lands in your dashboard under Errors, flagged as a sample so it does not affect your metrics or fire notifications.

The CLI auto-checks the Test Mode window (GET /v1/targets/connector-status) before sending. If the window is closed, it prints a clear "Test error window is not open for this site" message plus the exact dashboard URL where you can enable it - no traffic is sent. Pass --no-preflight to skip that check (used in tests).

Keep the connection alive on quiet hosts (patcherly heartbeat)

Once you've paired with patcherly login, the connection is designed to stay alive without you having to reconnect - even if the host sits idle for weeks. Every time the connector talks to Patcherly (sending an error, fetching a fix, polling status), the connection's credentials are quietly refreshed in the background.

If the host you paired is paired but rarely runs the connector (low-traffic site, weekend job server, etc.), wire a tiny once-a-day heartbeat into cron so the credentials never age out:

0 6 * * *  /usr/local/bin/patcherly heartbeat

That one daily call (a) refreshes your credentials long before they expire, and (b) tells the dashboard your connector is still alive (so the "Connector is healthy" check in the onboarding panel stays green). Exits 0 on success, 2 if the host isn't paired yet, 1 on any HTTP / network failure - so cron will email you only when something is actually wrong.

Post-apply tests (agent testing entitlement)

On plans that include agent testing, after a successful patch the connector may run npm test from your customer app root (PATCHERLY_TARGET_ROOTS / project cwd - never the connector install tree). There is a hard timeout (default 60 seconds, override with PATCHERLY_NPM_TEST_TIMEOUT_MS on the agent host). If scripts.test hangs or never exits, the agent kills the run, reports failure, and the dashboard will not sit on Verifying forever - but the error also will not reach a clean Fixed until tests pass or you adjust the suite. Prefer a short smoke script; do not point scripts.test at an interactive or unbounded suite.

App restart automation

For Node.js site or app types on plans that include app restart automation, the connector can run post-apply shell steps after a successful patch. Use Sites → App restart (On/Off toggle + Configure) for the YAML manifest; pause without deleting it via the toggle. On the server where the agent runs, install the yaml package (for example npm install yaml in the agent’s directory) so the agent can parse the manifest.

  • Guide: App restart automation
  • Command forms: prefer array-form run: ['node', 'scripts/reload.js'] for -e bodies with ;; string-form still applies the denylist. Defaults allowlist includes node / systemctl / pm2 / supervisorctl.
  • Optional environment variables on the agent host (for example PATCHERLY_POST_APPLY_DRY_RUN, PATCHERLY_WORKFLOW_LOCK_WAIT_MS): use only if your connector README or support has you set them.

Troubleshooting

Connection Issues

"Cannot connect to server" - Check network connectivity and firewall (outbound HTTPS to api.patcherly.com) - Verify Patcherly service is running

"Authentication failed" / credentials missing - Check that ~/.patcherly/credentials.json exists on the site server. - If it is missing or expired, re-pair with patcherly login.

"HMAC signature mismatch" - The per-token HMAC secret is in ~/.patcherly/credentials.json; re-pair with patcherly login if the credential file is corrupted - Ensure timestamp is synchronized (check system clock / NTP) - Restart the connector after re-pairing

Error Detection Issues

"No errors detected" - Verify log file path is correct - Check log file has read permissions - Ensure errors are being logged - Check log format matches expected format

"Errors not submitting" - Check queue file for pending errors - Verify network connectivity - Check server logs for errors - Review connector logs

Fix Application Issues

"Fix application failed" - Check backup was created - Verify file permissions - Check syntax validation - Review patch format

"Rollback failed" - Check backup integrity - Verify backup file exists - Check file permissions - Review rollback logs

Best Practices

Credentials

  • Never commit ~/.patcherly/credentials.json or .env files to version control
  • Use separate OAuth pairings for different environments (each patcherly login issues a distinct token)
  • To rotate credentials, run patcherly logout then patcherly login

Error Handling

  • Monitor connector logs regularly
  • Set up alerts for connection failures
  • Review error queue periodically
  • Test fix application in staging first

Performance

  • Use appropriate log file monitoring intervals
  • Configure queue limits appropriately
  • Clean up old backups regularly (delete them manually when you no longer need version history)
  • Monitor disk space usage

API Reference

NodeConnector class

class NodeAgent {
    constructor(options)  // options.logFile only; credentials from ~/.patcherly/credentials.json
    start()
    stop()
    monitorLogs(logFile)
    processError(errorContext)
    checkConnection()
}

Credentials are read from ~/.patcherly/credentials.json (no constructor option for keys).

Methods

  • start(): Start the agent and begin monitoring
  • stop(): Stop monitoring and cleanup
  • monitorLogs(logFile): Monitor a specific log file
  • processError(errorContext): Submit an error manually
  • checkConnection(): Check connection status

Next Steps