Client SDKs

JavaScript Client

Updated: December 2, 2024

Client Library for Nuxeo API

Jenkins npm version npm downloads Dependency Status devDependency Status

Browser Support thanks to SauceLabs

The Nuxeo JavaScript Client is a JavaScript client library for the Nuxeo Automation and REST API. The library can work in a browser, or in Node.js, using the same API.

This is an on-going project, supported by Nuxeo.

Nuxeo Platform Dependency

The JS Client is compliant with all Nuxeo versions as of LTS 2015.

Getting Started

Installation

Node.js Applications

After installing Node.js, use npm or yarn to install the nuxeo package:

$ npm install nuxeo

or

$ yarn add nuxeo
Node.js
var Nuxeo = require('nuxeo');
var nuxeo = new Nuxeo({ ... });
Node.js v4 (Argon)

As Node.js v4 is EOL, tests are not launched anymore on it and it's not a supported target. However, the ES5 build should work so if you really need to run on Node.js v4, use the following:

var Nuxeo = require('nuxeo/es5');
var nuxeo = new Nuxeo({ ... });

Bower Powered Applications

The nuxeo client can be also installed through bower:

$ bower install nuxeo --save

When added to your page, Nuxeo is available as a global variable.

var nuxeo = new Nuxeo({ ... });

Angular Applications

After adding nuxeo through Bower, you can easily create a service that will return a client:

...
.service('nuxeo', function() {
  return new Nuxeo({
    baseURL: 'http://localhost:8080/nuxeo/',
    auth: {
      method: 'basic',
      username: 'Administrator',
      password: 'Administrator'
    }
  });
})
...

To notify Angular to update the UI when a Nuxeo promise has resolved, you can either wrap Nuxeo promises in $q.when() or, the preferred way, configure the Promise library class to be $q.

// wrap promises
...
$q.when(nuxeo.request('/path/').get()).then(function(res) {
  $scope.res = res;
});
// use $q as the Promise library class
...
.service('nuxeo', function($q) {
  Nuxeo.promiseLibrary($q);
  return new Nuxeo({
    baseURL: 'http://localhost:8080/nuxeo/',
    auth: {
      method: 'basic',
      username: 'Administrator',
      password: 'Administrator'
    }
  });
})
...

Angular v2 Applications

After adding nuxeo through npm or yarn to your application, you can use the Nuxeo client directly by requiring the nuxeo module:

const Nuxeo = require('nuxeo');
...
const nuxeo = new Nuxeo({...});
...

Nuxeo works correctly with Angular v2 ZoneAwarePromise Promise library, so the component tree will be re-rendered when a Promise from Nuxeo will resolve.

React Applications

After adding nuxeo through npm or yarn to your application, to make it sure that it will work on most browsers you must require nuxeo differently according to your build system.

If your build transpiles external libraries from ES6 to ES5:

var Nuxeo = require('nuxeo');

If your build does not (such as create-react-app):

var Nuxeo = require('nuxeo/es5');

Documentation

Check out the API documentation.

Examples

Some working examples using the Nuxeo JavaScript Client can be found here.

Deprecated APIs

Base#timeout (since 3.6.0)

The timeout method available on the Base class is deprecated in favor of using directly the httpTimeout or transactionTimeout methods depending of what needs to be configured.

Note that the httpTimeout is in milliseconds while the transactionTimeout is in seconds, so guessing the transactionTimeout from a timeout is a bad idea, you better need to be explicit.

Nuxeo#nuxeoVersion (since 3.5.0)

The nuxeoVersion property of a Nuxeo client instance is deprecated in favor of the serverVersion property that allows correct versions comparison.

The Nuxeo.VERSIONS object is also deprecated in favor of the Nuxeo.SERVER_VERSIONS object.

Nuxeo#_http (since 3.3.0)

The "private" _http method is deprecated in favor of the "public" http method.

Nuxeo#login (since 3.0.0)

The login method is deprecated in favor of the connect method.

Quick Start

This quick start guide will show how to do basics operations using the client.

Authentication

The authentication method to be used is defined when creating a client:

var nuxeo = new Nuxeo({
  auth: {
    method: ...,
    ...
  }
});

The client supports different authentication methods matching the ones available on the Nuxeo Platform.

Basic Authentication

The simplest one allowing to authenticate with a username and password.

var nuxeo = new Nuxeo({
  auth: {
    method: 'basic',
    username: 'Administrator',
    password: 'Administrator'
  }
});

Portal Authenticaton

If the Portal Authentication is configured on the Nuxeo Platform, you can authenticate with the portal method.

var nuxeo = new Nuxeo({
  auth: {
    method: 'portal',
    username: 'joe',
    secret: 'shared-secret-from-server'
  }
});

Token Authentication

To authenticate through a token from the Nuxeo Server:

var nuxeo = new Nuxeo({
  auth: {
    method: 'token',
    token: 'a-token'
  }
});

There is a utility method Nuxeo#requestAuthenticationToken to retrieve a token from a Nuxeo Server using the configured authentication method. For instance, a typical flow would be:

var nuxeo = new Nuxeo({
  auth: {
    method: 'basic',
    username: 'Administrator',
    password: 'Administrator'
  }
});

nuxeo.requestAuthenticationToken('My App', deviceUID, deviceName, 'rw')
  .then(function(token) {
    nuxeo = new Nuxeo({
      auth: {
        method: 'token',
        token: token
      }
    });

    // do something with the new `nuxeo` client using token authentication
    // store the token, and next time you need to create a client, use it
  })
  .catch(function(err) {
    throw err;
  });

OAuth 2 Authorization and Bearer Token Authentication

Since Nuxeo Platform 9.2, you can use OAuth 2 authorization through the JS client.

For more information on OAuth 2 server side, see Using OAuth 2.

Assuming you already have an access token, you can configure the client:

var nuxeo = new Nuxeo({
  auth: {
    method: 'bearerToken',
    token: access_token,
    clientId: 'my-app' // optional OAuth2 client ID to refresh the access token
  }
});

The bearertoken method supports the token being a simple string (an access token) or a full token object such as:

{
  "access_token":"H8dXDdEW9U2jJnFDh6lJJ74AHRzCyG4D",
  "token_type":"bearer",
  "expires_in":3600,
  "refresh_token":"Amz8JlyglhGWDmYHMYS5EnTTFUFAwZLiHG4aqQDfkwUNunSMpTTSFUmvprX3WdSF"
}

If the token is a full token object (ie. with a refresh_token key) and a clientId is configured on the auth object, the client will try automatically to refresh the access token if it's expired.

OAuth 2 Flow

A typical OAuth 2 flow with the Nuxeo Platform would be:

Retrieving Authorization Code

Generate a "log in" link to be used in a browser, such as:

http://localhost:8080/nuxeo/oauth2/authorize?client_id=CLIENT_ID&response_type=code&redirect_uri=REDIRECT_URI

The user sees the login page then, after being logged in, the authorization prompt for the application.

If the user grants access, the Nuxeo Platform redirects the user back to the application:

http://localhost:8000/authorize?code=AUTH_CODE

Retrieving Access Token

The client exchanges the authorization code for an access token:

POST http://localhost:8080/nuxeo/oauth2/token
  grant_type=authorization_code
  code=AUTH_CODE
  redirect_uri=REDIRECT_URI
  client_id=CLIENT_ID

The Nuxeo Platform replies with an access token:

{
  "access_token":"H8dXDdEW9U2jJnFDh6lJJ74AHRzCyG4D",
  "token_type":"bearer",
  "expires_in":3600,
  "refresh_token":"Amz8JlyglhGWDmYHMYS5EnTTFUFAwZLiHG4aqQDfkwUNunSMpTTSFUmvprX3WdSF"
}

There are some utility methods on the client to help you with this flow:

Nuxeo.oauth2.getAuthorizationURL(baseURL, clientId[, params])

Returns the OAuth 2 authorization URL for the given baseURL and clientId.

var authorizationURL = Nuxeo.oauth2.getAuthorizationURL('http://localhost:8080/nuxeo', 'my-app', {
  state: 'xyz',
  redirect_uri: 'http://localhost:8000/authorize',
});
console.log(authorizationURL); // http://localhost:8080/nuxeo/oauth2/authorize?client_id=my-app&response_type=code&state=xyz&redirect_uri=http://localhost:8000/authorize

Nuxeo.oauth2.fetchAccessTokenFromAuthorizationCode(baseURL, clientId, code[, params])

Fetches an OAuth 2 access token for the given baseURL, clientId and code.

var code = ...
Nuxeo.oauth2.fetchAccessTokenFromAuthorizationCode('http://localhost:8080/nuxeo', 'my-app', code, {
  redirect_uri: 'http://localhost:8000/authorize',
}).then(function(token) {
  // do something with the access token
  var nuxeo = new Nuxeo({
    auth: {
      method: 'bearerToken',
      token: token
    }
  });
});

Nuxeo.oauth2.fetchAccessTokenFromJWTToken(baseURL, clientId, jwtToken[, params])

Fetches an OAuth 2 access token for the given baseURL, clientId and jwtToken.

var jwtToken = ...
Nuxeo.oauth2.fetchAccessTokenFromJWTToken('http://localhost:8080/nuxeo', 'my-app', jwtToken, {
  redirect_uri: 'http://localhost:8000/authorize',
}).then(function(token) {
  // do something with the access token
  var nuxeo = new Nuxeo({
    auth: {
      method: 'bearerToken',
      token: token
    }
  });
});

Nuxeo.oauth2.refreshAccessToken(baseURL, clientId, refreshToken[, params])

Manually refresh an access token for the given baseURL, clientId and refreshToken.

var refreshToken = ...
Nuxeo.oauth2.refreshAccessToken('http://localhost:8080/nuxeo', 'my-app', refreshToken)
  .then(function(token) {
    console.log(token); // refreshed access token
});

Creating a Client

var nuxeo = new Nuxeo({
  auth: {
    method: 'basic',
    username: 'Administrator',
    password: 'Administrator'
  }
});

To connect to a different Nuxeo Platform Instance, you can use the following:

var nuxeo = new Nuxeo({
  baseURL: 'http://demo.nuxeo.com/nuxeo/',
  auth: {
    method: 'basic',
    username: 'Administrator',
    password: 'Administrator'
  }
});

Promise Based Calls

All API calls made on the server return a Promise object.

nuxeo.operation('Document.GetChildren')
  .input('/')
  .execute()
  .then(function(docs) {
    // work with docs
  })
  .catch(function(error) {
    // something went wrong
    throw error;
  });

When something went wrong, the error is an Error object with a response field containing the whole response.

Connecting to a Nuxeo Server

After creating a Client, you can connect to a Nuxeo Server by using the connect method. This method returns a Promise which is resolved with the connected client.

var nuxeo = new Nuxeo({ ... });
nuxeo.connect()
  .then(function(client){
    // client.connected === true
    // client === nuxeo
    console.log('Connected OK!');
  })
  .catch(function(error) {
    // wrong credentials / auth method / ...
    throw error;
  });

Current User

The connect method fills the user property of the client. user is a full User object.

var nuxeo = new Nuxeo({ ... });
nuxeo.connect()
  .then(function(client){
    // client.user.id === 'Administrator'
    console.log(client.user);
  })
  .catch(function(error) {
    // wrong credentials / auth method / ...
    throw error;
  });

Nuxeo Server version

The connect method fills the serverVersion property of the client.

var nuxeo = new Nuxeo({ ... });
nuxeo.connect()
  .then(function(client){
    console.log(client.serverVersion); // '9.10'
  })
  .catch(function(error) {
    // wrong credentials / auth method / ...
    throw error;
  });

Some constants are available in the Nuxeo object for supported LTS versions:

Nuxeo.SERVER_VERSIONS.LTS_2016; // for '8.10';
Nuxeo.SERVER_VERSIONS.LTS_2017; // for '9.10';

You can use them to easily make different calls according to the target version:

...
if (nuxeo.serverVersion.lt(Nuxeo.SERVER_VERSIONS.LTS_2017)) {
  // do something on versions before LTS 2016
} else {
  // do something else
}
...

See the ServerVersion documentation.

Note that the nuxeoVersion property is deprecated but it is still filled with the Nuxeo Server version.

Operation

Operation object allows you to execute an operation (or operation chain).

See the Operation documentation.

Samples

Call an operation to create a new folder in the Root document

nuxeo.operation('Document.Create')
  .params({
    type: 'Folder',
    name: 'My Folder',
    properties: 'dc:title=My Folder \ndc:description=A Simple Folder'
  })
  .input('/')
  .execute()
  .then(function(doc) {
    console.log('Created ' + doc.title + ' folder');
  })
  .catch(function(error) {
    throw error;
  });

Request

The Request object allows you to call the Nuxeo REST API.

See the Request documentation.

Samples

Fetch the Administrator user

nuxeo.request('user/Administrator')
  .get()
  .then(function(user) {
    console.log(user);
  })
  .catch(function(error) {
    throw error;
  });

Fetch the whole list of Natures

nuxeo.request('directory/nature')
  .get()
  .then(function(data) {
    console.log(JSON.stringify(data.entries, null, 2))
  })
  .catch(function(error) {
    throw error
  });

Repository

The Repository object allows you to work with document.

See the Repository documentation.

Samples

Create a Repository object

var defaultRepository = nuxeo.repository(); // 'default' repository
...
var testRepository = nuxeo.repository('test'); // 'test' repository
...

Fetch the Root document

nuxeo.repository().fetch('/')
  .then(function(doc) {
    console.log(doc);
  })
  .catch(function(error) {
    throw error;
  });

Create a new folder

var newFolder = {
  'entity-type': 'document',
  name: 'a-folder',
  type: 'Folder',
  properties: {
    'dc:title': 'foo'
  }
};
nuxeo.repository()
  .create('/', newFolder)
  .then(function(doc) {
    console.log(doc);
  })
  .catch(function(error) {
    throw error;
  });

Delete a document

nuxeo.repository()
  .delete('/a-folder')
  .then(function(res) {
    // res.status === 204
  });

Document

Repository object returns and works with Document objects. Document objects exposes a simpler API to work with a document.

See the Document documentation.

Samples

Retrieve a Document object

nuxeo.repository()
  .fetch('/')
  .then(function(doc) {
    // doc instanceof Nuxeo.Document === true
  })
  .catch(function(error) {
    throw error;
  });

Set a document property

doc.set({ 'dc:title': 'foo' });

Get a document property

doc.get('dc:title');

Save an updated document

nuxeo.repository()
  .fetch('/')
  .then(function(doc) {
    // doc.title !== 'foo'
    doc.set({ 'dc:title': 'foo' });
    return doc.save();
  })
  .then(function(doc) {
    // doc.title === 'foo'
  })
  .catch(function(error) {
    throw error;
  });

Fetch the main Blob of a document

doc.fetchBlob()
  .then(function(res) {
    // in the browser, use res.blob() to work with the converted PDF
    // in Node.js, use res.body
  });

Convert a document main Blob to PDF

doc.convert({ format: 'pdf' })
  .then(function(res) {
    // in the browser, use res.blob() to work with the converted PDF
    // in Node.js, use res.body
  });

Fetch the 'thumbnail' rendition

doc.fetchRendition('thumbnail')
  .then(function(res) {
    // in the browser, use res.blob() to work with the rendition
    // in Node.js, use res.body
  });

Start a workflow

doc.startWorkflow('SerialDocumentReview')
  .then(function(workflow) {
    // workflow instance of Nuxeo.Workflow
  });

Complete a workflow task

workflow.fetchTasks()
  .then(function(tasks) {
    return tasks[0];
  })
  .then(function(tasks) {
    task.variable('participants', ['user:Administrator'])
      .variable('assignees', ['user:Administrator'])
      .variable('end_date', '2011-10-23T12:00:00.00Z');
    return task.complete('start_review', { comment: 'a comment' });
  })
  .then(function(task) {
    // task.state === 'ended'
  })

BatchUpload

The BatchUpload object allows you to upload blobs to a Nuxeo Platform instance, and use them as operation input or as document property value.

See the BatchUpload documentation.

Samples

Create a Nuxeo.Blob to be uploaded

// on the browser, assuming you have a File object 'file'
var blob = new Nuxeo.Blob({ content: file });
// the name, mimeType and size will be extracted from the file object itself, you can still override them.
...
// on Node.js, assuming you have a Stream 'file'
var blob = new Nuxeo.Blob({ content: file, name: 'foo.txt', mimeType: 'plain/text', size: 10 })

Upload a blob

nuxeo.batchUpload()
  .upload(blob)
  .then(function(res) {
    // res.blob instanceof Nuxeo.BatchBlob
    console.log(res.blob);
  })
  .catch(function(error) {
    throw error;
  });

Attach an uploaded blob to a document

nuxeo.batchUpload()
  .upload(blob)
  .then(function(res) {
    return nuxeo.operation('Blob.AttachOnDocument')
      .param('document', '/a-file')
      .input(res.blob)
      .execute();
  })
  .then(function() {
    return nuxeo.repository().fetch('/a-file', { schemas: ['dublincore', 'file']});
  })
  .then(function(doc) {
    console.log(doc.get('file:content'));
  })
  .catch(function(error) {
    throw error;
  });

Users

The Users object allows you to work with users.

See the Users and User documentation.

Samples

Fetch an user

nuxeo.users()
  .fetch('Administrator')
  .then(function(user) {
    // user.id === 'Administrator'
  });

Create a new user

var newUser = {
  properties: {
    username: 'leela',
    firstName: 'Leela',
    company: 'Futurama',
    email: '[email protected]'
  },
};
nuxeo.users()
  .create(newUser)
  .then(function(user) {
    // user.id === 'leela'
  });

Delete an user

nuxeo.users()
  .delete('leela').then(function(res) {
    // res.status === 204
  });

Groups

The Groups object allows you to work with groups.

See the Groups and Group documentation.

Samples

Fetch a group

nuxeo.groups().fetch('administrators')
  .then(function(group) {
    // group.groupname === 'administrators'
  });

Create a new group

var newGroup = {
  groupname: 'foo',
  grouplabel: 'Foo'
};
nuxeo.groups()
  .create(newGroup)
  .then(function(group) {
    // group.groupname === 'foo';
  });

Delete a group

nuxeo.groups()
  .delete('foo').then(function(res) {
    // res.status === 204
  });

Directory

The Directory object allows you to work with directories.

See the Directory and DirectoryEntry documentation.

Samples

Fetch all entries of a directory

nuxeo.directory('nature')
  .fetchAll()
  .then(function(entries) {
    // entries instance of Array
  });

Fetch a given directory entry

nuxeo.directory('nature')
  .fetch('article')
  .then(function(entry) {
    // entry.directoryName === 'nature'
    // entry.properties.id === 'article'
  });

Create a new directory entry

var newEntry = {
  properties: {
    id: 'foo',
    label: 'Foo'
  },
};
nuxeo.directory('nature')
  .create(newEntry)
  .then(function(entry) {
    // entry.directoryName === 'nature'
    // entry.properties.id === 'foo'
  });

Delete a directory entry

nuxeo.directory('nature')
 .delete('foo')
 .then(function(res) {
   // res.status === 204
 });

Contributing

See our contribution documentation.

Requirements

Setup

Install Node.js and then use yarn to install all the required libraries:

$ git clone https://github.com/nuxeo/nuxeo-js-client
$ cd nuxeo-js-client
$ yarn

Test

A Nuxeo Platform instance needs to be running on http://localhost:8080/nuxeo for the tests to be run.

Tests can be launched on Node.js with:

$ yarn test:node

For testing the browser client (tests are run on Chrome by default):

$ yarn test:browser

To run both Node.js and browser tests:

$ yarn test

Reporting Issues

You can follow the developments in the Nuxeo JS Client project of our JIRA bug tracker: https://jira.nuxeo.com/browse/NXJS.

You can report issues on answers.nuxeo.com.

Big Thanks

Cross-browser Testing Platform and Open Source <3 Provided by Sauce Labs

License

Apache License 2.0 Copyright (c) Nuxeo SA