Secure API Key while Using Fetch?

I am going through the Async Javascript and HTTP Requests course. I just finished the Film Finder project where we used the fetch API function to retrieve data from a movie database web API ( The Movie Database (TMDB) (themoviedb.org)). In this lesson, it mentioned keeping the API key we receive after signup a secret. However, the api key is passed in clear text when an asynchronous request is made in Javascript. Anyone using the web app could view this key. How would we prevent someone from stealing this API key in a real-world app?

Project -
Learn JavaScript Syntax: Requests | Codecademy

Thanks!

In real world app, fetch and xmlhttprequests are made by the back end. The front end isn’t enough to produce an application.

2 Likes

I would note @net3018099873 that depending on the hosting provider you are using, many of them such as Heroku/Vercel/Netlify etc include the ability to run Serverless Functions, this would allow you to make requests privately without the client ever having access to the API key, what happens is:

  • Your app calls the serverless function, which makes a request to the API
  • The serverless function returns the data back into your client application
  • Since the serverless function runs securely on the hosting providers servers and is responsible for the requests, the API key is never handled directly by the client, and is therefore secure.

Aside from that, @valeriadaffarra is absolutely correct, it is impossible to securely keep secrets on the front end alone, as they could always be seen in the “Network” tab of dev tools when a network request is made, or even by directly examining it. While methods like environment variables will keep the secret out of the code/repo, it is not sufficient on a sole front-end once the app is actually running in the browser.

While you may be more limited, I personally would argue it absolutely is possible, and there’s plenty you can do with a front end.

2 Likes

If you have a React App that could be avoided by using the .env file for API keys. From what I know your keys will neither be revealed in your repo nor in the dev tools as clear text when saving the API keys in that file.

I believe that (since the key would be sent in the HTTP headers of any requests to the API), that you would be able to examine the network request client site via dev tools, look at the headers and expose the token.

That said, I’m not certain and will have to test that, by all means please correct me if I’m wrong, more than happy to get corrected and learn from it! :slight_smile:

Edit: Found this stackoverflow Q&A which seems to concur that there’s no way to safely use secrets client site.

1 Like

Ah, ok, thanks for the link.
Just had a look at my App: I’m using basic authentication with base64 encoding. So I could not find my key as clear text anywhere in the dev tools, but the encoded key can be found under ‘Request Headers: authorization’.

1 Like