The @dotcms/client
library is responsible for interacting directly with dotCMS, securely performing Page API and Navigation API — and, soon, Content API — calls from your front-end web app or a Node.js server.
Installation
Installation can be performed via package manager. Choose any of the following commands:
npm install @dotcms/client
pnpm install @dotcms/client
yarn add @dotcms/client
Initialization and Basic Usage
First, you need to import the dotcmsClient
, which creates a dotCMS client. You can use the ES (or JS) module syntax as follows:
import { dotcmsClient } from '@dotcms/client';
CommonJS syntax is also supported:
const { DotCmsClient } = require('@dotcms/client');
dotcmsClient
exposes an init
method that that takes a configuration object with the following keys:
Key | Value |
---|---|
dotcmsUrl | URL for the dotCMS instance the remote website or application will be calling. For security reasons, we highly recommend passing this value through an environment file variable. |
authToken | dotCMS API token. For security reasons, we highly recommend passing this value through an environment file variable. |
siteId | Optional. The identifier for the dotCMS Site to be accessed. If not specified, falls back to the default site of the instance. |
requestOptions | Optional. An object containing options to pass via the JavaScript Fetch API, used by the library to make its calls to dotCMS. Note that body and method options are not taken into account. |
For example:
import { dotcmsClient } from '@dotcms/client';
const client = dotcmsClient.init({
dotcmsUrl: process.env.NEXT_PUBLIC_DOTCMS_HOST,
authToken: process.env.DOTCMS_AUTH_TOKEN,
siteId: '59bb8831-6706-4589-9ca0-ff74016e02b2',
requestOptions: {
cache: 'no-cache'
}
});
Once initialized, the client contains two properties, page
and nav
— i.e., one for each API. Each property exposes a single asynchronous get
method. Additional methods covering other API endpoints, such as delete
or update
operations, are planned for future releases.
Method | Argument | Response |
---|---|---|
{client}.page.get(options) | PageApiOptions object | A Promise that resolves to a JSON object containing a Page API response. |
{client}.nav.get(options) | NavApiOptions object | A Promise that resolves to a JSON object containing a Navigation API response. |
Each takes a distinctive object as its argument, the full specifications are provided in the following subsections.
client.page.get(opts)
Method
PageApiOptions Property | Value | Description |
---|---|---|
path | String | The path of the page to access. |
siteId | String | Optional. The identifier of the Site being accessed. If not provided, it will fall back to the one configured for the client object. |
language_id | Number | Optional. The Page's numeric language identifier. Defaults to the Site's default language. |
personaId | String | Optional. The identifier or the key tag of the persona for which the Page should be retrieved. |
fireRules | Boolean | Optional. Whether to fire rules on the Page. Defaults to false . |
depth | Number | Optional. Includes related content via Relationship fields, by up to as many steps as the number specified. Defaults to 0 . |
A call to this method might look like this:
const data = await client.page.get({
path: '/blog',
language_id: 1,
personaId: '34b720af-4b46-4a67-9e4b-2117071d01f1'
});
client.nav.get(opts)
Method
NavApiOptions Property | Value | Description |
---|---|---|
path | String | The root path from which to begin traversing the directory tree. |
depth | Number | Optional. Depth of the folder tree to return. A value of 1 (default) returns only the element specified in the path property; 2 includes any children, if the path specifies a folder; and 3 includes all children and grandchildren. |
language_id | Number | Optional. The Page's numeric language identifier. Defaults to the Site's default language. |
An example of a call:
const nav = await client.nav.get({
path: '/',
depth: 2,
languageId: 1
});
Content Queries
The client library offers straightforward ways to perform queries for content within the dotCMS system through JavaScript methods.
Building Queries With the Query Builder Syntax
The client library includes a QueryBuilder
class that allows the construction of content queries in a style more natural to a JavaScript environment, without needing to manually build the Lucene query syntax strings used by the system.
For instance:
const queryForBlogsOrArticles = queryBuilder
.field('contentType')
.equals('Blog')
.or()
.equals('Article')
.build();
The table below outlines its methods:
QueryBuilder Method | Type | Result | Explanation |
---|---|---|---|
.field('foo') | Field | foo:{bar} | Defines a field name to query, awaiting a value to be supplied via the .equals() method. Multiple such assignments can be made if joined together via operator methods such as or() . |
.excludeField('foo') | Field | -foo:{bar} | Defines a field name to exclude from the query, awaiting a value to be supplied via the .equals() method, or several combined through operators. |
.equals('bar') | Assignment | {foo:}bar | Supplies a value to a preceding field method. Multiple .equals() calls may be joined through operator methods. |
.raw('foo') | Raw | foo | Adds raw input as output to the query; requires use of Lucene syntax directly. |
.and() | Operator | AND | Joins two query clauses — whether assignments or field/assignment pairs — such that results will be returned when both halves apply. |
.or() | Operator | OR | Joins two query clauses such that results will be returned when at least one half applies. |
.not() | Operator | NOT | Unary operator; query will return only results where the subsequent clause does not apply. |
.build() | Constructor | n/a | Outputs the final query string. |
The following example displays all of the builder class's methods, generating a complex Lucene query:
let queryBuilder = new QueryBuilder();
const myQuery = queryBuilder
.field('contentType')
.equals('Blog')
.or()
.equals('Activity')
.excludeField('conhost')
.equals('my-super-cool-site')
.field('languageId')
.equals('2') // spanish
.and()
.field('deleted')
.equals('false')
.raw('+summary:Snowboard')
.not()
.equals('Swiss Alps')
.build();
The above myQuery
variable will have the following value:
+contentType:Blog OR Activity -conhost:my-super-cool-site +languageId:2 AND +deleted:false +summary:Snowboard NOT “Swiss Alps”
For additional examples, see the class's specification page on GitHub.
Performing the Query
The getCollection
method allows you to fetch a collection of content items using the queries built in the manner indicated above. Once you have initialized your client
object, the fetch can be performed through the following method:
client.content.getCollection()
The getCollection()
method, in its most basic form, accepts as an argument a string specifying the system name of a content type — e.g.: client.content.getCollection('Blog')
. However, there are also further methods specifying parameters of this fetch operation. A more complex query might be executed as follows:
client.content
.getCollection('Destination')
.sortBy([
{
field: 'modDate',
order: 'desc'
}
])
.limit(3)
.depth(0)
.sortBy([{ field: 'title', order: 'asc' }, { field: 'modDate', order: 'desc' }])
.query((queryBuilder) =>
queryBuilder.field('title').equals('Hello World').or().equals('Hello World 2')
)
.fetch()
.then((response) => {
setDestinations(response.contentlets);
})
.catch((error) => {
console.error(`Error fetching Destinations`, error);
});
Below is a full list of methods that supplement a getCollection()
call.
Method | Argument | Description |
---|---|---|
limit() | Integer | The maximum number of items to fetch. |
page() | Integer | Indicates which page number to fetch; used with limit for paginated fetches. |
depth() | Integer | Indicates how many levels of related content can be pulled as part of this query. (Note that increasing depth increases the computational load of queries significantly.) |
sortBy() | Collection of Objects | Sorts the content by the specified objects, each consisting of the properties field (a field's variable name) and order (asc or desc for ascending or descending). |
render() | Boolean | Setting this to true will perform a server-side render using Velocity on any widgets that are returned by the content query. |
query() | Query | Accepts a query generated via the query builder syntax, either as a variable or an inline function, such as in the example above. |
rawQuery() | String | Accepts a Lucene query as a string. |
language() | Number or String | The language ID by which to filter the content. |
draft() | Boolean | Allows retrieval of draft content. |
fetch() | None | Sends the final parameterized query. |
This method can be used with either await
or then
-style asynchronous calls.