Nextcloud Node.js Client
The `nextcloud-node-client` is a TypeScript-first library offering a comprehensive API to interact with Nextcloud servers from Node.js applications. Currently at version 1.8.1, it demonstrates an active development cadence with regular minor releases introducing new features like recursive file retrieval, user management, and improved sharing capabilities. The library differentiates itself by providing a rich, simple API that abstracts away the underlying Nextcloud communication protocols, supporting essential operations such as uploading and downloading files, managing folder structures, handling user accounts, creating and managing shares, and applying tags and comments to filesystem elements. A key feature is its flexible credential management, allowing configuration via environment variables (NEXTCLOUD_USERNAME, NEXTCLOUD_PASSWORD, NEXTCLOUD_URL) or Cloud Foundry's `VCAP_SERVICES`, and strongly recommending the use of Nextcloud's app-specific passwords for enhanced security. This client aims to streamline automation tasks for Nextcloud instances.
Common errors
-
ReferenceError: require is not defined
cause Attempting to use `require('nextcloud-node-client')` in an ECMAScript Module (ESM) context (e.g., a file with `"type": "module"` in `package.json` or a `.mjs` file).fixSwitch to ESM import syntax: `import Client, { File } from 'nextcloud-node-client';`. Ensure your project is configured for ESM or use a bundler if targeting older Node.js environments. -
Error: Nextcloud credentials not found (NEXTCLOUD_USERNAME, NEXTCLOUD_PASSWORD, NEXTCLOUD_URL)
cause The `Client` constructor was called without explicit credentials and the required environment variables (NEXTCLOUD_USERNAME, NEXTCLOUD_PASSWORD, NEXTCLOUD_URL) were not set or were misspelled.fixSet the `NEXTCLOUD_USERNAME`, `NEXTCLOUD_PASSWORD`, and `NEXTCLOUD_URL` environment variables before running your application, or pass them directly to the `Client` constructor: `new Client({ url: '...', username: '...', password: '...' })`. -
Error: Forbidden (403)
cause This error often indicates incorrect credentials (username/password), insufficient permissions for the user, or issues with app-specific passwords not being correctly generated or applied. It can also occur if the Nextcloud server's `trusted_domains` configuration does not include the host from which your Node.js application is making requests.fixVerify that `NEXTCLOUD_USERNAME` and `NEXTCLOUD_PASSWORD` (preferably an app-specific password) are correct. Ensure the Nextcloud user has the necessary permissions for the attempted operations. Check your Nextcloud server's `config/config.php` to ensure the `trusted_domains` array includes the domain or IP of your Node.js application.
Warnings
- gotcha When configuring the Nextcloud URL, specify the base URL of your Nextcloud instance (e.g., `https://your.nextcloud.host`). Earlier versions might have implicitly expected or preferred a WebDAV-specific URL, but as of v1.8.0, the client can infer the correct endpoints from a general server URL, simplifying configuration. Ensure your Nextcloud server's WebDAV API is correctly configured.
- gotcha For production environments and enhanced security, it is strongly recommended to use app-specific passwords generated in your Nextcloud user settings instead of your main account password. These passwords offer more granular control and can be revoked independently.
- gotcha The library primarily uses Promises for asynchronous operations. While you can use `.then().catch()`, modern TypeScript/JavaScript code should leverage `async/await` for better readability and error handling. Make sure to wrap your asynchronous code in an `async` function and use `try...catch` blocks.
Install
-
npm install nextcloud-node-client -
yarn add nextcloud-node-client -
pnpm add nextcloud-node-client
Imports
- Client
import { Client } from 'nextcloud-node-client';import Client from 'nextcloud-node-client';
- File, Folder, Tag, Share
import File from 'nextcloud-node-client/File';
import { File, Folder, Tag, Share } from 'nextcloud-node-client'; - * as NextcloudClient
const NextcloudClient = require('nextcloud-node-client');import * as NextcloudClient from 'nextcloud-node-client';
Quickstart
import Client, { File, Folder, Share } from 'nextcloud-node-client';
// Ensure these environment variables are set:
// process.env.NEXTCLOUD_USERNAME
// process.env.NEXTCLOUD_PASSWORD
// process.env.NEXTCLOUD_URL (e.g., 'https://your.nextcloud.host')
(async () => {
try {
// Create a new client. Credentials are automatically picked up from environment variables.
const client = new Client();
// Create a folder structure if it doesn't exist
const folder: Folder = await client.createFolder('my-test-folder/subfolder');
console.log(`Created folder: ${folder.name}`);
// Create a file within the folder
const fileContent = Buffer.from('Hello, Nextcloud from Node.js!');
const file: File = await folder.createFile('hello.txt', fileContent);
console.log(`Created file: ${file.name}`);
// Add a tag to the file (the tag will be created if it doesn't exist)
await file.addTag('nodejs-api-test');
console.log('Added tag to file.');
// Get the content of the created file
const downloadedContent: Buffer = await file.getContent();
console.log(`Downloaded file content: ${downloadedContent.toString()}`);
// Share the file publicly with a password and note
const share: Share = await client.createShare({
fileSystemElement: file,
password: 'my-secure-password',
note: 'Shared via nextcloud-node-client example.'
});
console.log(`File shared publicly. Share link: ${share.url}`);
console.log(`Share password: ${share.password}`);
// Clean up: Delete the folder, which also deletes the file and share within it
await folder.delete();
console.log(`Deleted folder: ${folder.name}`);
} catch (e) {
console.error('An error occurred:', e);
// More robust error handling might include checking error types or messages
if (e instanceof Error) {
console.error(e.message);
}
}
})();