leafletbasic-authenticationvector-tiles

How to add custom Authorization Header for tile requests in Leaflet


I am using the Leaflet.VectorGrid plugin to load pbf vector tiles on a leaflet map. The API that I retrieve the vector tiles requires an authorization header to be passed. In Mapbox GL js this can be resolved by using the transformRequest option. Example:

var baseLayer = L.mapboxGL({
    accessToken: token,
    style: 'myStyle',
    transformRequest: (url, resourceType)=> {
        if(resourceType == 'Tile' && url.startsWith(TILE_SERVER_HOST)) {
            return {
                url: url,
                headers: { 'Authorization': 'Basic ' + key }
            };
        }
    }
}).addTo(leafletMap);

How can I do something similar in Leaflet to bypass the 401 authorized message that I am getting?

For reference vector layer constructor from the plugin:

var vectorTileOptions = {
    rendererFactory: L.canvas.tile
};

var pbfLayer = L.vectorGrid.protobuf(vectorTileUrl, VectorTileOptions).addTo(leafletMap);

Solution

  • This Github issue https://github.com/Leaflet/Leaflet.VectorGrid/issues/89 describes a fetchOptions attribute you can pass when instantiating your layer that will be used as fetch options to retrieve the tiles.

    You should be able to do

    var vectorTileOptions = {
        rendererFactory: L.canvas.tile,
        fetchOptions: {
            headers: { 
                Authorization: 'Basic ' + key
            }
        }
    };
    
    var pbfLayer = L.vectorGrid.protobuf(vectorTileUrl, VectorTileOptions).addTo(leafletMap);