JavaScript SDK: Client Library

Last Updated: Jan 27, 2025
documentation for the dotCMS Content Management System

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:

KeyValue
dotcmsUrlURL 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.
authTokendotCMS API token. For security reasons, we highly recommend passing this value through an environment file variable.
siteIdOptional. The identifier for the dotCMS Site to be accessed. If not specified, falls back to the default site of the instance.
requestOptionsOptional. 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.

MethodArgumentResponse
{client}.page.get(options)PageApiOptions objectA Promise that resolves to a JSON object containing a Page API response.
{client}.nav.get(options)NavApiOptions objectA 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 PropertyValueDescription
pathStringThe path of the page to access.
siteIdStringOptional. The identifier of the Site being accessed. If not provided, it will fall back to the one configured for the client object.
language_idNumberOptional. The Page's numeric language identifier. Defaults to the Site's default language.
personaIdStringOptional. The identifier or the key tag of the persona for which the Page should be retrieved.
fireRulesBooleanOptional. Whether to fire rules on the Page. Defaults to false.
depthNumberOptional. 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 PropertyValueDescription
pathStringThe root path from which to begin traversing the directory tree.
depthNumberOptional. 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_idNumberOptional. 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 MethodTypeResultExplanation
.field('foo')Fieldfoo:{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:}barSupplies a value to a preceding field method. Multiple .equals() calls may be joined through operator methods.
.raw('foo')RawfooAdds raw input as output to the query; requires use of Lucene syntax directly.
.and()OperatorANDJoins two query clauses — whether assignments or field/assignment pairs — such that results will be returned when both halves apply.
.or()OperatorORJoins two query clauses such that results will be returned when at least one half applies.
.not()OperatorNOTUnary operator; query will return only results where the subsequent clause does not apply.
.build()Constructorn/aOutputs 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.

MethodArgumentDescription
limit()IntegerThe maximum number of items to fetch.
page()IntegerIndicates which page number to fetch; used with limit for paginated fetches.
depth()IntegerIndicates 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 ObjectsSorts 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()BooleanSetting this to true will perform a server-side render using Velocity on any widgets that are returned by the content query.
query()QueryAccepts a query generated via the query builder syntax, either as a variable or an inline function, such as in the example above.
rawQuery()StringAccepts a Lucene query as a string.
language()Number or StringThe language ID by which to filter the content.
draft()BooleanAllows retrieval of draft content.
fetch()NoneSends the final parameterized query.

This method can be used with either await or then-style asynchronous calls.

On this page

×

We Dig Feedback

Selected excerpt:

×