Search code examples
reactjsrestgithubjwt

Exposing API Endpoints in Frontend Application


I am building a frontend application using react and I am wondering whether it is risky to expose API endpoint URLs (ex: https://myapi.com/v1/getitems) on GitHub, assuming that the endpoint has several security measures that are not exposed such as CORS and JWT Token Bearer Authentication. I would assume not, since, if someone were to take the endpoint and send requests, they would need a token and be allowed to do so by CORS.

Is there any security risk in doing so?


Solution

  • Yes. Don't add the base url of your api on github in plain view. Even though you might have CORS and Authorization, that doesn't stop a malicious actor to keep spamming your back-end.

    What you do is create a .env file in your root folder. You can use a library like @beam-australia/react-env and there are others as well.

    You add in the .env file the values that are important for your environment and that are usually secrets, and you want them to not be visible in your code. You do it like so:

    API_URL="https://myapi.com/v1"
    

    And then you access this variable in your code with env("API-URL") ( in the @beam-australia/react-env case, but others libraries work the same). Keep in mind that you need to add .env in .gitignore so that the .env file is not pushed to github.

    Regarding requests, you can make one like so:

    fetch(`${env("API_URL")}/getitems`)
    

    This way your code will be stripped of the API's base url and if someone sees your code it will see only the endpoint, not the full url.