javascriptmapboxaccess-tokenmapbox-gl-jsmapbox-gl

Is there any way to hide the mapbox access token when initializing the map?


I'm using the mapbox API to display an interactive map. I made a kind of proxy to make the API requests outside the client side, to hide my access token. But when initializing the map (on the client side) I have no idea how to hide my access token.

This is the code I'm using to initialize the map. It works normally, but if someone inspects my code in the browser, or sees the code in the GitHub repository, they will have access to the token.

const accessToken = 'myKey';

mapboxgl.accessToken = accessToken;
const map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/mapbox/streets-v12',
    center: [-46.625290, -23.533773],
    zoom: 12,
    minZoom: 5,
    language: 'pt'
});

I've already put a URL restriction on the access token, but I don't know if that's enough to keep it protected.

Any solution is welcome. Thanks!


Solution

  • No, you can't hide it. But, assuming you're talking about your pk.ey... token (not a secret one), that's normal.

    Theoretically someone could access some data using your token and you could potentially be liable for the usage, but it doesn't really seem to happen in practice. You can rotate your token frequently (using the API for this) to reduce the impact of such abuse.

    This is the code I'm using to initialize the map. It works normally, but if someone inspects my code in the browser, or sees the code in the GitHub repository, they will have access to the token.

    They don't need to do those things - they can just look at the network tab. Every network request has your token in it.