skip to Main Content

I’m new to web development and I’m creating a pure html/ css/ and js website and host it on a server. I have to use an API key in my js file and of course I don’t want it to be exposed to public. in my research I’ve learned that there is no easy way to actually mask my key and it can only be done with a proper backend.

Now my question is that is there a way to only have the api key on the backend and get it to the js file on front end to do the rest of the functions? if yes how?

Sorry if this question is repetitive but I couldn’t find an answer when I searched the forums.

myhtml.html


a regular html with <script></script> tag to myjs.js 
myjs.js


API="something"


initilize-library (API); 

// use the library

I haven’t try anything specific since most of the solutions I found were for frameworks such as react and not specific enough (They say you need a backend but not much on how to implement it and how to connect to what I already have which is an html, css , and js files)

I know we can have secret files and folders on hosting servers and I was thinking of storing my JS there but it didnt work

2

Answers


  1. I think a better approach than sticking your API directly into the code is to have the server side script call for the api from a separate file. (Php likely since you’re doing web dev).

    Login or Signup to reply.
  2. The only way that I can say is the Server-Side option, I already read all that the guys said, and I found that using localStorage is not safe, however, server-side may be a better option, you can call the script API (I mean except calling it like <script data-secret="123123"></script> you directly Build it and Inisialise it) directly.

    Another Option would be using Server-Side API, If the library you wish Inisialise has API, you can use the API to fetch the data and do your process on that, then, publish it into the Client-Side

    // in this example we want to get the Clients' IP Details from an API and show to them
    
    // code written in PHP
    
    $secret="123123";
    $data = file_get_contents("https://api.myip.example/v1/getIPdetails?secret=$secret&ip=1.1.1.1");
    
    echo $data;
    

    The only thing that users/clients can see on their screens is something like this.

    <!-- pre is like a tag for PHP, ignore it -->
    <pre>
    DATA WE GOT FROM THE API
    </pre>
    

    See!, No API key was exposed, also, clients don’t know where we got those details.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search