Last updated: June 13, 2025

<span aria-hidden="true" id="export-files-to-sftp-in-nodejs-with-ssh2-sftp-client"></span>

# Export files to SFTP in Node.js with ssh2-sftp-client

![Kevin van Zonneveld](/assets/images/teammates/avatar-kvz-4.jpg?dpl=dpl_BnUJZFhrwex1Jq8Abt73kPZ9xPzJ)

#### Kevin van Zonneveld

Co-founder · Amsterdam, The Netherlands · Show bio

[](https://x.com/kvz)[](https://github.com/kvz)

Secure file transfers are crucial for protecting sensitive data. SFTP (Secure File Transfer Protocol) is a reliable method for securely transferring files over a network. In this DevTip, we'll explore how to use Node.js and the open-source library `ssh2-sftp-client` to efficiently handle file transfers to and from an SFTP server. `ssh2-sftp-client` is a convenient, promise-based wrapper around the powerful `ssh2` library, simplifying SFTP operations.

<span aria-hidden="true" id="introduction-to-sftp"></span>

## Introduction to SFTP

SFTP is a secure protocol built on SSH (Secure Shell) that provides encrypted file transfers. It ensures data integrity and confidentiality, making it ideal for transferring sensitive information.

<span aria-hidden="true" id="setting-up-your-nodejs-environment"></span>

## Setting up your Node.js environment

Ensure you have Node.js installed. `ssh2-sftp-client` version 12.x (current stable) supports Node.js versions 20.x and higher. Versions prior to 20.x are not supported. You can verify your installation by running:

```bash
node -v
npm -v

```

<span aria-hidden="true" id="installing-and-configuring-ssh2-sftp-client"></span>

## Installing and configuring ssh2-sftp-client

Install the `ssh2-sftp-client` library using npm:

```bash
npm install ssh2-sftp-client

```

<span aria-hidden="true" id="connecting-uploading-downloading-and-error-handling"></span>

## Connecting, uploading, downloading, and error handling

Here's how you can establish a connection, upload a file, download a file, and handle errors robustly:

```javascript
const Client = require('ssh2-sftp-client')
const fs = require('fs') // Required for the dummy file creation

async function main() {
  const sftp = new Client()
  const config = {
    host: 'your.sftp.server',
    port: 22, // Use an integer for the port
    username: 'your-username',
    password: 'your-password',
    // For testing against a non-existent server, you might add a timeout
    // readyTimeout: 5000 // e.g., 5 seconds
  }

  const localPath = './local-file.txt'
  const remotePath = '/remote/path/file.txt'
  const localDownloadPath = './downloaded-file.txt'

  // Create a dummy file for upload example if it doesn't exist
  if (!fs.existsSync(localPath)) {
    fs.writeFileSync(localPath, 'This is a test file for SFTP upload.')
    console.log(`Created dummy ${localPath} for testing.`)
  }

  try {
    await sftp.connect(config)
    console.log('Connected successfully to SFTP server.')

    // Uploading files
    console.log(`Attempting to upload ${localPath} to ${remotePath}...`)
    await sftp.put(localPath, remotePath)
    console.log('File uploaded successfully.')

    // Downloading files
    console.log(`Attempting to download ${remotePath} to ${localDownloadPath}...`)
    await sftp.get(remotePath, localDownloadPath)
    console.log('File downloaded successfully.')
  } catch (err) {
    console.error('An error occurred:', err.message)
    // More specific error handling can be added here based on err.code or err.level
  } finally {
    try {
      await sftp.end()
      console.log('Connection closed.')
    } catch (err) {
      console.error('Error closing connection:', err.message)
    }
  }
}

main().catch(console.error) // Ensure top-level errors from main are caught

```

In the example above, we've wrapped our SFTP operations within an `async` function called `main`. This function handles connecting to the server, uploading a file, and then downloading it. The`try...finally` block ensures that the SFTP connection is closed using `sftp.end()` regardless of whether the operations were successful or an error occurred. We also create a dummy `local-file.txt`to ensure the upload example can run.

<span aria-hidden="true" id="best-practices-for-secure-and-efficient-file-transfers"></span>

## Best practices for secure and efficient file transfers

* Always use strong authentication methods. For enhanced security, using SSH key-based authentication is highly recommended. The `privateKey` option in the `connect` config can be used for this. Refer to the `ssh2-sftp-client` and `ssh2` documentation for detailed examples.
* Regularly update your libraries and dependencies.
* Validate file paths and permissions.
* Implement logging and monitoring for file transfers.

<span aria-hidden="true" id="conclusion-and-practical-use-cases"></span>

## Conclusion and practical use cases

Using `ssh2-sftp-client` simplifies secure file transfers in Node.js applications. This approach is ideal for automated backups, data synchronization, and secure file exchanges between systems.

For a streamlined solution, consider Transloadit's[🤖 /sftp/store Robot](/docs/robots/sftp-store.md) as part of our File Exporting service.

\#node-js#sftp#ssh2-sftp-client#file-transfer#secure-file-upload#open-source#file-exporting-service

### 👩‍💻 Join 20k+ developers

Sign up for our [monthly newsletter](/newsletters.md) to receive direct links to 3 exclusive tech — and 2 product updates. No less, no more.

Your email:

Get access

## File uploading and encoding. Made simple.

Transloadit streamlines file handling for developers, trusted by brands like Coursera and The New York Times. We’re known for a reliable API, top-notch support, and a strong commitment to open source, with projects like [Uppy⁠](https://uppy.io) and [Tus⁠](https://tus.io) setting standards in file processing.

[Sign up](/c/)[Book a Demo](https://survey.typeform.com/to/kRg47Xi5)

No credit card needed · 5 GB included in the free plan

Cancel anytime
