a

How to Embed MongoDB Dashboards in Your App

Share on facebook
Share on linkedin
Share on twitter
Share on email

TL;DR

MongoDB Charts offers two embedding paths: iframe (quick but limited) and JavaScript SDK (more control with auth and filtering). Iframe works for prototypes; the SDK handles authenticated, filtered dashboards. But neither provides true multi-tenancy, row-level security, cross-collection joins, or full white-labeling which is where purpose-built embedded analytics platforms take over for customer-facing SaaS.

This tutorial covers embedding MongoDB Charts dashboards into your web application, providing interactive data visualizations for your users.

Table of Contents

Prerequisites

  • MongoDB Atlas account with an active cluster
  • MongoDB Charts enabled on your Atlas project
  • A web application (React, Vue, Angular, or vanilla JavaScript)
  • Basic knowledge of JavaScript and HTML

Overview

MongoDB Charts is Atlas’s built-in visualization tool that allows you to create dashboards directly from your MongoDB data. For a comparison of MongoDB Charts against other visualization options, see MongoDB Charts: What It Is, How It Works, And What It’s Used For and The Best MongoDB Visualization, Reporting and Analytics Tools. You can embed these charts in your applications using:

  1. Iframe Embedding – Simple HTML iframe integration
  2. JavaScript SDK – Programmatic control with the Charts Embedding SDK

Part 1: Creating a Chart in MongoDB Charts

Step 1: Access MongoDB Charts

  1. Log into MongoDB Atlas
  2. Navigate to your project
  3. Click Charts in the left sidebar
  4. Click Add Dashboard to create a new dashboard

Step 2: Create Your First Chart

  1. Click Add Chart on your dashboard
  2. Select your data source (database and collection)
  3. Choose a chart type (bar, line, pie, etc.)
  4. Drag fields to configure your visualization
  5. Click Save and Close

Part 2: Embedding with Iframe (Simple Method)

Step 1: Enable Embedding for Your Chart

  1. Open your chart in MongoDB Charts
  2. Click the menu on the chart
  3. Select Embed Chart
  4. Toggle Enable unauthenticated access (for public charts) or configure authentication
  5. Copy the iframe embed code

Step 2: Add to Your HTML

<!DOCTYPE html>
<html>
<head>
<title>MongoDB Dashboard</title>
<style>
.chart-container {
width: 100%;
max-width: 800px;
margin: 0 auto;
}
iframe {
width: 100%;
height: 480px;
border: none;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
</style>
</head>
<body>
<div class="chart-container">
<iframe
src="https://charts.mongodb.com/charts-project-xxxxx/embed/charts?id=xxxxx-xxxxx-xxxxx&maxDataAge=3600&theme=light&autoRefresh=true"
allowfullscreen>
</iframe>
</div>
</body>
</html>

Iframe URL Parameters

ParameterDescription
maxDataAgeCache duration in seconds
themelight or dark
autoRefreshEnable automatic data refresh
filterJSON filter to apply to the chart
URL parameters for iframe

The SDK provides more control, including programmatic filtering and authenticated embedding.

Step 1: Install the SDK

npm install @mongodb-js/charts-embed-dom

Or include via CDN:

<script src="https://unpkg.com/@mongodb-js/charts-embed-dom"></script>

Step 2: Get Your Embed Credentials

  1. In MongoDB Charts, click on your chart
  2. Select Embed Chart
  3. Choose Verified Signature or Authenticated embedding
  4. Copy your Base URL and Chart ID

Step 3: Basic SDK Implementation

import ChartsEmbedSDK from '@mongodb-js/charts-embed-dom';
// Initialize the SDK
const sdk = new ChartsEmbedSDK({
baseUrl: 'https://charts.mongodb.com/charts-project-xxxxx'
});
// Create the chart
const chart = sdk.createChart({
chartId: 'xxxxx-xxxxx-xxxxx',
height: '400px',
width: '600px',
theme: 'light',
autoRefresh: true,
maxDataAge: 300 // 5 minutes
});
// Render the chart
chart.render(document.getElementById('chart-container'));

Step 4: React Implementation

import React, { useEffect, useRef } from 'react';
import ChartsEmbedSDK from '@mongodb-js/charts-embed-dom';
const MongoDBChart = ({ chartId, filter }) => {
const chartRef = useRef(null);
const renderedChart = useRef(null);
useEffect(() => {
const sdk = new ChartsEmbedSDK({
baseUrl: 'https://charts.mongodb.com/charts-project-xxxxx'
});
const chart = sdk.createChart({
chartId: chartId,
height: '400px',
theme: 'light'
});
chart.render(chartRef.current).then(() => {
renderedChart.current = chart;
});
return () => {
// Cleanup on unmount
if (renderedChart.current) {
renderedChart.current = null;
}
};
}, [chartId]);
// Update filter when it changes
useEffect(() => {
if (renderedChart.current && filter) {
renderedChart.current.setFilter(filter);
}
}, [filter]);
return <div ref={chartRef} className="chart-container" />;
};
// Usage
function App() {
const [dateFilter, setDateFilter] = useState({
createdAt: { $gte: new Date('2024-01-01') }
});
return (
<div>
<h1>Sales Dashboard</h1>
<MongoDBChart
chartId="xxxxx-xxxxx-xxxxx"
filter={dateFilter}
/>
</div>
);
}
export default App;

Part 4: Authenticated Embedding

For secure, user-specific dashboards, use authenticated embedding.

Option A: Realm App Services Authentication

import ChartsEmbedSDK from '@mongodb-js/charts-embed-dom';
import * as Realm from 'realm-web';
const app = new Realm.App({ id: 'your-app-id' });
async function renderAuthenticatedChart() {
// Login user
const credentials = Realm.Credentials.emailPassword(
'user@example.com',
'password'
);
const user = await app.logIn(credentials);
// Initialize SDK with user token
const sdk = new ChartsEmbedSDK({
baseUrl: 'https://charts.mongodb.com/charts-project-xxxxx',
getUserToken: () => user.accessToken
});
const chart = sdk.createChart({
chartId: 'xxxxx-xxxxx-xxxxx'
});
await chart.render(document.getElementById('chart'));
}

Option B: Custom JWT Authentication

const sdk = new ChartsEmbedSDK({
baseUrl: 'https://charts.mongodb.com/charts-project-xxxxx',
getUserToken: async () => {
// Fetch JWT from your backend
const response = await fetch('/api/charts-token');
const { token } = await response.json();
return token;
}
});

Part 5: Dynamic Filtering

Apply filters programmatically to show user-specific data.
const chart = sdk.createChart({
chartId: 'xxxxx-xxxxx-xxxxx',
filter: {
// Initial filter
region: 'North America'
}
});
await chart.render(document.getElementById('chart'));
// Update filter dynamically
document.getElementById('region-select').addEventListener('change', (e) => {
chart.setFilter({ region: e.target.value });
});
// Combine multiple filters
chart.setFilter({
region: 'Europe',
status: 'active',
revenue: { $gte: 10000 }
});
// Clear filters
chart.setFilter({});

Part 6: Embedding Full Dashboards

Embed an entire dashboard instead of individual charts.

const sdk = new ChartsEmbedSDK({
baseUrl: 'https://charts.mongodb.com/charts-project-xxxxx'
});
const dashboard = sdk.createDashboard({
dashboardId: 'xxxxx-xxxxx-xxxxx',
height: '800px',
widthMode: 'scale', // 'scale' or 'fixed'
heightMode: 'fixed',
theme: 'dark',
showAttribution: false
});
dashboard.render(document.getElementById('dashboard-container'));
// Apply filter to all charts in dashboard
dashboard.setFilter({ organizationId: 'org-123' });
// Refresh all charts
dashboard.refresh();

Part 7: Event Handling

Listen to chart events for interactivity.

const chart = sdk.createChart({
chartId: 'xxxxx-xxxxx-xxxxx'
});
// Listen for click events
chart.addEventListener('click', (payload) => {
console.log('Clicked data point:', payload.data);
// Navigate to detail view, show modal, etc.
});
// Listen for refresh events
chart.addEventListener('refreshstart', () => {
console.log('Chart is refreshing...');
});
chart.addEventListener('refreshend', () => {
console.log('Chart refresh complete');
});
// Get current chart data
const data = await chart.getData();
console.log('Chart data:', data);

Best Practices

Performance

  1. Set appropriate maxDataAge – Balance freshness vs. performance
  2. Use filters – Reduce data transferred to the client
  3. Lazy load charts – Only render charts when visible
// Intersection Observer for lazy loading
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
renderChart(entry.target);
observer.unobserve(entry.target);
}
});
});
document.querySelectorAll('.chart-placeholder').forEach(el => {
observer.observe(el);
});

Security

  1. Use authenticated embedding for sensitive data
  2. Apply server-side filters via JWT claims
  3. Never expose embedding credentials in client-side code
  4. Enable CORS only for your domains in Atlas settings

Responsive Design

.chart-container {
width: 100%;
min-height: 300px;
max-height: 600px;
}
@media (max-width: 768px) {
.chart-container {
height: 250px;
}
}

Troubleshooting

IssueSolution
Chart not renderingCheck if embedding is enabled and URL/ID are correct
CORS errorsAdd your domain to allowed origins in Charts settings
Authentication failedVerify JWT token format and expiration
Filters not applyingEnsure field names match your collection schema
Slow loadingIncrease maxDataAge, add database indexes
Troubleshooting various issues

Start with iframe embedding for quick prototypes, then migrate to the SDK when you need programmatic control or authentication. If you need multi-tenant security, cross-source joins, or full white-labeling, see The Complete Guide to Embedded Analytics with Knowi.

When MongoDB Charts Is the Right Fit

MongoDB Charts embedding works well if:

  • Your dashboards are **internal or lightly shared**
  • Data is **non-sensitive or aggregate**
  • You don’t need strict tenant isolation
  • You’re embedding a **small number of charts**
  • You’re optimizing for **speed to first dashboard**

Most teams start here.

What MongoDB Charts Embedding Supports

MongoDB Charts lets you embed visualizations using two approaches:

1. Iframe Embedding (Fastest Path)

  • Simple <iframe> embed
  • Optional public or authenticated access
  • Minimal setup
  • Best for prototypes and internal tools

2. Charts Embedding SDK (More Control)

  • Programmatic rendering
  • Dynamic filters
  • Authenticated embedding
  • Better lifecycle control

The SDK is typically used once analytics moves inside the product, not just alongside it.

Creating Charts in MongoDB Charts (Baseline Setup)

To embed anything, you first need charts.

Steps

  1. Log into MongoDB Atlas
  2. Open Charts from the left sidebar
  3. Create a dashboard
  4. Add charts from a single collection
  5. Save the dashboard

At this stage, MongoDB Charts works like a traditional BI layer on top of MongoDB.

Embedding via Iframe (What Most Teams Start With)

Iframe embedding is the simplest way to get charts into your app.

How it works

  • MongoDB hosts the visualization
  • Your app renders it via iframe
  • Optional URL parameters control refresh, theme, and filters

Where iframe embedding starts to strain

  • Filters are client-side and modifiable
  • No tenant-level enforcement
  • Limited customization
  • Not suitable for sensitive customer data

Iframe works well until analytics becomes customer-facing.

Embedding with the JavaScript SDK (Where Complexity Starts)

Once you need authentication, dynamic filtering, or tighter integration, teams move to the SDK.

What the SDK adds

  • Authenticated embedding
  • Programmatic filters
  • Dashboard lifecycle control
  • Better UX control than iframe

What it still doesn’t solve

  • True row-level security
  • Multi-tenant enforcement
  • Cross-collection analytics
  • Deep event-level interactivity

This is usually the inflection point where teams reassess whether MongoDB Charts can scale with the product.

Authentication Options (What’s Actually Possible)

MongoDB Charts supports authenticated embedding using:

Option 1: Atlas App Services (formerly Realm)

  • Users authenticate via MongoDB’s auth layer
  • Charts access is tied to user tokens
  • Works for internal or MongoDB-centric apps

Option 2: Custom JWT Authentication

  • JWT issued by your backend
  • Claims can be mapped to chart filters
  • Requires careful server-side enforcement

Important: Filters ≠ security. Filters can reduce data shown, but MongoDB Charts does not offer true row-level or tenant isolation for embedded analytics. For a detailed look at security tradeoffs, see SSO vs Secure URL Embedding.

Dynamic Filtering (Useful, but Not Security)

You can apply filters programmatically:

chart.setFilter({ region: 'Europe' });

This works well for:

  • UX personalization
  • Simple segmentation
  • Interactive dashboards

It should not be used to enforce customer isolation in a SaaS product.

Embedding Full Dashboards

You can embed entire dashboards instead of individual charts:

  • Faster setup
  • Consistent layouts
  • Shared filters across charts

This works well for internal teams and single-tenant apps, but becomes harder to manage as customer count grows.

Known Limitations Teams Hit

This is where most evaluations get serious:

  • Single-collection analytics only
  • No joins across MongoDB collections or external sources (see How to Join MongoDB Data with MySQL, Elasticsearch, REST APIs for what’s possible with federation)
  • Limited customization and theming
  • No reliable click-level events or data extraction
  • Filters are not security boundaries
  • Scaling embedded analytics increases operational complexity

For many teams, this is the point where MongoDB Charts stops being “good enough.”

Summary: Where MongoDB Charts Fits

MongoDB Charts is a solid choice when:

  • You need dashboards quickly
  • Your data is non-sensitive
  • Analytics is supportive, not core

Teams typically outgrow it when:

  • Analytics becomes a **product feature**
  • Customers expect isolation and customization
  • Data spans multiple collections or sources
  • Engineering becomes the bottleneck again

At that stage, most teams evaluate purpose-built embedded analytics platforms rather than extending Charts further.

Frequently Asked Questions

Can MongoDB Charts handle multi-tenant embedded analytics?

MongoDB Charts supports filtering via the SDK, which lets you pass user-specific parameters to restrict data at render time. However, this is client-side filtering, not true multi-tenancy. There’s no built-in tenant model, no row-level security enforcement, and no audit trail for data isolation. For customer-facing SaaS with strict data separation requirements, you’ll need to build the tenant isolation layer yourself or use a purpose-built platform.

Is MongoDB Charts free to use?

Yes, MongoDB Charts is included with MongoDB Atlas at no additional cost. You can create dashboards and embed them using iframes or the JavaScript SDK. However, advanced features like full white-labeling, cross-collection joins, and production-grade multi-tenancy require additional tooling or a dedicated embedded analytics platform.

What’s the difference between iframe embedding and SDK embedding in MongoDB Charts?

Iframe embedding is the simplest method, you copy an embed URL and place it in an <iframe> tag. It’s fast to set up but offers limited control over authentication, filtering, and styling. The JavaScript SDK provides programmatic control, including authenticated embedding, dynamic filters, and chart lifecycle management. Most teams start with iframe and move to SDK when analytics moves inside the product.

Can I join MongoDB data with other databases in MongoDB Charts?

No. MongoDB Charts only visualizes data from a single MongoDB collection per chart. It doesn’t support cross-collection joins or joins with external databases like PostgreSQL, MySQL, or Elasticsearch. If your analytics require combining data from multiple sources, see How to Join MongoDB Data with MySQL, Elasticsearch, REST APIs.

When should I move beyond MongoDB Charts for embedded analytics?

Teams typically outgrow MongoDB Charts when analytics becomes a core product feature, customers expect data isolation and branded dashboards, data spans multiple collections or external sources, or engineering time spent on embedding workarounds exceeds the cost of a dedicated platform. If you’re evaluating alternatives, see MongoDB Charts vs Metabase vs Knowi.

Does MongoDB Charts work outside of MongoDB Atlas?

No. MongoDB Charts is exclusive to MongoDB Atlas, it cannot connect to self-hosted MongoDB deployments, other databases, or REST APIs. If you need analytics on self-hosted MongoDB or need to combine MongoDB with other data sources, you’ll need an alternative tool.

How do I make MongoDB Charts dashboards look like part of my app?

MongoDB Charts offers basic theming (light/dark mode) and the ability to hide attribution via showAttribution: false in the SDK. However, full white-labeling, custom fonts, colors, logos, and complete branding removal, is limited. For a fully branded experience, see White-Label Embedded Analytics: Complete Guide for SaaS.


Learn more about how you can embed MongoDB Charts without any limitations. Request a Demo →

Sanskriti Garg

Sanskriti Garg

Sanskriti Garg is the Marketing Manager at Knowi, where she leads all marketing initiatives for the company. She oversees positioning, messaging, go-to-market strategy, and campaigns that help Knowi reach businesses looking to unify, analyze, and act on their data with powerful AI analytics. Sanskriti brings over 10+ years of marketing experience, with a strong consumer-focused mindset and storytelling skills. Her expertise spans marketing, demand generation, AI, and analytics, and she’s passionate about making advanced analytics accessible and impactful for organizations of all sizes.

Want to See Knowi in Action?

Connect your databases, run cross-source joins, and ask questions in plain English. No warehouse required.

See Knowi in action
Connect your databases, query across sources, and run AI on-premises. No warehouse required.
Book a Demo