I'm working on a React.js project where I need to render a Mapbox map. I've created a custom map style in Mapbox Studio and want to use it in my application. To avoid exposing my Mapbox API key on the client side, I set up a Laravel backend using Laravel Sanctum to handle the Mapbox API requests.
Here's what I've done so far:
In Laravel, I created a MapboxController.php that retrieves the style using the Mapbox Styles API and my secret key.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
class MapboxController extends Controller
{
public function getMapStyle()
{
$response = Http::get('https://api.mapbox.com/styles/v1/{username}/{style_id}?access_token='.env('MAPBOX_API_KEY'));
return response()->json($response->json());
}
}
The Laravel API returns the response to my React app, that should initialize the map like this:
import React, { useEffect, useRef } from "react";
import mapboxgl from "mapbox-gl";
import "./Map.css";
const Map = () => {
const mapContainer = useRef(null);
useEffect(() => {
fetch("MY_BACKEND_URL")
.then((response) => response.json())
.then((data) => {
console.log(data); //Logging the response for debugging, the data arrives as expected
// Initializing the map with the data
const map = new mapboxgl.Map({
container: mapContainer.current,
style: data.style,
center: [9.984395, 51.145088],
zoom: 8,
attributionControl: false,
logoPosition: "bottom-left",
});
const attribution = new mapboxgl.AttributionControl({});
map.dragRotate.disable();
map.touchZoomRotate.disableRotation();
map.addControl(attribution, "bottom-right");
return () => map.remove();
})
.catch((error) => {
console.error("Fehler beim Laden der Karte: ", error);
});
}, []);
return <div ref={mapContainer} style={{ height: "100vh" }} />;
};
export default Map;
However, I'm encountering an issue where Mapbox still requires an API key on the client side. Here's the error message I receive in the console:
Map.js:32 Fehler beim Laden der Karte: Error: An API access token is required to use Mapbox GL. See https://docs.mapbox.com/api/overview/#access-tokens-and-token-scopes
at e.cS._makeAPIURL (mapbox.js:221:23)
at e.cS.normalizeStyleURL (mapbox.js:80:21)
at kr.loadURL (style.js:390:40)
at Map._updateStyle (map.js:2019:28)
at Map.setStyle (map.js:1994:25)
at new Map (map.js:658:18)
at Map.js:15:21
I'm looking for a way to render my map in React without having the API key in the frontend. Is there a way to securely use Mapbox in this scenario, where the API key remains hidden and only the necessary data is sent to the frontend?
I'm looking for a way to render my map in React without having the API key in the frontend
You can't, but that's ok. What you do instead if add URL restrictions to your API key