@dotcms/client 0.0.1-beta.33 → 0.0.1-beta.35

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,405 +1,621 @@
1
- # dotCMS API Client - `@dotcms/client`
1
+ # dotCMS Client SDK
2
2
 
3
- The `@dotcms/client` is a JavaScript/TypeScript library for interacting with a dotCMS instance. It allows you to easily fetch pages, content, and navigation information in JSON format, as well as to make complex queries on content collections.
3
+ The `@dotcms/client` is a powerful JavaScript/TypeScript SDK designed to simplify the integration of dotCMS content into your applications. Whether building dynamic websites or content-driven apps, this SDK offers an intuitive API for seamless and type-safe content retrieval, enabling you to create engaging experiences effortlessly by accessing and displaying content from dotCMS.
4
4
 
5
- > **⚠️ IMPORTANT:** Versions published under the `next` tag (`npm install @dotcms/client@next`) are experimental, in beta, and not code complete. For the current stable and functional version, please use `latest` (`npm install @dotcms/client@latest`). Once we release the stable version, we will provide a migration guide from the alpha to stable version. The current alpha version (under `latest`) will continue to work, allowing you to migrate progressively at your own pace.
5
+ ### When to Use It:
6
6
 
7
- This client library provides a streamlined, promise-based interface to fetch pages and navigation API.
7
+ - Building headless frontends that need dotCMS content
8
+ - Building content-driven apps that need to access dotCMS content
9
+ - Developing multi-language or personalized experiences
10
+ - Implementing dynamic navigation and page structures
11
+
12
+ ### Key Benefits:
13
+
14
+ - **Simplified Development**: Write less code with intuitive methods and builders
15
+ - **Type Safety**: Built-in TypeScript definitions prevent runtime errors
16
+ - **Universal Compatibility**: Works in both browser and Node.js environments
17
+ - **Security First**: Handles authentication and requests securely
18
+ - **Developer Experience**: Rich autocompletion and documentation
8
19
 
9
20
  ## Table of Contents
10
21
 
11
- - [Features](#features)
12
- - [What's New](#whats-new)
13
- - [What's Being Deprecated](#whats-being-deprecated)
14
- - [Installation](#installation)
15
- - [Browser Compatibility](#browser-compatibility)
16
- - [Usage](#usage)
17
- - [ES Modules](#es-modules)
18
- - [CommonJS](#commonjs)
19
- - [Initialization](#initialization)
20
- - [Fetching a Page](#fetching-a-page)
21
- - [Example with all options](#example-with-all-options)
22
- - [Fetching Navigation](#fetching-navigation)
23
- - [Legacy Navigation Example](#legacy-navigation-example)
24
- - [Fetching a Collection of Content](#fetching-a-collection-of-content)
25
- - [Basic Usage](#basic-usage)
26
- - [Sorting Content](#sorting-content)
27
- - [Filtering by Language](#filtering-by-language)
28
- - [Using Complex Queries](#using-complex-queries)
29
- - [Fetching Draft Content](#fetching-draft-content)
30
- - [Setting Depth for Relationships](#setting-depth-for-relationships)
31
- - [Combining Multiple Methods](#combining-multiple-methods)
32
- - [Error Handling Example](#error-handling-example)
33
- - [Pagination](#pagination)
34
- - [API Reference](#api-reference)
35
- - [Contributing](#contributing)
36
- - [Licensing](#licensing)
37
- - [Support](#support)
38
- - [Documentation](#documentation)
39
- - [Getting Help](#getting-help)
40
-
41
- ## Features
42
-
43
- - Easy-to-use methods to interact with [dotCMS pages](https://www.dotcms.com/docs/latest/page-rest-api-layout-as-a-service-laas) and the [Navigation API](https://www.dotcms.com/docs/latest/navigation-rest-api).
44
- - Support for custom actions to communicate with the dotCMS page editor.
45
- - Comprehensive TypeScript typings for better development experience.
46
-
47
- ## What's New
48
-
49
- - **Improved Collection Builder API:** Enhanced content fetching with a fluent builder pattern
50
- - **TypeScript Support:** Comprehensive type definitions for better developer experience
51
- - **Promise-based API:** Modern, async/await compatible interface for all API calls
52
- - **Performance Optimizations:** Faster response times and reduced memory footprint
53
- - **New Client Creation:** The `dotCMSCreateClient()` function replaces `DotCmsClient.init()` for better functional programming
54
-
55
- > **Note:** Some deprecated features are being phased out. See [API Reference](#api-reference) for details.
56
-
57
- ## What's Being Deprecated
58
-
59
- - **Legacy Editor APIs:** The `postMessageToEditor`, `initEditor`, and related functions are being phased out
60
- - **Direct Content API:** The `content.get()` method is being replaced by the more powerful `content.getCollection()`
61
- - **Callback-based APIs:** All callback-based methods are being replaced with Promise-based alternatives
62
- - **DotCmsClient.init:** The static `DotCmsClient.init()` method is replaced by the `dotCMSCreateClient()` function
63
- - **client.editor:** The editor functionality has been completely moved to the `@dotcms/uve` package
64
-
65
- > **Note:** Deprecated items will continue to work for backward compatibility but will be removed in future major versions.
66
-
67
- ## Installation
68
-
69
- To get started, install the client via npm or yarn:
22
+ - [Prerequisites & Setup](#prerequisites--setup)
23
+ - [Get a dotCMS Environment](#get-a-dotcms-environment)
24
+ - [Create a dotCMS API Key](#create-a-dotcms-api-key)
25
+ - [Installation](#installation)
26
+ - [Quickstart](#quickstart)
27
+ - [Example Projects](#example-projects)
28
+ - [Key Concepts](#key-concepts)
29
+ - [Choosing the Right Method](#choosing-the-right-method)
30
+ - [Start with `page.get()`: The One-Request Solution](#start-with-pageget-the-one-request-solution)
31
+ - [API Reference](#api-reference)
32
+ - [Client Initialization](#client-initialization)
33
+ - [client.page.get(): Fetching Page Content](#clientpageget-fetching-page-content)
34
+ - [client.navigation.get(): Fetching Navigation Structure](#clientnavigationget-fetching-navigation-structure)
35
+ - [client.content.getCollection(): Fetching Content Collections](#clientcontentgetcollection-fetching-content-collections)
36
+ - [Using the SDK with TypeScript](#using-the-sdk-with-typescript)
37
+ - [Usage Example](#usage-example)
38
+ - [How to Enable Page Editing in dotCMS](#how-to-enable-page-editing-in-dotcms)
39
+ - [Use an Official SDK](#use-an-official-sdk)
40
+ - [⚠️ Advanced Only: Custom UVE Integration](#advanced-only-custom-uve-integration)
41
+ - [dotCMS Support](#dotcms-support)
42
+ - [How To Contribute](#how-to-contribute)
43
+ - [Licensing Information](#licensing-information)
70
44
 
71
- ```bash
72
- npm install @dotcms/client
73
- ```
45
+ ## Prerequisites & Setup
74
46
 
75
- Or using Yarn:
47
+ ### Get a dotCMS Environment
76
48
 
77
- ```bash
78
- yarn add @dotcms/client
49
+ #### Version Compatibility
79
50
 
51
+ - **Recommended**: dotCMS Evergreen
52
+ - **Minimum**: dotCMS v25.05
53
+ - **Best Experience**: Latest Evergreen release
80
54
 
81
- ## Browser Compatibility
55
+ #### Environment Setup
82
56
 
83
- The @dotcms/client package is compatible with the following browsers:
57
+ **For Production Use:**
84
58
 
85
- | Browser | Minimum Version | TLS Version |
86
- |---------|----------------|-------------|
87
- | Chrome | Latest 2 versions | TLS 1.2+ |
88
- | Edge | Latest 2 versions | TLS 1.2+ |
89
- | Firefox | Latest 2 versions | TLS 1.2+ |
59
+ - ☁️ [Cloud hosting options](https://www.dotcms.com/pricing) - managed solutions with SLA
60
+ - 🛠️ [Self-hosted options](https://dev.dotcms.com/docs/current-releases) - deploy on your infrastructure
90
61
 
91
- ## Usage
62
+ **For Testing & Development:**
92
63
 
93
- `@dotcms/client` supports both ES modules and CommonJS. You can import it using either syntax:
64
+ - 🧑🏻‍💻 [dotCMS demo site](https://demo.dotcms.com/dotAdmin/#/public/login) - perfect for trying out the SDK
65
+ - 📘 [Learn how to use the demo site](https://dev.dotcms.com/docs/demo-site)
66
+ - 📝 Read-only access, ideal for building proof-of-concepts
94
67
 
95
- ### ES Modules
68
+ **For Local Development:**
96
69
 
97
- ```javascript
98
- import { createDotCMSClient } from '@dotcms/client/next';
99
- ```
70
+ - 🐳 [Docker setup guide](https://github.com/dotCMS/core/tree/main/docker/docker-compose-examples/single-node-demo-site)
71
+ - 💻 [Local installation guide](https://dev.dotcms.com/docs/quick-start-guide)
72
+
73
+ ### Create a dotCMS API Key
74
+
75
+ > [!TIP]
76
+ > Make sure your API Token has read-only permissions for Pages, Folders, Assets, and Content. Using a key with minimal permissions follows security best practices.
77
+
78
+ This integration requires an API Key with read-only permissions for security best practices:
100
79
 
101
- ### CommonJS
80
+ 1. Go to the **dotCMS admin panel**.
81
+ 2. Click on **System** > **Users**.
82
+ 3. Select the user you want to create the API Key for.
83
+ 4. Go to **API Access Key** and generate a new key.
102
84
 
103
- ```javascript
104
- const { createDotCMSClient } = require('@dotcms/client/next');
85
+ For detailed instructions, please refer to the [dotCMS API Documentation - Read-only token](https://dev.dotcms.com/docs/rest-api-authentication#ReadOnlyToken).
86
+
87
+ ### Installation
88
+
89
+ Install the SDK and required dependencies:
90
+
91
+ ```bash
92
+ npm install @dotcms/client@next @dotcms/types@next
105
93
  ```
106
94
 
107
- ### Initialization
95
+ > [!TIP]
96
+ > If you are working with pure JavaScript, you can avoid installing the `@dotcms/types` package.
97
+
98
+ ## Quickstart: Basic Setup Example
108
99
 
109
- First, initialize the client with your dotCMS instance details.
100
+ Here's a basic setup of the dotCMS Client SDK to help you get started:
110
101
 
111
- ```javascript
102
+ ```typescript
103
+ import { createDotCMSClient } from '@dotcms/client/next';
104
+
105
+ // Create a client instance
112
106
  const client = createDotCMSClient({
113
107
  dotcmsUrl: 'https://your-dotcms-instance.com',
114
- authToken: 'your-auth-token',
115
- siteId: 'your-site-id'
108
+ authToken: 'your-auth-token', // Optional for public content
109
+ siteId: 'your-site-id' // Optional site identifier
116
110
  });
111
+
112
+ // Start using the client!
113
+ const { pageAsset } = await client.page.get('/about-us');
114
+ console.log(pageAsset.page.title);
117
115
  ```
118
116
 
119
- ### Fetching a Page
117
+ ### Full-Stack Example Projects Using the SDK
120
118
 
121
- You can retrieve the elements of any page in your dotCMS system in JSON format using the `client.page.get()` method.
119
+ While there isn't a dedicated example project specifically for the client SDK, you can see it in action within these full-stack examples:
122
120
 
123
- ```javascript
124
- const pageData = await client.page.get('/your-page-path', {
125
- languageId: '1',
126
- personaId: 'optional-persona-id'
121
+ - [Next.js Example](https://github.com/dotCMS/core/tree/main/examples/nextjs) - Modern React-based SSR implementation
122
+ - [Angular Example](https://github.com/dotCMS/core/tree/main/examples/angular) - Enterprise Angular implementation
123
+ - [Astro Example](https://github.com/dotCMS/core/tree/main/examples/astro) - Astro implementation
124
+
125
+ These examples demonstrate how to use the client SDK as part of a complete web application.
126
+
127
+ ## Key Concepts
128
+
129
+ | Term | Description | Documentation |
130
+ | ------------ | ----------------------------------------------------- | ------------------------------------------------------------------------------ |
131
+ | `pageAsset` | The page data structure containing layout and content | [Page API](https://dev.dotcms.com/docs/page-rest-api-layout-as-a-service-laas) |
132
+ | `contentlet` | A single piece of content in dotCMS | [Content API](https://dev.dotcms.com/docs/content) |
133
+ | `collection` | A group of contentlets of the same type | [Content API](https://dev.dotcms.com/docs/search) |
134
+ | `graphql` | Query language used to extend API responses | [GraphQL](https://dev.dotcms.com/docs/graphql) |
135
+
136
+ ## Choosing the Right Method
137
+
138
+ The dotCMS Client SDK provides three core methods for fetching data. Use this quick guide to decide which one is best for your use case:
139
+
140
+ | Method | Use When You Need... | Best For |
141
+ | -------------------------------------------------------------------------------------------- | ------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
142
+ | [`client.page.get()`](#clientpageget-fetching-page-content) | A full page with layout, containers, and related content | **Rendering entire pages** with a single request. Ideal for headless setups, SSR/SSG frameworks, and cases where you want everything—page structure, content, and navigation—tied to a URL path. |
143
+ | [`client.content.getCollection()`](#clientcontentgetcollection-fetching-content-collections) | A filtered list of content items from a specific content type | Populating dynamic blocks, lists, search results, widgets, or reusable components. |
144
+ | [`client.navigation.get()`](#clientnavigationget-fetching-navigation-structure) | Only the site's navigation structure (folders and links) | Standalone menus or use cases where navigation is needed outside of page context. |
145
+
146
+ ### Start with `page.get()`: The One-Request Solution
147
+
148
+ For most use cases, `client.page.get()` is all you need. It lets you retrieve:
149
+
150
+ - The full page layout
151
+ - Related content
152
+ - Navigation structure
153
+
154
+ All in a single request using GraphQL.
155
+
156
+ Only use `content.getCollection()` or `navigation.get()` if you have advanced needs, like real-time data fetching or building custom dynamic components.
157
+
158
+ > 🔍 **For an example of how to bundle content and navigation in one `page.get()` call,** see the [advanced usage](#fetching-additional-content-with-graphql) section under `client.page.get()`.
159
+
160
+ ## API Reference
161
+
162
+ ### createDotCMSClient: Client Initialization
163
+
164
+ The `createDotCMSClient` function is the first step in using the dotCMS Client SDK. It allows you to create a new client instance with your dotCMS configuration.
165
+
166
+ | Option | Type | Required | Description |
167
+ | ---------------- | -------------- | -------- | ------------------------------------------------------------- |
168
+ | `dotcmsUrl` | string | ✅ | Your dotCMS instance URL |
169
+ | `authToken` | string | ✅ | Authentication token |
170
+ | `siteId` | string | ❌ | Site identifier (falls back to default site if not specified) |
171
+ | `requestOptions` | RequestOptions | ❌ | Additional fetch options |
172
+
173
+ #### Initialization Example
174
+
175
+ ```typescript
176
+ import { createDotCMSClient } from '@dotcms/client/next';
177
+
178
+ const client = createDotCMSClient({
179
+ dotcmsUrl: 'https://your-dotcms-instance.com',
180
+ authToken: 'your-auth-token',
181
+ siteId: 'your-site-id',
182
+ requestOptions: {
183
+ headers: { 'Custom-Header': 'value' },
184
+ cache: 'default'
185
+ }
127
186
  });
128
187
  ```
129
188
 
189
+ ### client.page.get(): Fetching Page Content
190
+
191
+ The `client.page.get()` method is your primary way to retrieve page content from dotCMS using the SDK. It abstracts away the complexity of raw REST or GraphQL calls, letting you fetch structured page data with just a single method.
130
192
 
131
- ### Warning
193
+ #### Why Use `page.get()`?
132
194
 
133
- If you are updating from a version that is lower than `0.0.1-beta.29`, be aware that the response from the `client.page.get` method changed the access to the page value from `page` to `pageAsset`.
134
- This change was made to avoid redundancy on access inside of `page` object.
195
+ - Fetch everything needed to render a page with one call
196
+ - Avoid building multiple API queries manually
197
+ - Type-safe, customizable, and extensible with GraphQL
198
+ - Works with dotCMS content localization and personalization out of the box
135
199
 
136
- #### Before
200
+ #### Basic Usage
137
201
 
138
- ```javascript
139
- const { page } = await client.page.get("/")
202
+ Here's the simplest way to fetch a page by its URL:
203
+
204
+ ```ts
205
+ const { pageAsset } = await client.page.get('/about-us');
206
+ console.log(pageAsset.page.title);
140
207
  ```
141
208
 
142
- #### After
209
+ You can now render this content or pass it to your components.
210
+
211
+ #### Customizing the Request
143
212
 
144
- ```javascript
145
- const { pageAsset } = await client.page.get("/")
213
+ You can customize the request to fetch different languages, rendering modes, or user personas:
214
+
215
+ ```ts
216
+ const { pageAsset } = await client.page.get('/about-us', {
217
+ languageId: '2',
218
+ fireRules: true,
219
+ personaId: '1234'
220
+ });
146
221
  ```
147
222
 
223
+ #### Bundling Content and Navigation in One Request
148
224
 
149
- #### Example with all options
225
+ You can also pull in related content, like blog posts or navigation menus, using the `graphql` option:
150
226
 
151
- ```javascript
152
- // Fetching a page with all available options
227
+ ```ts
153
228
  const { pageAsset, content } = await client.page.get('/about-us', {
154
- languageId: '1', // Language ID (optional)
155
- siteId: 'demo.dotcms.com', // Site ID (optional, defaults to the one provided during initialization)
156
- mode: 'PREVIEW_MODE', // ADMIN_MODE, PREVIEW_MODE, or LIVE_MODE (optional)
157
- personaId: '123', // Persona ID for personalization (optional)
158
- device: 'smartphone', // Device for responsive rendering (optional)
159
- graphql: { // Extend page and/or content response (optional)
229
+ graphql: {
160
230
  page: `
161
- containers {
162
- containerContentlets {
163
- uuid
164
- contentlets {
165
- title
166
- }
167
- }
231
+ title
232
+ vanityUrl {
233
+ url
168
234
  }
169
235
  `,
170
236
  content: {
171
237
  blogPosts: `
172
- search(query: "+contentType:Blog", limit: 3) {
238
+ BlogCollection(limit: 3) {
173
239
  title
174
- identifier
175
- ...blogFragment
240
+ urlTitle
176
241
  }
177
242
  `,
178
- },
179
- fragments: [
180
- `
181
- fragment blogFragment on Blog {
182
- urlTitle
183
- blogContent {
184
- json
243
+ navigation: `
244
+ DotNavigation(uri: "/", depth: 2) {
245
+ href
246
+ title
247
+ children {
248
+ href
249
+ title
185
250
  }
186
251
  }
187
-
188
252
  `
189
- ]
253
+ }
190
254
  }
191
255
  });
256
+ ```
257
+
258
+ #### Request Options
192
259
 
193
- // Access page data
194
- console.log(pageAsset.containers);
260
+ The `page.get()` method accepts an optional second argument of type [`DotCMSPageRequestParams`](https://github.com/dotCMS/core/blob/6e003eb697554ea9636a1fec59bc0fa020b84390/core-web/libs/sdk/types/src/lib/client/public.ts#L5-L54). This lets you customize how the page is fetched. Common options include:
195
261
 
196
- // Access content data
197
- console.log(content.blogPosts);
262
+ | Option | Type | Description |
263
+ | ------------ | ---------------- | ------------------------------------------------ |
264
+ | `languageId` | string \| number | Language version of the page |
265
+ | `mode` | string | Rendering mode: `LIVE`, `PREVIEW_MODE`, etc. |
266
+ | `personaId` | string | Personalize content based on persona ID |
267
+ | `graphql` | object | Extend the response with additional content/data |
268
+ | `fireRules` | boolean | Whether to trigger page rules |
269
+
270
+ > 💡 See [`DotCMSPageRequestParams`](https://github.com/dotCMS/core/blob/6e003eb697554ea9636a1fec59bc0fa020b84390/core-web/libs/sdk/types/src/lib/client/public.ts#L5-L54) for a full list of supported options.
271
+
272
+ #### Method Signature
273
+
274
+ ```ts
275
+ get<T extends DotCMSExtendedPageResponse = DotCMSPageResponse>(
276
+ url: string,
277
+ options?: DotCMSPageRequestParams
278
+ ): Promise<DotCMSComposedPageResponse<T>>;
198
279
  ```
199
280
 
200
- ### Fetching Navigation
281
+ ### client.navigation.get(): Fetching Navigation Structure
201
282
 
202
- The new API allows you to fetch navigation data using GraphQL through the page.get method:
283
+ The `client.navigation.get()` method fetches a structured view of a site's file and folder hierarchy from dotCMS. It's useful for building menus and navigation UIs.
203
284
 
204
- ```javascript
205
- // Fetch navigation using the page.get method with GraphQL
206
- const { content } = await client.page.get('/', {
207
- languageId: '1',
208
- graphql: {
209
- content: {
210
- nav: `
211
- query {
212
- nav {
213
- identifier
214
- path
215
- label
216
- children {
217
- identifier
218
- path
219
- label
220
- }
221
- }
222
- }
223
- `
224
- }
225
- }
226
- });
285
+ #### Basic Usage
227
286
 
228
- // Access navigation data
229
- console.log(content.nav);
287
+ Here's the simplest way to fetch the root-level navigation:
288
+
289
+ ```ts
290
+ const nav = await client.navigation.get('/');
291
+ console.log(nav);
230
292
  ```
231
293
 
232
- > **Note:** The legacy `client.nav.get()` method is still available but deprecated.
294
+ #### Customizing the Request
233
295
 
234
- #### Legacy Navigation Example
296
+ You can tailor the navigation structure using optional parameters:
235
297
 
236
- ```javascript
237
- // Legacy approach - still works but is deprecated
238
- const navData = await client.nav.get({
239
- path: '/',
298
+ ```ts
299
+ const nav = await client.navigation.get('/', {
240
300
  depth: 2,
241
301
  languageId: 1
242
302
  });
243
303
  ```
244
304
 
245
- ### Fetching a Collection of Content
305
+ #### Request Options
246
306
 
247
- The `getCollection` method allows you to fetch a collection of content items (sometimes called "contentlets") using a builder pattern for complex queries.
307
+ The `navigation.get()` method accepts an optional second argument with the following parameters:
248
308
 
249
- #### Basic Usage
309
+ | Option | Type | Description |
310
+ | ------------ | ------ | ------------------------------------------ |
311
+ | `depth` | number | Number of child levels to include |
312
+ | `languageId` | number | Language ID for localized navigation names |
250
313
 
251
- Here's a simple example to fetch content from a collection:
314
+ > 💡 For typical use cases, setting `depth: 2` will include top-level navigation and one level of children.
252
315
 
253
- ```typescript
254
- import { dotCMSCreateClient } from '@dotcms/client';
316
+ #### Method Signature
255
317
 
256
- const client = dotCMSCreateClient({
257
- dotcmsUrl: 'https://your-dotcms-instance.com',
258
- authToken: 'your-auth-token'
259
- });
318
+ ```ts
319
+ get(
320
+ uri: string,
321
+ options?: {
322
+ depth?: number;
323
+ languageId?: number;
324
+ }
325
+ ): Promise<DotCMSNavigationItem[]>;
326
+ ```
260
327
 
261
- const collectionResponse = await client.content
262
- .getCollection('Blog') // Collection name
263
- .limit(10) // Limit results to 10 items
264
- .page(1) // Fetch the first page
265
- .fetch(); // Execute the query
328
+ #### Why Use `navigation.get()`?
266
329
 
267
- console.log(collectionResponse.contentlets);
268
- ```
330
+ - Build dynamic menus and site trees with minimal configuration
331
+ - Avoid manual parsing or custom REST calls
332
+ - Support localized navigation out of the box
333
+ - Easily control navigation depth for responsive and nested UIs
269
334
 
270
- #### Sorting Content
335
+ ### client.content.getCollection(): Fetching Content Collections
271
336
 
272
- You can sort the content by any field in ascending or descending order:
337
+ The `client.content.getCollection()` method allows you to query and retrieve a collection of content items of a specific type from dotCMS. It uses a builder pattern so you can fluently compose queries with filters, pagination, sorting, and more.
273
338
 
274
- ```typescript
275
- const sortedResponse = await client.content
276
- .getCollection('Blog')
277
- .sortBy([{ field: 'title', order: 'asc' }]) // Sort by title in ascending order
278
- .fetch();
279
- ```
339
+ #### Why Use `getCollection()`?
280
340
 
281
- #### Filtering by Language
341
+ - Query exactly the content you need
342
+ - Chain filters, sorting, and pagination cleanly
343
+ - Works great for lists, search results, or dynamic components
344
+ - Fully type-safe when used with TypeScript interfaces
282
345
 
283
- If you need to filter content by language, you can specify the `language` parameter:
346
+ #### Basic Usage
284
347
 
285
- ```typescript
286
- const languageFilteredResponse = await client.content
287
- .getCollection('Blog')
288
- .language(2) // Filter by language ID (e.g., 2)
289
- .fetch();
348
+ Here's how to fetch the first 10 items from the "Blog" content type:
349
+
350
+ ```ts
351
+ const blogs = await client.content.getCollection('Blog').limit(10).page(1);
290
352
  ```
291
353
 
292
- #### Using Complex Queries
354
+ #### Filtering and Querying Content
293
355
 
294
- You can build more complex queries using the query builder. For example, filter by `author` and `title`:
356
+ You can apply query filters using a fluent builder pattern:
295
357
 
296
- ```typescript
297
- const complexQueryResponse = await client.content
358
+ ```ts
359
+ const filtered = await client.content
298
360
  .getCollection('Blog')
299
- .query((qb) => qb.field('author').equals('John Doe').and().field('title').equals('Hello World'))
300
- .fetch();
361
+ .query((qb) => qb.field('title').equals('dotCMS*'))
362
+ .limit(5)
363
+ .sortBy([{ field: 'publishDate', direction: 'desc' }]);
301
364
  ```
302
365
 
303
- #### Fetching Draft Content
366
+ #### Search and Paginate Product Results by Title and Price
304
367
 
305
- To only fetch draft content, use the `draft()` method:
368
+ ```ts
369
+ const searchResults = await client.content
370
+ .getCollection('Product')
371
+ .query((qb) => qb.field('title').equals('Book*'))
372
+ .sortBy([{ field: 'price', order: 'asc' }])
373
+ .limit(10)
374
+ .page(2);
306
375
 
307
- ```typescript
308
- const draftContentResponse = await client.content
309
- .getCollection('Blog')
310
- .draft() // Fetch only drafts content
311
- .fetch();
376
+ console.log(searchResults);
312
377
  ```
313
378
 
314
- #### Setting Depth for Relationships
379
+ #### Localized Query with Conditional Status Filtering
315
380
 
316
- To fetch content with a specific relationship depth, use the `depth()` method:
381
+ ```ts
382
+ const events = await client.content
383
+ .getCollection('Event')
384
+ .query((qb) => qb.field('status').equals('Live').or().equals('Scheduled').build())
385
+ .language(2) // e.g., French
386
+ .limit(5);
317
387
 
318
- ```typescript
319
- const depthResponse = await client.content
320
- .getCollection('Blog')
321
- .depth(2) // Fetch related content up to depth 2
322
- .fetch();
388
+ console.log(events);
323
389
  ```
324
390
 
325
- #### Combining Multiple Methods
391
+ #### Raw Search + Sorting + Pagination
326
392
 
327
- You can combine multiple methods to build more complex queries. For example, limit results, sort them, and filter by author:
393
+ ```ts
394
+ const images = await client.content
395
+ .getCollection('Image')
396
+ .query('+title:vacation*')
397
+ .sortBy([{ field: 'publishDate', order: 'desc' }])
398
+ .limit(10)
399
+ .page(1);
328
400
 
329
- ```typescript
330
- const combinedResponse = await client.content
331
- .getCollection('Blog')
332
- .limit(5)
333
- .page(2)
334
- .sortBy([{ field: 'title', order: 'asc' }])
335
- .query((qb) => qb.field('author').equals('John Doe'))
336
- .depth(1)
337
- .fetch();
401
+ console.log(images);
402
+ ```
403
+
404
+ #### Available Builder Methods
405
+
406
+ The builder returned by `getCollection()` supports the following methods:
407
+
408
+ | Method | Arguments | Description |
409
+ | ------------ | ----------------------------- | ------------------------------------------------------------------------- |
410
+ | `query()` | `string` \| `BuildQuery` | Filter content using query builder or raw query |
411
+ | `limit()` | `number` | Set number of items to return |
412
+ | `page()` | `number` | Set which page of results to fetch |
413
+ | `sortBy()` | `SortBy[]` | Sort by one or more fields |
414
+ | `render()` | None | Enable server-side rendering of widgets |
415
+ | `draft()` | None | Retrieve draft content |
416
+ | `variant()` | `string` | Filter content by variant ID |
417
+ | `depth()` | `number` | Set depth of related content |
418
+ | `language()` | `number \| string` | Set content language |
419
+ | `then()` | `OnFullfilled<T>, OnRejected` | Handle promise fulfillment or rejection. Not needed if using async/await. |
420
+
421
+ #### Method Signature
422
+
423
+ ```ts
424
+ getCollection<T = DotCMSBasicContentlet>(
425
+ contentType: string
426
+ ): CollectionBuilder<T>;
338
427
  ```
339
428
 
340
- ## Error Handling Example
429
+ ## Using the SDK with TypeScript
430
+
431
+ As mentioned earlier, dotCMS provides a rich set of types provided by the `@dotcms/types@next` package. These types can be leveraged to ensure proper typing for your page and content data, enhancing type safety and developer experience.
432
+
433
+ ### Defining Page Response Types
341
434
 
342
- To handle errors gracefully, you can use a `try-catch` block around your API calls. Here's an example:
435
+ You can use these types to define interfaces for your content and page structures, ensuring that your application benefits from TypeScript's type-checking capabilities:
343
436
 
344
437
  ```typescript
345
- try {
346
- const pageData = await client.page.get({
347
- path: '/your-page-path',
348
- languageId: 1
349
- });
350
- } catch (error) {
351
- console.error('Failed to fetch page data:', error);
438
+ // Import the base DotCMS types
439
+ import { DotCMSPageAsset, DotCMSBasicContentlet } from '@dotcms/types';
440
+
441
+ // Define the page structure by extending the base DotCMSPageAsset
442
+ interface AboutUsPage extends DotCMSPageAsset {
443
+ vanityUrl: {
444
+ url: string;
445
+ };
352
446
  }
447
+
448
+ // Define interfaces for your content types
449
+ interface BlogPost extends DotCMSBasicContentlet {
450
+ title: string;
451
+ identifier: string;
452
+ urlTitle: string;
453
+ blogContent: {
454
+ json: string;
455
+ };
456
+ }
457
+
458
+ interface TeamMember {
459
+ name: string;
460
+ position: string;
461
+ bio?: string;
462
+ }
463
+
464
+ // Define the content response structure
465
+ interface AboutUsContent {
466
+ blogPosts: BlogPost[];
467
+ teamMembers: TeamMember[];
468
+ }
469
+
470
+ // Use the type parameters to get fully typed responses
471
+ const response = await client.page.get<{ pageAsset: AboutUsPage; content: AboutUsContent }>(
472
+ '/about-us',
473
+ {
474
+ languageId: '1',
475
+ fireRules: true,
476
+ graphql: {
477
+ page: `
478
+ title
479
+ pageId
480
+ vanityUrl {
481
+ url
482
+ }
483
+ `,
484
+ content: {
485
+ blogPosts: `
486
+ BlogCollection(limit: 3) {
487
+ title
488
+ identifier
489
+ ...blogFragment
490
+ }
491
+ `,
492
+ teamMembers: `
493
+ TeamMemberCollection(limit: 5) {
494
+ name
495
+ position
496
+ bio
497
+ }
498
+ `
499
+ },
500
+ fragments: [
501
+ `
502
+ fragment blogFragment on Blog {
503
+ urlTitle
504
+ blogContent {
505
+ json
506
+ }
507
+ }
508
+ `
509
+ ]
510
+ }
511
+ }
512
+ );
513
+
514
+ const { pageAsset, content } = response;
515
+
516
+ // Now you get full TypeScript support
517
+ console.log(pageAsset.vanityUrl.url); // TypeScript knows this exists
518
+ console.log(content.blogPosts[0].title); // TypeScript knows this exists
519
+ console.log(content.teamMembers[0].position); // TypeScript knows this exists
353
520
  ```
354
521
 
355
- This ensures that any errors that occur during the fetch (e.g., network issues, invalid paths, etc.) are caught and logged properly.
522
+ ### Defining Content Response Types
356
523
 
357
- ## Pagination
524
+ You can define interfaces for your content types to get full type safety:
358
525
 
359
- When fetching large collections of content, pagination is key to managing the number of results returned:
526
+ ```ts
527
+ import { DotCMSBasicContentlet } from '@dotcms/types';
360
528
 
361
- ```typescript
362
- const paginatedResponse = await client.content
363
- .getCollection('Blog')
364
- .limit(10) // Limit to 10 items per page
365
- .page(2) // Get the second page of results
366
- .fetch();
529
+ interface BlogPost extends DotCMSBasicContentlet {
530
+ title: string;
531
+ publishDate: string;
532
+ author: string;
533
+ blogContent: {
534
+ json: string;
535
+ };
536
+ urlTitle: string;
537
+ tags: string[];
538
+ }
539
+
540
+ const response = await client.content.getCollection<BlogPost>('Blog');
541
+
542
+ response.contentlets.forEach((post) => {
543
+ console.log(post.title); // Type-safe access
544
+ console.log(post.author);
545
+ console.log(post.tags.join(', '));
546
+ });
367
547
  ```
368
548
 
369
- ## API Reference
549
+ ## How to Enable Page Editing in dotCMS
550
+
551
+ By default, the `@dotcms/client` SDK is **read-only**. It's designed to fetch content from dotCMS—pages, navigation, and collections—but it doesn't make pages editable in the dotCMS backend.
552
+
553
+ To make your pages editable using the dotCMS **Universal Visual Editor (UVE)**, you'll need to pair this SDK with one of our supported front-end integrations.
554
+
555
+ ### Use an Official SDK:
556
+
557
+ If you're using a modern JavaScript framework like React or Angular, we strongly recommend starting with one of our official UVE integrations. These pair the `@dotcms/client` SDK with framework-specific tooling for the Universal Visual Editor:
558
+
559
+ * 🧩 **React SDK**: [`@dotcms/react`](https://github.com/dotCMS/core/tree/main/core-web/libs/sdk/react)
560
+ * 🧩 **Angular SDK**: [`@dotcms/angular`](https://github.com/dotCMS/core/tree/main/core-web/libs/sdk/angular)
561
+
562
+ You can also see them in action within our full-stack examples:
563
+
564
+ * [Next.js Example](https://github.com/dotCMS/core/tree/main/examples/nextjs)
565
+ * [Angular Example](https://github.com/dotCMS/core/tree/main/examples/angular)
566
+ * [Astro Example](https://github.com/dotCMS/core/tree/main/examples/astro)
567
+
568
+ These integrations come pre-wired with everything you need to:
569
+
570
+ * Enable editable pages inside dotCMS using the UVE
571
+ * Render layouts and content containers
572
+ * Fetch page and content data using `@dotcms/client`
573
+
574
+ ### ⚠️ Advanced Only: Custom UVE Integration
575
+
576
+ If you’re building with a framework we don’t yet support, you can build your own UVE integration using the low-level [`@dotcms/uve`](https://github.com/dotCMS/core/tree/main/core-web/libs/sdk/uve) package.
577
+
578
+ > **This is not a recommended path.**
579
+ >
580
+ > Custom UVE implementations are complex, require a deep understanding of dotCMS internals, and are not actively supported.
581
+ >
582
+ > This route is intended only for advanced use cases, such as wiring up layout rendering, editable regions, and UVE behavior manually.
583
+
584
+ That said, if you’re experienced and want to explore it, you can [review the `@dotcms/uve` source and docs here](https://github.com/dotCMS/core/tree/main/core-web/libs/sdk/uve).
585
+
586
+ ## dotCMS Support
587
+
588
+ We offer multiple channels to get help with the dotCMS Client SDK:
370
589
 
371
- Detailed documentation of the `@dotcms/client` methods, parameters, and types can be found below:
590
+ - **GitHub Issues**: For bug reports and feature requests, please [open an issue](https://github.com/dotCMS/core/issues/new/choose) in the GitHub repository.
591
+ - **Community Forum**: Join our [community discussions](https://community.dotcms.com/) to ask questions and share solutions.
592
+ - **Stack Overflow**: Use the tag `dotcms-client` when posting questions.
372
593
 
373
- | Method | Description | Parameters | Returns |
374
- |--------|-------------|------------|---------|
375
- | `dotCMSCreateClient(config)` | Initializes the dotCMS client | `config: DotCMSClientConfig` | `DotCMSClient` |
376
- | `client.page.get(path, options)` | Retrieves page elements | `path: string, options: PageApiOptions` | `Promise<{page: any, content: any}>` |
377
- | `client.nav.get(options)` | Retrieves navigation structure | `options: NavApiOptions` | `Promise<unknown>` |
378
- | `client.content.getCollection(contentType)` | Builds a query for content | `contentType: string` | `CollectionBuilder<T>` |
594
+ When reporting issues, please include:
379
595
 
380
- ## Contributing
596
+ - SDK version you're using
597
+ - dotCMS version
598
+ - Minimal reproduction steps
599
+ - Expected vs. actual behavior
381
600
 
382
- GitHub pull requests are the preferred method to contribute code to dotCMS. Before any pull requests can be accepted, an automated tool will ask you to agree to the [dotCMS Contributor's Agreement](https://gist.github.com/wezell/85ef45298c48494b90d92755b583acb3).
601
+ Enterprise customers can access premium support through the [dotCMS Support Portal](https://dev.dotcms.com/docs/help).
383
602
 
384
- ## Licensing
603
+ ## How To Contribute
385
604
 
386
- dotCMS comes in multiple editions and as such is dual licensed. The dotCMS Community Edition is licensed under the GPL 3.0 and is freely available for download, customization and deployment for use within organizations of all stripes. dotCMS Enterprise Editions (EE) adds a number of enterprise features and is available via a supported, indemnified commercial license from dotCMS. For the differences between the editions, see [the feature page](http://dotcms.com/cms-platform/features).
605
+ GitHub pull requests are the preferred method to contribute code to dotCMS. We welcome contributions to the DotCMS UVE SDK! If you'd like to contribute, please follow these steps:
387
606
 
388
- ## Support
607
+ 1. Fork the repository [dotCMS/core](https://github.com/dotCMS/core)
608
+ 2. Create a feature branch (`git checkout -b feature/amazing-feature`)
609
+ 3. Commit your changes (`git commit -m 'Add some amazing feature'`)
610
+ 4. Push to the branch (`git push origin feature/amazing-feature`)
611
+ 5. Open a Pull Request
389
612
 
390
- If you need help or have any questions, please [open an issue](https://github.com/dotCMS/core/issues/new/choose) in the GitHub repository.
613
+ Please ensure your code follows the existing style and includes appropriate tests.
391
614
 
392
- ## Documentation
615
+ ## Licensing Information
393
616
 
394
- Always refer to the official [dotCMS documentation](https://www.dotcms.com/docs/latest/) for comprehensive guides and API references.
617
+ dotCMS comes in multiple editions and as such is dual-licensed. The dotCMS Community Edition is licensed under the GPL 3.0 and is freely available for download, customization, and deployment for use within organizations of all stripes. dotCMS Enterprise Editions (EE) adds several enterprise features and is available via a supported, indemnified commercial license from dotCMS. For the differences between the editions, see [the feature page](http://www.dotcms.com/cms-platform/features).
395
618
 
396
- ## Getting Help
619
+ This SDK is part of dotCMS's dual-licensed platform (GPL 3.0 for Community, commercial license for Enterprise).
397
620
 
398
- | Source | Location |
399
- | --------------- | ------------------------------------------------------------------- |
400
- | Installation | [Installation](https://dotcms.com/docs/latest/installation) |
401
- | Documentation | [Documentation](https://dotcms.com/docs/latest/table-of-contents) |
402
- | Videos | [Helpful Videos](http://dotcms.com/videos/) |
403
- | Forums/Listserv | [via Google Groups](https://groups.google.com/forum/#!forum/dotCMS) |
404
- | Twitter | @dotCMS |
405
- | Main Site | [dotCMS.com](https://dotcms.com/) |
621
+ [Learn more ](https://www.dotcms.com)at [dotcms.com](https://www.dotcms.com).