How to Verify a Valid apiKey at runTime

582
0
04-22-2022 10:39 AM
RyanSutcliffe
Occasional Contributor II

I am finally moving our apps to use the new vector basemap services and have set up an ESRI API key to access the data. 

I would like to write a check at runtime that ensures that the token supplied for my app will indeed work. The logic I'm thinking is something like:

At Build: load api key token (from environment variables)

At Runtime: do a basic check that token works (isn't expired, lacking credits, works with referrer, supports the services I want to use it against (e.g. search, basemaps) etc)

- Make an `esriRequest` to some url endpoint that returns a brief description validating token or no and what services it works against.

- If token is invalid handle accordingly, fall back to other basemaps, disable search etc.

However I don't see anything anywhere in the ESRI API documentation discussing any such process. Of course I could test trying to fetch a particular basemap tile and see if an error message comes back but I'd rather just have a lightweight explicit "verify token" endpoint not just for a basemap but for the token itself. 

What I tried so far:

This'll work and fail with a bad token, but would like something a bit more descriptive:

require([
  "esri/config",
  "esri/request",
  "esri/Map",
  "esri/views/MapView",
  "esri/widgets/Search",
], function (esriConfig, esriRequest, Map, MapView, Search) {
   esriConfig.apiKey = "some-invalid-key-here";
   
    esriRequest(
    "https://basemaps-api.arcgis.com/arcgis/rest/services/styles/ArcGIS:Streets",
    {
      responseType: "json",
    }
  )
    .then(function (response) {
      let data = response.data;
      console.log(data);
    })
    .catch((err) => {
      console.log("whoops");
    });

 

Wondering if anyone has any advice before I go bother ESRI Canada support and/or make an idea suggestion about this. I also welcome feedback as to why my above approach idea might not be a good idea or is ill-advised.

 

 

0 Kudos
0 Replies