I'm trying to use a API (https://tracker.gg/developers/docs/titles/csgo) and it's not working properly. When I try to make a request it asks for headers inside fetch (never used headers, only regular fetch and a url). Doing a little search I came up with:
async function fetchData() {
const response = await fetch('https://public-api.tracker.gg/v2/csgo/standard/profile/steam/76561198008049283', {
method: 'GET',
headers: {
'TRN-Api-Key': 'XXXX-XXXXX-XXX-XXXXXX-XXX', //here goes the key that I got for this app.
'Accept': 'application/json',
'Accept-Encoding': 'gzip',
},
mode: 'no-cors',
})
const second = await response.json();
console.log(second);
}
And when I call this function I get two errors inside console:
My knowledge is too basic at the moment and I'd like to get some insights of what I'm missing and what I could do to learn a little more about fetching data and how to do a validations when needed (like a authentication key)
Alright after tinkering with the request I realized something that should have been obvious...
The request you are trying to make should NOT occur in the browser unless you are on tracker.gg's site. Simply put you should be making this request from your app (server). Server to server will have no effect on cors.
Now lets get into the dirty details of why? Firstly your request will not include the 'TRN-Api-Key' header because it is not CORS-safelisted (as this brilliant answer tells us). Basically when you make the fetch request it removes the headers that are not safelisted and thus 'TRN-Api-Key' is removed from your header request and does not go to the API. Hence why you are seeing that "no api key being sent" because it isn't being sent. If you remove the mode: 'no-cors' then the key will be sent but fails CORS. If you don't have cors being used then the request must be made on tracker.gg to have the correct cors site.
Thus the developers of this project thought (and for good reason) that you would only be making this request on a server (It simply isn't a secure way to handle the api key having it on the front-end). If you instead make an api to work with their api your app can use your own custom server without knowing the api key (using some form of authentication of course).
Simply put it is Your game server's responsibility to take care of this API key and use it responsibiliy for the users of your app. Please read up on the docs of the api you are trying to access (also please read that answer as it is interesting).
Final answer: The API key should be used for server to server communcation as it was intended (not in the browser).