2

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.

Tejas_hooray
  • 606
  • 1
  • 6
  • 16
  • 1
    create server that would make a call to that api and make your react app call server instead? then just limit functionality you need with server interface. credentials won't be exposed this way to frontend – Yehor Androsov Nov 29 '20 at 18:45
  • 1
    Probably a HelloWorld level Security problem but it make sense :) – DevLoverUmar Nov 29 '20 at 18:51
  • Hello, thanks for your responses! However, I'm a bit confused at what you mean (I'm a beginner to React) and was wondering how I would actually implement this? Sorry if this question is very basic.. – Tejas_hooray Nov 29 '20 at 18:52

1 Answers1

1

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.

Chrissi Grilus
  • 1,099
  • 2
  • 9
  • 21
  • Thank you! So would one day to do this be to maybe check the IP address or domain of the caller and based on that return data? – Tejas_hooray Nov 29 '20 at 19:04
  • 1
    Not a safe way, IPs can be spoofed. Try to go the right way and read about one proper way of authentication. This would be: - Tokens like JSONWebTokens - Session-Cookies 2 approaches you will need to wrap your head around but its worth it. – Chrissi Grilus Nov 29 '20 at 19:07