Skip to main content

Connection Lifecycle

The React Native SSH SFTP library manages SSH and SFTP connections through a well-defined lifecycle. Understanding this lifecycle is crucial for proper resource management.

Creating Connections

Connections are created using factory methods on the SSHClient class:
Do not instantiate SSHClient directly using the new keyword. Always use the static factory methods connectWithPassword() or connectWithKey().

SSH vs SFTP Connections

The library maintains separate connection states for SSH and SFTP operations:
  • SSH Connection: Established when you create a client instance
  • SFTP Connection: Established when you first use an SFTP method or explicitly call connectSFTP()

SSH Connection

The SSH connection is automatically established during client creation and allows you to:
  • Execute commands via execute()
  • Start and interact with shell sessions via startShell(), writeToShell()
  • Use as a base for SFTP operations

SFTP Connection

The SFTP connection is established on-demand and allows file transfer operations.

When to Call connectSFTP()

TL;DR: Calling connectSFTP() is optional. All SFTP methods automatically establish the connection if needed.

Automatic Connection

All SFTP methods (sftpLs, sftpDownload, sftpUpload, etc.) automatically call an internal checkSFTP() method that establishes the connection if it’s not already active:

Explicit Connection

You may want to call connectSFTP() explicitly to:
  1. Separate connection from operation: Establish the connection early to reduce latency on first SFTP operation
  2. Handle connection errors separately: Catch connection errors before attempting file operations
  3. Verify SFTP availability: Test if SFTP is available on the server

Method Signature

Disconnecting Properly

Proper disconnection is essential to free up resources and prevent connection leaks.

Disconnect SFTP

Use disconnectSFTP() to close the SFTP connection while keeping the SSH connection active:
On iOS, disconnectSFTP() has limited functionality due to native implementation constraints. The SSH disconnect() method will properly close the SFTP stream on all platforms.
From the source code (sshclient.ts:696-707):

Disconnect SSH

Use disconnect() to close all active connections (shell, SFTP, and SSH):

Best Practices

Connection State Tracking

The library internally tracks connection states for both shell connections and SFTP connections.

Shell Session Management

Shell sessions have their own lifecycle separate from SFTP:
See the API Reference for complete shell documentation.

Connection Errors

Connection methods return Promises that reject on failure:
See Error Handling for comprehensive error handling patterns.
Last modified on March 26, 2026