Innovation in web development thrives on the right tools. For those seeking the robust capabilities of universal content management without sacrificing front-end flexibility, the dotCMS JavaScript SDK will transform your approach and is designed to seamlessprly bridge dotCMS with your preferred JavaScript framework.
In this guide, I will demonstrate how to use the dotCMS JavaScript SDK to quickly render dotCMS pages in your preferred JavaScript framework.
Why Framework Agnosticism is Your Superpower
Imagine building a dynamic web application with the framework you're most comfortable with–be it React, Angular, Vue, or even a homegrown framework–and having access to the full power of dotCMS's universal capabilities. That's the promise of the dotCMS JavaScript SDK. It’s about breaking free from the constraints of specific technologies and embracing a future where your tools adapt to you, not the other way around.
This framework agnosticism isn't just a nice-to-have; it's a strategic advantage. It means:
No Lock-In: Choose the best framework for each project without rewriting your entire content management integration.
Future-Proofing: Stay agile and adopt new frameworks as they emerge, without disrupting your content infrastructure.
Team Flexibility: Empower diverse teams to work with their preferred tools, boosting productivity.
Getting Started: Your Quickstart Journey
Ready to take the dotCMS JavaScript SDK for a spin? Here's a simplified quickstart to get you going:
Install the SDK and Select Your Framework
First, install the core @dotcms/client library and the framework-specific library (e.g. @dotcms/react or @dotcms/angular) in your project, this example code uses npm, but you can use any package manager like yarn or bun.
npm install @dotcms/client @dotcms/react # For React
npm install @dotcms/client @dotcms/angular # For Angular
@dotcms/client: The API Interaction Engine
At the heart of the SDK lies @dotcms/client. Think of this as your dedicated communication channel with the dotCMS REST API. It takes care of the heavy lifting of fetching data, managing API requests, and handling authentication. Key features include:
Simplified API Calls: @dotcms/client provides intuitive methods to fetch pages, navigation menus, and content items in JSON without having to write your own HTTP requests.
Powerful Query Building: Need to retrieve specific content based on complex criteria? The SDK includes a robust query builder, allowing you to construct rich Lucene queries in a type-safe and readable manner.
Editor Integration: This library is the bridge between your web application and the dotCMS Universal Visual Editor (UVE). It sets up real-time communication, enabling features like inline editing and visual page building directly within your chosen framework.
Initialize the Client
In your application's entry point, initialize the DotCmsClient with your dotCMS instance URL and API token:
import { DotCmsClient } from '@dotcms/client';
const client = DotCmsClient.init({
dotcmsUrl: 'YOUR_DOTCMS_URL',
authToken: 'YOUR_DOTCMS_API_TOKEN',
siteId: 'YOUR_DOTCMS_SITE_ID' // Optional, if needed
});
Implement Catch-All Routing
To fully leverage the SDK, implement a catch-all route that dynamically fetches and renders dotCMS-managed pages.
Next.js (App Directory)
In Next.js 13 and later, using the app directory, create a route group (or a folder named app) and within it, a folder named [[...slug]]. Inside this folder, create a page.jsx (or page.tsx) file. Next.js automatically interprets [[...slug]] as a catch-all route.
// app/[[...slug]]/page.js
import MyDotCMSPageComponent from './my-dotcms-page-component'; // Your dotCMS page component
export default function CatchAllRoute({ params }) {
const { slug } = params;
const path = slug ? /${slug.join('/')} : '/';
return <MyDotCMSPageComponent path={path} />;
}
React Router
Using React Router v6, define a route with the path="*". This path matches any URL.
// App.js or similar routing configuration file
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import DotcmsLayout from '@dotcms/react';
function App() {
return (
<Router>
<Routes>
<Route path="*" element={<DotcmsLayout />} />
</Routes>
</Router>
);
}
Angular
In Angular, configure your routing module (e.g., app-routing.module.ts) with a route that uses path: '**'. The ** wildcard in Angular routes matches any route.
// app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { DotCMSPageComponent } from './dotcms-page.component'; // Your dotCMS page component
const routes: Routes = [
{ path: '**', component: DotCMSPageComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
Why Catch-All Routing?
Your application needs to be flexible enough to render pages with URLs defined within dotCMS, not predetermined routes in your codebase. Catch-all routes act as the entry point for any URL that doesn't match a specific, predefined route in your application, effectively delegating the routing decision to dotCMS.
Render the Layout
Use the appropriate component from the SDK to render dotCMS pages, based on the framework you’re building in
@dotcms/react: React Components for Dynamic Rendering
For React developers, @dotcms/react provides a rich set of pre-built React components that understand the dotCMS layout system, making it easy to render dotCMS pages within your React applications. Here is the code example:
// React Example (Client-Side Rendering)
import { DotcmsLayout } from '@dotcms/react';
function MyPage() {
const [pageAsset, setPageAsset] = useState(null);
useEffect(() => {
const fetchPage = async () => {
const data = await client.page.get({ path: '/your-page-path' });
setPageAsset(data);
};
fetchPage();
}, []);
return pageAsset ? <DotcmsLayout pageContext={{ pageAsset, components: /* Your Component Map */ }} config={{ pathname: '/your-page-path' }} /> : <div>Loading...</div>;
}
// Next.js Example (Server-Side Rendering in app directory - [[...slug]]/page.js)
import { DotcmsLayout } from '@dotcms/react';
import { client } from '@/dotcmsClient'; // Assuming you have dotcmsClient.js in your src folder
export default async function MyPage({ params }) {
const path = params.slug ? params.slug.join('/') : '/';
const pageAsset = await client.page.get({ path });
return pageAsset ? <DotcmsLayout pageContext={{ pageAsset, components: /* Your Component Map */ }} config={{ pathname: path }} /> : <div>Loading...</div>;
}
Key concepts include:
DotcmsLayout Component: This component takes the JSON response from the dotCMS Page API and intelligently renders the entire page layout, rows, columns, containers, and contentlets with minimal code.
DotEditableText Component: Wrap this component around any text-based contentlet, and it instantly becomes editable inline directly within the UVE, providing a seamless content authoring experience.
Block Editor Renderer: Render dotCMS Block Editor fields with the BlockEditorRenderer component, complete with support for custom renderers to tailor the output to your preferences.
@dotcms/angular: Angular Components for Seamless Integration
For Angular developers, @dotcms/angular mirrors the functionality of its React counterpart, bringing the same level of ease and efficiency to Angular applications.
// Angular Example
import { DotcmsLayoutComponent } from '@dotcms/angular';
@Component({
selector: 'app-dotcms-page',
template: <dotcms-layout [pageAsset]="pageAsset" [components]="componentsMap" [editor]="editorConfig"></dotcms-layout>
})
export class DotCMSPageComponent implements OnInit {
pageAsset: DotCMSPageAsset;
componentsMap = DYNAMIC_COMPONENTS; // Your Component Map
editorConfig = { params: { depth: 2 } };
constructor(private pageService: PageService) {}
ngOnInit(): void {
this.pageService.getPageData('/your-page-path').subscribe(data => {
this.pageAsset = data;
});
}
}
Key features include:
DotcmsLayoutComponent: Similar to the React version, this component is your one-stop shop for rendering entire dotCMS page layouts in Angular, handling the complexities of rows, columns, and containers.
DotEditableTextComponent: Bring inline editing to your Angular app with this component. It leverages TinyMCE to provide a rich text editing experience directly within your Angular components, fully integrated with the UVE.
Dynamic Component Rendering: Angular's powerful dynamic components are leveraged to map dotCMS content types to your Angular components, ensuring the right content is rendered in the right way.
Services for Context Management: The PageContextService provides a centralized way to manage and share dotCMS page data across your Angular application, making data access clean and efficient.
Map Content Types to Components
A component registry is a map connecting dotCMS content types to specific UI components in your framework. Think of it as a directory that determines which component should render each content type dynamically. For example, you could map a 'blog' content type to a BlogPostComponent and an 'image' content type to an ImageComponent. Here's how you can set one up:
const componentRegistry = {
'blog': BlogPostComponent,
'image': ImageComponent,
'video': VideoComponent
};
function resolveComponent(contentType) {
return componentRegistry[contentType] || DefaultComponent;
}
Enable Inline Editing
Wrap editable fields with DotEditableText to enable real-time editing in the UVE. For React:
import { DotEditableText } from '@dotcms/react';
<DotEditableText field="title" contentlet={contentlet} />
And for Angular:
<dotcms-editable-text field="title" [contentlet]="contentlet"></dotcms-editable-text>
Unlock Speed, Flexibility, and Editor Empowerment
The dotCMS JavaScript SDK is more than just a set of libraries–it's a big step forward in your development workflow. It empowers you to:
Develop Faster: Skip the boilerplate and focus on building compelling user experiences.
Embrace Framework Freedom: Work with the tools you love, without compromising dotCMS integrability.
Empower Content Authors: Provide your content team with a best-in-class visual editing experience, leading to happier authors and more dynamic content.
Next Steps
Ready to experience the future of Universal CMS development? Dive deeper into the dotCMS JavaScript SDK, explore our detailed guides and examples, and start building something amazing today!