mapbox-web-integration-patterns
Provides production-ready integration patterns for Mapbox GL JS v3.x across React, Vue, Svelte, Angular, Next.js, and vanilla JavaScript.
Identity proven by GitHub's verified organisation badge (mapbox)
- Agents
- Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, OpenCode, claude.ai and API
- License
- MIT (permissive)
- Pin
- f71cd72pinned Oct 9, 2026
- Context cost
- about 3,100 tokenswhen the skill loads
- GitHub stars
- 80on mapbox/mapbox-agent-skills
- Scripts
- None found
What it does
“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.”
Generated summary from the skill's own text
Provides production-ready integration patterns for Mapbox GL JS v3.x across React, Vue, Svelte, Angular, Next.js, and vanilla JavaScript. Covers proper lifecycle management, token handling, search integration using Mapbox Search JS, and detailed documentation of common mistakes like memory leaks and proxy issues in Vue.
When to use it
- Setting up Mapbox GL JS in a new web project or framework
- Integrating Mapbox Search functionality with search boxes
- Debugging map initialization, cleanup, or framework lifecycle issues
- Converting Mapbox implementations between different frameworks
When not to
- Projects using Mapbox GL JS v2.x or legacy versions
- Building custom map styling without code integration patterns
- Creating mobile apps outside web browser environments
Install
These commands install from the publisher's repository and need no account.
skills CLI
npx skills add mapbox/mapbox-agent-skills --skill mapbox-web-integration-patternsInstalls from the repository's default branch, which may have changed since the commit we checked.
GitHub CLI 2.90 or later
gh skill install mapbox/mapbox-agent-skills mapbox-web-integration-patterns@f71cd72b8d8937b06db440538bd65559eb792c49Installs the commit we checked (f71cd72).
Copy by hand
Download the folder at f71cd72 and put it in .claude/skills/mapbox-web-integration-patterns for Claude Code and in .agents/skills/mapbox-web-integration-patterns for Codex, Cursor, Gemini CLI, GitHub Copilot and OpenCode.
Claude Code plugin
/plugin install mapbox@claude-plugins-officialThe publisher's plugin in Claude's official marketplace. It may hold more than this skill, and we have not pinned it.
Copy for your agent
A prompt for any coding agent. It installs this skill from GitHub at the pinned commit, copies the files as they are, and runs nothing unless you ask.
Prompt
Install the agent skill "mapbox-web-integration-patterns" by Mapbox. Source, pinned to commit f71cd72b8d8937b06db440538bd65559eb792c49: https://github.com/mapbox/mapbox-agent-skills/tree/f71cd72b8d8937b06db440538bd65559eb792c49/skills/mapbox-web-integration-patterns 1. Download that folder at exactly this commit. Do not use the default branch. 2. Copy every file unchanged, keeping the folder structure, into .claude/skills/mapbox-web-integration-patterns/ for Claude Code and .agents/skills/mapbox-web-integration-patterns/ for Codex, Cursor, Gemini CLI, GitHub Copilot and OpenCode. Create the folders if they do not exist. 3. Do not edit the files, and do not run any script in the folder unless I ask you to. 4. When you are done, list the files you copied and where you put them. Listing and checks: https://www.agentnative.dev/skills/mapbox/mapbox-web-integration-patterns
SKILL.md at the pin
---
name: mapbox-web-integration-patterns
description: 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.
---
# Mapbox Integration Patterns Skill
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.
## Version Requirements
### Mapbox GL JS
**Recommended:** v3.x (latest)
- **Minimum:** v3.0.0
- **Why v3.x:** Modern API, improved performance, active development
- **v2.x:** Legacy; no longer actively developed (see migration notes below)
**Installing via npm (recommended for production):**
```bash
npm install mapbox-gl@^3.0.0 # Installs latest v3.x
```
**CDN (for prototyping only):**
```html
<!-- 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" />
```
### Framework Requirements
**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+.
### Mapbox Search JS
```bash
npm install @mapbox/search-js-react@^1.0.0 # React
npm install @mapbox/search-js-web@^1.0.0 # Other frameworks
```
### Version Migration Notes (v2.x to v3.x)
- WebGL 2 now required
- `optimizeForTerrain` option removed
- Improved TypeScript types, better tree-shaking support
- No breaking changes to core initialization patterns
**Token patterns (work in v2.x and v3.x):**
```javascript
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: '...'
});
```
## Core Principles
**Every Mapbox GL JS integration must:**
1. Initialize the map in the correct lifecycle hook
2. Store map instance in component state (not recreate on every render)
3. **Always call `map.remove()` on cleanup** to prevent memory leaks
4. Handle token management securely (environment variables)
5. Import CSS: `import 'mapbox-gl/dist/mapbox-gl.css'`
## React Integration (Primary Pattern)
**Pattern: useRef + useEffect with cleanup**
> **Note:** These examples use **Vite** (the bundler used in `create-web-app`). If using Create React App, replace `import.meta.env.VITE_MAPBOX_ACCESS_TOKEN` with `process.env.REACT_APP_MAPBOX_TOKEN`. See [Token Management Patterns](references/token-management.md) for other bundlers.
```jsx
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:**
- Use `useRef` for both map instance and container
- Initialize in `useEffect` with empty deps `[]`
- **Always return cleanup function** that calls `map.remove()`
- Never initialize map in render (causes infinite loops)
### React + Search JS
```jsx
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' }} />
</>
);
}
```
## Search JS Integration Summary
**Install:**
```bash
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 token
- `map`: Map instance (must be initialized first)
- `mapboxgl`: The mapboxgl library reference
- `proximity`: `[lng, lat]` to bias results geographically
- `marker`: Boolean to show/hide result marker
- `placeholder`: Search box placeholder text
### Positioning Search Box
**Absolute positioning (overlay):**
```jsx
<div
style={{
position: 'absolute',
top: 10,
right: 10,
zIndex: 10,
width: 300
}}
>
<SearchBox {...props} />
</div>
```
**Common positions:**
- Top-right: `top: 10px, right: 10px`
- Top-left: `top: 10px, left: 10px`
- Bottom-left: `bottom: 10px, left: 10px`
## Common Mistakes (Critical)
### Mistake 1: Forgetting to call map.remove()
```javascript
// 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.
### Mistake 2: Initializing map in render
```javascript
// 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.
### Mistake 3: Not storing map instance properly
```javascript
// 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()`.
### Mistake 4: Storing map instance in Vue's data() (Vue-specific)
```javascript
// 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.
### Mistake 5: Silent style/tile failures (no error handler)
```javascript
// 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
});
```
### Mistake 6: Broken deck.gl CDN via jsDelivr `+esm`
```html
<!-- BAD — often throws: does not provide export named 'makeBatchFromTable' -->
<script type="module">
import { MapboxOverlay } from 'https://cdn.jsdelivr.net/npm/@deck.gl/mapbox@9.0.0/+esm';
</script>
<!-- GOOD — UMD bundle (or esm.sh) -->
<script src="https://unpkg.com/deck.gl@9.1.14/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.
### Mistake 7: Draw toolbar without `draw.create`
If 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.
### Mistake 8: Layers lost after `setStyle` (no `style.load` rebind)
`map.setStyle(...)` replaces the style tree. Custom sources/layers/handlers added earlier are wiped unless you re-attach them.
```javascript
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.
## Reference Files
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 handling
- `references/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 Router
- `references/common-mistakes.md` — Common Mistakes 4-7 + Testing Patterns
- `references/token-management.md` — Token Management per bundler + Style Configuration
## When to Use This Skill
Invoke this skill when:
- 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
- Creating reusable map components for component libraries
- Debugging map initialization issues
- Adding Mapbox Search functionality
- Implementing proper cleanup and lifecycle management
- Converting between frameworks (e.g., React to Vue)
- Reviewing code for Mapbox integration best practices
## Related Skills
- **mapbox-cartography**: Map design principles and styling
- **mapbox-token-security**: Token management and security
- **mapbox-style-patterns**: Common map style patterns
## Resources
- [Mapbox GL JS Documentation](https://docs.mapbox.com/mapbox-gl-js/)
- [Mapbox Search JS Documentation](https://docs.mapbox.com/mapbox-search-js/)
- [create-web-app GitHub](https://github.com/mapbox/create-web-app)
From mapbox/mapbox-agent-skills at f71cd72, shown as plain text under its license: MIT (permissive). The license text is in LICENSE.md.
View SKILL.md on GitHub at f71cd72Files
- SKILL.md13 KB · d9152ec7e800
- AGENTS.md7.3 KB · 79e0dd6a0608
- evals/
- evals.json5.7 KB · 516747034a7a
- references/
- angular.md2.1 KB · a85d650855b2
- common-mistakes.md2.8 KB · 74bbfb51aa0c
- nextjs.md1.4 KB · 7e46f56273e8
- svelte.md895 B · c3b5613f1d79
- token-management.md2.1 KB · 122702ea848e
- vanilla.md3.0 KB · d5adeff6cc8b
- vue.md987 B · 07c2c2efdec4
- web-components.md6.4 KB · 1bfad4abb90e
11 files, 45 KB in total. Each file has a sha256 in the pin's manifest; the first 12 characters are shown.
Skill folder on GitHub at f71cd72More from Mapbox
mapbox-android-patterns
This skill provides official patterns for integrating Mapbox Maps SDK v11 on Android, covering setup, map initialization, markers, user location display…
Claude Code, Codex, Cursor +4 · about 2.5K tokens · pinned 6 days ago
mapbox-cartography
This skill provides cartographic expertise for designing effective maps with Mapbox, covering visual hierarchy, color theory, typography, and zoom strategies.
Claude Code, Codex, Cursor +4 · about 1.7K tokens · pinned 6 days ago
mapbox-data-visualization-patterns
This skill teaches the agent to implement data visualization patterns on Mapbox maps, including choropleth maps, heat maps, 3D extrusions, and animated data…
Claude Code, Codex, Cursor +4 · about 2.1K tokens · pinned 6 days ago
mapbox-flutter-patterns
This skill teaches agents the standard patterns for integrating the Mapbox Maps Flutter SDK into iOS and Android apps written in Dart.
Claude Code, Codex, Cursor +4 · about 2.3K tokens · pinned 6 days ago
mapbox-geospatial-operations
This skill guides agents on selecting appropriate geospatial tools from the Mapbox MCP Server based on problem requirements.
Claude Code, Codex, Cursor +4 · about 4.8K tokens · pinned 6 days ago
mapbox-google-maps-migration
This skill guides developers migrating from Google Maps Platform to Mapbox GL JS by comparing APIs, translating patterns, and highlighting architectural…
Claude Code, Codex, Cursor +4 · about 2.9K tokens · pinned 6 days ago
Related in Frontend and design
stitch::extract-design-md
Extracts a comprehensive design system document (DESIGN.md) by analyzing frontend source code including component files, stylesheets, Tailwind configs, and…
by GoogleOfficial publisher
Claude Code, Codex, Cursor +4 · about 3.3K tokens · pinned 6 days ago
remotion-saas
This skill helps build video generation applications using Remotion, a React framework for programmatic video creation.
by RemotionOfficial publisher
Claude Code, Codex, Cursor +3 · about 240 tokens · pinned 6 days ago
stitch::code-to-design
This skill converts existing frontend code (React, Vue, Angular, etc.) into a Stitch Design by extracting HTML, analyzing design systems, and uploading both…
by GoogleOfficial publisher
Claude Code, Codex, Cursor +4 · about 760 tokens · pinned 6 days ago
create-site
Guides users through building a complete Power Pages code site using React, Angular, Vue, or Astro, from initial requirements discovery through deployment.
by MicrosoftOfficial publisher
Contains scripts
Claude Code · about 29.1K tokens · pinned 6 days ago
portable-text-serialization
This skill enables rendering Portable Text content across multiple frameworks and output formats using the @portabletext library family.
by SanityOfficial publisher
Claude Code, Codex, Cursor +4 · about 940 tokens · pinned 6 days ago
crxjs
CRXJS is a Vite plugin for Chrome extension development that provides true hot-module reloading for popups, options pages, content scripts, and side panels.
by samberCommunity
Claude Code · about 2.3K tokens · pinned 6 days ago