Authentication overview

Mapbox GL JS, a client-side JavaScript library for interactive web maps, authenticates requests to Mapbox services primarily through the use of public access tokens. These tokens authorize an application to fetch map styles, vector tiles, geocoding results, and other data from Mapbox APIs. Unlike server-side APIs that might use secret keys or OAuth flows, Mapbox GL JS operates in the browser environment, necessitating a public-facing token for client-side requests. The token must be included with every request made to Mapbox services to ensure proper authorization and to track usage against an account’s quota.

Each access token is associated with a Mapbox account and can be configured with specific scopes and restrictions to enhance security. This allows developers to control which Mapbox resources an application can access and from which origins it can make requests. Understanding how to generate, manage, and secure these tokens is fundamental for deploying Mapbox GL JS applications effectively and preventing unauthorized usage.

Supported authentication methods

Mapbox GL JS primarily supports one method for authentication in client-side web applications: public access tokens. These tokens are designed for direct use in browser environments.

Public Access Tokens

Public access tokens are alphanumeric strings that uniquely identify an application and grant it permission to access specific Mapbox services. When Mapbox GL JS makes a request to a Mapbox API (e.g., to load a map style or retrieve vector tiles), this token is included in the request URL or headers. The Mapbox API then validates the token against the associated account and its configured permissions. Mapbox provides detailed documentation on understanding Mapbox access tokens.

These tokens are classified as “public” because they are exposed in the client-side code of web applications. Because of this exposure, it is critical to apply restrictions to tokens used in production environments to mitigate potential misuse. Restrictions can include specifying allowed URLs (HTTP referrers) or IP addresses, and limiting the scope of services the token can access.

While Mapbox GL JS itself does not directly implement complex authentication flows like OAuth 2.0 or API key hashing, it integrates into broader web security contexts. For instance, a server-side application might generate temporary, restricted access tokens for clients after a user authenticates via OAuth 2.0 or another identity provider, and then pass these tokens securely to the client-side Mapbox GL JS application. However, the direct interaction between Mapbox GL JS and Mapbox services still relies on the presence of a valid access token.

Authentication methods table

Method When to Use Security Level
Public Access Tokens Client-side web applications requiring direct access to Mapbox services (e.g., loading maps, geocoding requests from browser). Moderate (requires careful restriction configuration)
(Server-side token generation with client delivery) When enhanced security or dynamic token management is needed; server generates and securely delivers restricted tokens to clients. High (depends on server-side security implementation)

Getting your credentials

To use Mapbox GL JS, you need a Mapbox account and a public access token. Follow these steps to obtain your credentials:

  1. Create a Mapbox Account: If you don't already have one, sign up for a free account on the Mapbox website.
  2. Navigate to the Access Tokens Page: Once logged in, go to your Mapbox Account Dashboard. On the left sidebar, look for “Access tokens” under the “API & services” section.
  3. Use Default Public Token or Create a New One: Mapbox provides a “Default public token” upon account creation. You can use this for development and testing. For production applications, it is recommended to create a new access token by clicking the “Create a token” button.
  4. Configure Token Settings:
    • Name: Give your token a descriptive name (e.g., “My Web App Production Token”).
    • Scopes: Select the necessary scopes for your application. For Mapbox GL JS to display maps, the styles:read and tiles:read scopes are typically required. Add other scopes like geocoding:search if your application uses geocoding services. Only grant the minimum necessary permissions.
    • Restrictions: This is crucial for public tokens.
      • URL restrictions: Add the exact URLs (e.g., https://yourdomain.com/*, http://localhost:8000/*) from which your application will be making requests. Use wildcards (*) for subdomains or paths if appropriate. This prevents the token from being used on unauthorized websites.
      • IP restrictions: While less common for client-side applications, you can also restrict tokens to specific IP addresses if your application runs from a fixed set of servers or environments.
  5. Save and Copy Token: After configuring, click “Create token” or “Save token”. Mapbox will display the token string. Copy this string immediately as it may not be fully displayed again for security reasons.

Authenticated request example

Mapbox GL JS requires the access token to be set globally or passed directly to the map initialization. The most common method is to set it globally using mapboxgl.accessToken before any map instances are created.

Setting the access token globally

import mapboxgl from 'mapbox-gl';

// Set your Mapbox access token here
// Replace 'YOUR_MAPBOX_ACCESS_TOKEN' with the actual token you obtained
mapboxgl.accessToken = 'YOUR_MAPBOX_ACCESS_TOKEN';

const map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/mapbox/streets-v12', // Replace with your desired style URL
    center: [-74.5, 40],
    zoom: 9
});

map.on('load', () => {
    console.log('Map loaded successfully with authentication.');
});

Setting the access token per map instance (less common)

While less common, you can also pass the access token directly to the mapboxgl.Map constructor. This can be useful for applications managing multiple maps with different tokens, though it adds complexity.

import mapboxgl from 'mapbox-gl';

const map1 = new mapboxgl.Map({
    container: 'map1',
    accessToken: 'YOUR_MAPBOX_ACCESS_TOKEN_FOR_MAP1',
    style: 'mapbox://styles/mapbox/streets-v12',
    center: [-74.5, 40],
    zoom: 9
});

const map2 = new mapboxgl.Map({
    container: 'map2',
    accessToken: 'YOUR_MAPBOX_ACCESS_TOKEN_FOR_MAP2',
    style: 'mapbox://styles/mapbox/satellite-v9',
    center: [-73.9, 40.7],
    zoom: 10
});

Environment variables for tokens

For development, avoid hardcoding tokens directly in your source code. Instead, use environment variables. With build tools like Webpack or Vite, you can inject these variables at build time. For example, using a .env file:

// .env file
VITE_MAPBOX_ACCESS_TOKEN=YOUR_SECRET_TOKEN_HERE
// In your JavaScript file (example with Vite)
mapboxgl.accessToken = import.meta.env.VITE_MAPBOX_ACCESS_TOKEN;

const map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/mapbox/streets-v12',
    center: [-74.5, 40],
    zoom: 9
});

This approach keeps your token out of version control and allows for different tokens across development, staging, and production environments.

Security best practices

Given that Mapbox GL JS access tokens are public, implementing robust security measures is essential to prevent unauthorized use and protect your Mapbox account. Mapbox itself provides guidance on securing access tokens.

  • Restrict Tokens by URL (HTTP Referrer): Always set URL restrictions for your public tokens in the Mapbox dashboard. This limits the domains or subdomains from which your token can be used. For example, if your application is hosted at https://www.example.com, add https://www.example.com/* as a URL restriction. This is the most critical security measure for client-side tokens.
  • Restrict Scopes: Grant only the minimum necessary permissions (scopes) to your access tokens. For a basic map display, styles:read and tiles:read might suffice. Avoid granting broad permissions like secrets:read or uploads:write to public tokens.
  • Use Separate Tokens for Different Environments: Create distinct tokens for development, staging, and production environments. This allows you to revoke a compromised token for one environment without affecting others.
  • Avoid Hardcoding Tokens: Do not hardcode access tokens directly into your source code, especially for production builds. Use environment variables (e.g., process.env.MAPBOX_ACCESS_TOKEN with a build tool like Webpack, or import.meta.env.VITE_MAPBOX_ACCESS_TOKEN with Vite) to inject tokens at build time.
  • Rotate Tokens Regularly: Periodically rotate your access tokens, especially for long-running applications. This mitigates the risk associated with a token being compromised over time.
  • Monitor Usage: Regularly check your Mapbox account dashboard for unusual API usage patterns. Spikes in requests or usage from unexpected regions could indicate a compromised token.
  • Implement HTTPS: Ensure your application is served over HTTPS. This encrypts all communication between the client and server, including the transmission of your access token to Mapbox APIs, protecting it from eavesdropping. The Mozilla Developer Network provides information on HTTPS.
  • Server-Side Token Generation (Advanced): For applications requiring the highest level of security or dynamic access control, consider generating short-lived, highly restricted Mapbox tokens on your server after a user has authenticated. The server then securely passes this temporary token to the client-side Mapbox GL JS application. This prevents the primary, long-lived token from ever being exposed directly in the browser.