Best for
- Setting up Mapbox GL JS in a new project
- Integrating Mapbox into a specific framework (React, Vue, Svelte, Angular, Next.js)
- Building framework-agnostic Web Components
mapbox/mapbox-agent-skills/skills/mapbox-web-integration-patterns/SKILL.md
Official integration patterns for Mapbox GL JS across popular web frameworks (React, Vue, Svelte, Angular). Covers setup, lifecycle management, token handling, search integration, and common pitfalls. Based on Mapbox's create-web-app scaffolding tool.
Decision brief
This skill provides official patterns for integrating Mapbox GL JS into web applications using React, Vue, Svelte, Angular, and vanilla JavaScript. These patterns are based on Mapbox's create-web-app scaffolding tool and represent production-ready best practices.
Compatibility matrix
| Platform | Status | Evidence | What to check |
|---|---|---|---|
| Codex | Not declared | No explicit evidence | Portability before use |
| Claude Code | Not declared | No explicit evidence | Portability before use |
| Cursor | Not declared | No explicit evidence | Portability before use |
| Gemini CLI | Not declared | No explicit evidence | Portability before use |
Installation
The source command is displayed only when detected. A safe inspection prompt is always available so your agent can explain every action before execution.
npx skills add https://github.com/mapbox/mapbox-agent-skills --skill "skills/mapbox-web-integration-patterns"Inspect the Agent Skill "mapbox-web-integration-patterns" from https://github.com/mapbox/mapbox-agent-skills/blob/304d4eb7b0c61d999ce1ad690fe368680e2e5993/skills/mapbox-web-integration-patterns/SKILL.md at commit 304d4eb7b0c61d999ce1ad690fe368680e2e5993. List every install step, command, network request, credential, file read/write, external action, and rollback step. Explain whether it fits my task. Do not install or execute anything until I approve.
Workflow
Recommended: v3.x (latest)
Recommended: v3.x (latest)
React: GL JS works with React 16.8+ (requires hooks). create-web-app scaffolds with React 19.x. Vue: GL JS works with Vue 2.x+ (Vue 3 Composition API recommended). Svelte: GL JS works with any Svelte version. create-web-app scaffolds with Svelte 5.x. Angular: GL JS works with An…
Review the “Mapbox Search JS” section in the pinned source before continuing.
Token patterns (work in v2.x and v3.x):
Permission review
The documentation asks the agent to run terminal commands or scripts.
npm install mapbox-gl@^3.0.0 # Installs latest v3.xThe documentation includes network, browsing, or remote request actions.
<script src="https://api.mapbox.com/mapbox-gl-js/vVERSION/mapbox-gl.js"></script>The documentation includes network, browsing, or remote request actions.
<link href="https://api.mapbox.com/mapbox-gl-js/vVERSION/mapbox-gl.css" rel="stylesheet" />The documentation asks the agent to run terminal commands or scripts.
npm install @mapbox/search-js-react@^1.0.0 # ReactEvidence record
| Signal | Value | Evidence type | Meaning |
|---|---|---|---|
| Quality score | 94/100 | Computed | Documentation, specificity, maintenance, and trust rules |
| Repository stars | 72 | Source | Repository attention, not individual Skill quality |
| Compatibility | 0 platforms | Source | Declared in the catalog source record |
| Usage guide | automated source guide | Editorial | Generated or reviewed according to the visible evidence level |
Pinned source
This skill provides official patterns for integrating Mapbox GL JS into web applications using React, Vue, Svelte, Angular, and vanilla JavaScript. These patterns are based on Mapbox's create-web-app scaffolding tool and represent production-ready best practices.
Recommended: v3.x (latest)
Installing via npm (recommended for production):
npm install mapbox-gl@^3.0.0 # Installs latest v3.x
CDN (for prototyping only):
<!-- Replace VERSION with latest v3.x from https://docs.mapbox.com/mapbox-gl-js/ -->
<script src="https://api.mapbox.com/mapbox-gl-js/vVERSION/mapbox-gl.js"></script>
<link href="https://api.mapbox.com/mapbox-gl-js/vVERSION/mapbox-gl.css" rel="stylesheet" />
React: GL JS works with React 16.8+ (requires hooks). create-web-app scaffolds with React 19.x.
Vue: GL JS works with Vue 2.x+ (Vue 3 Composition API recommended).
Svelte: GL JS works with any Svelte version. create-web-app scaffolds with Svelte 5.x.
Angular: GL JS works with Angular 2+. create-web-app scaffolds with Angular 19.x.
Next.js: Minimum 13.x (App Router), Pages Router 12.x+.
npm install @mapbox/search-js-react@^1.0.0 # React
npm install @mapbox/search-js-web@^1.0.0 # Other frameworks
optimizeForTerrain option removedToken patterns (work in v2.x and v3.x):
const token = import.meta.env.VITE_MAPBOX_ACCESS_TOKEN; // Use env vars in production
// Global token (works since v1.x)
mapboxgl.accessToken = token;
const map = new mapboxgl.Map({ container: '...' });
// Per-map token (preferred for multi-map setups)
const map = new mapboxgl.Map({
accessToken: token,
container: '...'
});
Every Mapbox GL JS integration must:
map.remove() on cleanup to prevent memory leaksimport 'mapbox-gl/dist/mapbox-gl.css'Pattern: useRef + useEffect with cleanup
Note: These examples use Vite (the bundler used in
create-web-app). If using Create React App, replaceimport.meta.env.VITE_MAPBOX_ACCESS_TOKENwithprocess.env.REACT_APP_MAPBOX_TOKEN. See Token Management Patterns for other bundlers.
import { useRef, useEffect } from 'react';
import mapboxgl from 'mapbox-gl';
import 'mapbox-gl/dist/mapbox-gl.css';
function MapComponent() {
const mapRef = useRef(null); // Store map instance
const mapContainerRef = useRef(null); // Store DOM reference
useEffect(() => {
mapboxgl.accessToken = import.meta.env.VITE_MAPBOX_ACCESS_TOKEN;
mapRef.current = new mapboxgl.Map({
container: mapContainerRef.current,
center: [-71.05953, 42.3629],
zoom: 13
});
// CRITICAL: Cleanup to prevent memory leaks
return () => {
mapRef.current.remove();
};
}, []); // Empty dependency array = run once on mount
return <div ref={mapContainerRef} style={{ height: '100vh' }} />;
}
Key points:
useRef for both map instance and containeruseEffect with empty deps []map.remove()import { useRef, useEffect, useState } from 'react';
import mapboxgl from 'mapbox-gl';
import { SearchBox } from '@mapbox/search-js-react';
import 'mapbox-gl/dist/mapbox-gl.css';
const accessToken = import.meta.env.VITE_MAPBOX_ACCESS_TOKEN;
const center = [-71.05953, 42.3629];
function MapWithSearch() {
const mapRef = useRef(null);
const mapContainerRef = useRef(null);
const [inputValue, setInputValue] = useState('');
useEffect(() => {
mapboxgl.accessToken = accessToken;
mapRef.current = new mapboxgl.Map({
container: mapContainerRef.current,
center: center,
zoom: 13
});
return () => {
mapRef.current.remove();
};
}, []);
return (
<>
<div
style={{
margin: '10px 10px 0 0',
width: 300,
right: 0,
top: 0,
position: 'absolute',
zIndex: 10
}}
>
<SearchBox
accessToken={accessToken}
map={mapRef.current}
mapboxgl={mapboxgl}
value={inputValue}
proximity={center}
onChange={(d) => setInputValue(d)}
marker
/>
</div>
<div ref={mapContainerRef} style={{ height: '100vh' }} />
</>
);
}
Install:
npm install @mapbox/search-js-react # React
npm install @mapbox/search-js-web # Vanilla/Vue/Svelte
Both packages include @mapbox/search-js-core as a dependency. Only install -core directly if building a custom search UI.
Key configuration options:
accessToken: Your Mapbox public tokenmap: Map instance (must be initialized first)mapboxgl: The mapboxgl library referenceproximity: [lng, lat] to bias results geographicallymarker: Boolean to show/hide result markerplaceholder: Search box placeholder textAbsolute positioning (overlay):
<div
style={{
position: 'absolute',
top: 10,
right: 10,
zIndex: 10,
width: 300
}}
>
<SearchBox {...props} />
</div>
Common positions:
top: 10px, right: 10pxtop: 10px, left: 10pxbottom: 10px, left: 10px// BAD - Memory leak!
useEffect(() => {
const map = new mapboxgl.Map({ ... })
// No cleanup function
}, [])
// GOOD - Proper cleanup
useEffect(() => {
const map = new mapboxgl.Map({ ... })
return () => map.remove() // Cleanup
}, [])
Why: Every Map instance creates WebGL contexts, event listeners, and DOM nodes. Without cleanup, these accumulate and cause memory leaks.
// BAD - Infinite loop in React!
function MapComponent() {
const map = new mapboxgl.Map({ ... }) // Runs on every render
return <div />
}
// GOOD - Initialize in effect
function MapComponent() {
useEffect(() => {
const map = new mapboxgl.Map({ ... })
}, [])
return <div />
}
Why: React components re-render frequently. Creating a new map on every render causes infinite loops and crashes.
// BAD - map variable lost between renders
function MapComponent() {
useEffect(() => {
let map = new mapboxgl.Map({ ... })
// map variable is not accessible later
}, [])
}
// GOOD - Store in useRef
function MapComponent() {
const mapRef = useRef()
useEffect(() => {
mapRef.current = new mapboxgl.Map({ ... })
// mapRef.current accessible throughout component
}, [])
}
Why: You need to access the map instance for operations like adding layers, markers, or calling remove().
// BAD - Vue's reactivity wraps data() objects in a Proxy, breaking mapbox-gl internals!
export default {
data() {
return {
map: null // Will be wrapped in a Proxy
}
},
mounted() {
this.map = new mapboxgl.Map({ ... }) // Proxy breaks GL internals
}
}
// GOOD - Assign map as a plain instance property, not in data()
export default {
mounted() {
this.map = new mapboxgl.Map({
container: this.$refs.mapContainer,
center: [-71.05953, 42.3629],
zoom: 13
})
},
unmounted() {
this.map?.remove()
}
}
Why: In Vue (especially Vue 3), data() properties are wrapped in a Proxy for reactivity. Mapbox GL JS internally checks object identity and uses properties that don't survive proxy wrapping. Storing the map in data() causes subtle, hard-to-debug failures. Instead, assign the map instance directly as this.map in mounted() — properties assigned outside data() are not made reactive.
// BAD — blank map when the token/style fails
const map = new mapboxgl.Map({ ... });
// GOOD — surface failures
map.on('error', (e) => {
console.error(e.error || e);
// optionally show an on-page error message
});
+esm<!-- BAD — often throws: does not provide export named 'makeBatchFromTable' -->
<script type="module">
import { MapboxOverlay } from 'https://cdn.jsdelivr.net/npm/@deck.gl/[email protected]/+esm';
</script>
<!-- GOOD — UMD bundle (or esm.sh) -->
<script src="https://unpkg.com/[email protected]/dist.min.js"></script>
<script>
const { MapboxOverlay, ScatterplotLayer } = deck;
map.addControl(
new MapboxOverlay({
interleaved: false,
layers: [
/* ... */
]
})
);
</script>
Use MapboxOverlay (Mapbox IControl), not a bare Deck as a map control.
draw.createIf you load mapbox-gl-draw, listen for draw.create (and update the UI from draw.getAll()). Half-deleted handlers that leave a dangling }); crash the page.
setStyle (no style.load rebind)map.setStyle(...) replaces the style tree. Custom sources/layers/handlers added earlier are wiped unless you re-attach them.
function onStyleReady() {
// re-add sources, layers, and interaction handlers here
}
map.on('style.load', onStyleReady);
document.querySelectorAll('[data-style]').forEach((btn) => {
btn.addEventListener('click', () => {
map.setStyle(btn.dataset.style);
// do NOT only add layers on the first 'load' — wait for style.load after every switch
});
});
Agent anti-pattern: style switcher buttons that call setStyle once with no style.load rebind. The first style works; every switch after looks broken.
Load these for framework-specific patterns and additional details:
references/vue.md — Vue Integration (mounted/unmounted lifecycle)references/svelte.md — Svelte Integration (onMount/onDestroy)references/angular.md — Angular Integration with SSR handlingreferences/vanilla.md — Vanilla JS (Vite) + Vanilla JS (CDN)references/web-components.md — Web Components (basic + reactive + usage in React/Vue/Svelte)references/nextjs.md — Next.js App Router + Pages Routerreferences/common-mistakes.md — Common Mistakes 4-7 + Testing Patternsreferences/token-management.md — Token Management per bundler + Style ConfigurationInvoke this skill when:
Frequently asked questions
This skill provides official patterns for integrating Mapbox GL JS into web applications using React, Vue, Svelte, Angular, and vanilla JavaScript. These patterns are based on Mapbox's create-web-app scaffolding tool and represent production-ready best practices.
The source record exposes this install command: npx skills add https://github.com/mapbox/mapbox-agent-skills --skill "skills/mapbox-web-integration-patterns". Inspect the command and pinned source before running it.
Static rules flagged exec-script, network in the source; the page lists the matching lines and excerpts.
Alternatives
event4u-app/agent-config
Use BEFORE writing or editing any non-trivial UI — inventories components, design tokens, shadcn primitives, and reusable patterns into state.ui_audit. Hard gate for the ui directive set.
kensaurus/cursor-kenji
Add purposeful 3D/WebGL and scroll choreography to an existing site with Three.js/R3F, GSAP, or Motion. Use when "add 3D", "WebGL hero", "React Three Fiber", or "scroll-driven 3D". General UI polish → enhance-web-ui. Motion without 3D → enhance-motion.
UiPath/skills
UiPath Coded Apps — scaffold, build, run, and deploy Coded Web Apps and Coded Action Apps: React/TypeScript apps that call UiPath Cloud APIs via the `@uipath/uipath-typescript` SDK and ship to Automation Cloud (push/pull to Studio Web, pack, publish, deploy, OAuth-PKCE). Also generates live analytics & governance dashboards from a plain-language request, wired to tenant data via the Insights real-time API, with edit and deploy flows. For RPA→uipath-rpa, Python agents→uipath-agents, Maestro flows
objectstack-ai/objectstack
Author ObjectStack UI metadata — Views (list/form/kanban/calendar/gantt), Apps (navigation), Pages (structured plus the HTML and React source-authoring tiers, ADR-0080/0081), Dashboards, Reports, Charts, Actions, and package Docs (`src/docs/*.md`). Use when the user is adding `*.view.ts` / `*.app.ts` / `*.dashboard.ts` / `*.action.ts` / `src/docs/*.md` files or designing a Studio-rendered UI surface, including dataset-bound dashboard/report widgets. Do not use for: data schema (see objectstack-d