Request Traffic-Aware Driving Routes with Mapbox Directions API
Request traffic-aware driving routes, validate GeoJSON responses, and implement quota-safe fallbacks with the Mapbox Directions API.
29 Apr 2026, 09:02 UTC

Problem and takeaway
You need a driving route between two coordinates, but Mapbox Directions API responses vary by profile, and an HTTP 200 alone does not guarantee a usable route. If you request traffic-aware data without validating the response shape, your UI can show missing geometry or misleading ETAs. The practical approach is to request `mapbox/driving-traffic` with `depart_at`, validate that the first route contains a LineString geometry and the expected leg count, and fall back to `mapbox/driving` or a cached route when traffic data, quota, or authentication fails.
Prerequisites
- A Mapbox access token with Directions read scope. Check your Mapbox account dashboard for the exact scope name; do not hard-code a secret token in client-side code. Call the API from a backend or through a proxy so the token never reaches a browser or mobile app.
- Waypoints in WGS84 longitude,latitude order, joined by semicolons. Reversed coordinates are a common cause of `NoRoute` or implausible geometry.
- A profile decision. `mapbox/driving` returns time-independent routes. `mapbox/driving-traffic` adds traffic-aware duration but can increase latency and usage cost. Confirm current profile names and pricing in your account dashboard before production use.
Build the request
Run the example from a backend or terminal. Replace the placeholders with your own coordinates and token.
curl "https://api.mapbox.com/directions/v5/mapbox/driving-traffic/-73.9851,40.7588;-74.0060,40.7128?geometries=geojson&overview=full&steps=true&depart_at=now&access_token=MAPBOX_ACCESS_TOKEN"
- Where to run: any environment with outbound HTTPS to `api.mapbox.com`. Use a server-side process if the token is secret.
- Permissions: the access token must include Directions read access.
- Placeholders: replace the coordinate pair with your origin and destination; replace `MAPBOX_ACCESS_TOKEN` with your token.
- Expected checks: covered in the next section.
- Risks: exposing the token in client code or logs; reversed coordinates causing `NoRoute`; treating traffic duration as a guaranteed arrival time.
The `geometries=geojson` parameter returns GeoJSON instead of encoded polyline. `overview=full` returns the complete route geometry. `steps=true` includes turn-by-turn maneuvers. `depart_at=now` requests traffic-aware timing based on current conditions.
Validate the response
Do not stop at HTTP 200. Parse the JSON body and assert the following:
- `code` is `Ok`.
- `routes` contains at least one entry.
- `routes[0].geometry.type` is `LineString`.
- `routes[0].legs.length` equals the number of waypoints minus one.
- `routes[0].distance` and `routes[0].duration` are greater than zero.
- When `steps=true`, each leg's `steps` array contains maneuver locations.
Example validation logic:
if (response.code !== "Ok" || !response.routes?.length) {
throw new Error("No usable route");
}
const route = response.routes[0];
if (route.geometry.type !== "LineString") {
throw new Error("Unexpected geometry type");
}
if (route.legs.length !== waypoints.length - 1) {
throw new Error("Leg count mismatch");
}
Handle failures and fallbacks
- `429` or `5xx`: retry with exponential backoff and jitter. Do not retry immediately in a tight loop.
- `401` or `403`: fail closed. Refresh or rotate credentials through operations; do not keep retrying with the same bad token.
- `NoRoute`: verify coordinate order is longitude,latitude; simplify or reorder waypoints and retry once.
- Traffic data unavailable or quota exhausted: fall back from `mapbox/driving-traffic` to `mapbox/driving`, then to a cached route for the same origin/destination and time bucket if one exists.
- High-frequency routing: use caching or the Matrix API instead of repeated Directions calls; quotas and pricing vary by account.
Limitations and verification
- Traffic-aware duration depends on `depart_at` and current traffic data. Present it as an estimate, not a guaranteed arrival time.
- Minimize retention of raw waypoints and route results because trips can reveal sensitive locations. Apply access controls and retention limits.
- Profile names, rate limits, and pricing can change. Re-check your Mapbox account dashboard after API or plan changes.
- No state-changing rollback is required for the API call itself. If your application persists route geometry, revert to the previously cached route or disable the traffic profile behind a feature flag.
Verification steps:
- In staging, request one known routable pair and assert `code` is `Ok`, exactly one route, `LineString` geometry, and leg count equal to waypoint pairs minus one.
- Compare `mapbox/driving` and `mapbox/driving-traffic` for the same pair and departure time. Confirm traffic-related values appear only where expected and differences are plausible.
- Force failure modes with an invalid token and an unroutable coordinate. Verify backoff on `429`/`5xx`, fail-closed behavior on `401`/`403`, and no token leakage in logs or client errors.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.