Mapbox GL: How can I handle invalid/expired access tokens?

Viewed 61

I've implemented Mapbox GL:

script.src = 'https://api.mapbox.com/mapbox-gl-js/v2.8.2/mapbox-gl.js';
script.onload = function() {
    mapboxgl.accessToken = 'invalid_token';
    map = new mapboxgl.Map({
        container: 'mapsection', // container ID
        style: 'mapbox://styles/mapbox/streets-v11' // style URL
    });
}

If the access token is invalid or expired then a message is shown in the console, but how can I handle this in my code? I've tried both try .. catch and map.on('error'), but neither acknowledge there is an error. Any operations on the map are performed without errors, but there is just nothing to see on the page.

Alternatively, is there an API to validate a given token?

2 Answers

I don't know for sure, but if you take one of the URLs that are being requested (by looking in developer tools), and using fetch to query that URL, you will probably get back either 200 for a correct token, or 401 or 403 for an invalid token (or other issue).

Looks like I was almost there, but just made a small mistake. It is indeed the map.on('error') event handler I need to use:

script.src = 'https://api.mapbox.com/mapbox-gl-js/v2.8.2/mapbox-gl.js';
script.onload = function() {
    mapboxgl.accessToken = 'invalid_token';
    map = new mapboxgl.Map({
        container: 'mapsection', // container ID
        style: 'mapbox://styles/mapbox/streets-v11' // style URL
    });
    map.on('error', (response) => {
        alert(response.error.message)
    });
}
Related