Secure API Call in React JS

3.5k views Asked by At

I have an API that I want to make a request to from my frontend, which is built using React. However, I don't want anyone to be able to see the API call in my code, because if someone just opens the inspect window, then they can see the API call. I've thought of perhaps adding some sort of header to be sent as authentication in the request, but that doesn't work either because you can just see the code if you inspect the site.

How would I do this? My API returns a private key that I can't just store in a variable directly within my code.

Sorry if this question doesn't make sense, but I appreciate all the help.

1

There are 1 answers

2
Chrissi Grilus On BEST ANSWER

Your frontend code is insecure and observable by default. There is no secret in the frontend. If your API returns confidential data that should only be accessed by the appropriate user you will have to implement authentication of any sort.

A user would then for example provide a password in order to call the API or he logged in before and got a token (e.g. JWT) that he sends with every request to authenticate. There is a user identity on every request then and your backend can decide if the user is allowed to get that private key.

If you really really want to make it difficult for someone to see your frontend code your router might provide a feature like "protected routes" that require such a token in order to access certain routes of your application. It will still always be possible to get the frontend code because the business logic has to stay on the backend.