-1

I want my API key to be hidden and not publicly exposed.

I can think of a few ways of how to transfer the API key, through document.getelementbyId, .queryselector, input - hidden; but the API key will still be visible on the HTML page.

What is the best solution?

2
  • 5
    There's no solution if you insist on calling the API from user's browsers, the network inspector would show everything no matter how you try to obfuscate the key. Commented Oct 24, 2021 at 11:42
  • 3
    HTML is code running on the client and can never be hidden completely. What you need is a proper authentication mechanism such as JWT Commented Oct 24, 2021 at 11:47

2 Answers 2

3

The important factor to note here is that any JavaScript is run on the client's machine.

It is their machine and they are in full control of what runs on it.

You can minify, you can obfuscate, you can try every method possible but the API key will finally have to be formulated back somehow within the client's browser. And since the client's browser is theirs, you essentially have 0 control over what they can do with the API key. Plus the network tab in the client's browser will show all the requests the web application makes, including the one being sent with the API key.

If it is a third-party external API requiring an API key, the solution is to have an endpoint that does the authentication for you that acts as an interface between your front-end application and the API.

If this is your own API & you need to expose API endpoints that shouldn't be publically available, you will need a way to authenticate users. Starting off from JSON web tokens will be a great start but how you introduce JWTs will be massively dependent on your application.

Sign up to request clarification or add additional context in comments.

Comments

0

Put it in a .env file as a variable and export it to the file where you need it, .env files are not always shown to the browser.

Example; create a file api.env then in the file:

const key = "your API KEY goes here"

then export it (key) to the file where you need it.

.env files will never be shown to the front end

3 Comments

This is a good option hiding keys in source codes. Especially if it's shared and stored in repositories like Github. But in this special case, javascript on client side, it won't help.
Thank you for the clarification, but what are these "special cases" if you don't mind please.
Current topic, javascript on a client in browser. You can hide keys as .env variable in i.e. java code which is then compiled and run within an application server.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.