Music Downloader API Secured on the Frontend
Tags: showdev, webdev, security, react
Published: 2021-10-11 19:37:24

This YouTube music download API integration is done on the client side without a backend (I did not want to deal with backend infrastructure to hide the API key). I used [KOR Connect](https://korconnect.io) as the middleware platform (free) to quickly and easily integrate the API in a secure way. Firstly I will go over why I chose this route. 

We all know that API keys and connections can not be secured on the client side of an application. Hard coding API keys on the frontend is a quick and surefire way to have your API connection shutdown, API keys stolen, and have your API provider’s bill skyrocket. So what options are there if you do not want to maintain back end infrastructure? I will explore the recommended techniques for integrating 3rd party APIs into client side applications without having to build a backend. Then I will walk you through a step by step example of integrating YouTube’s private API to download music for free using [KOR Connect](https://korconnect.io).   

##**Ways of integrating 3rd party APIs without backend infrastructure:**

![Lambda image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j6ufft11nrvwv10knfon.png)
####**Serverless Functions as a backend proxy (AWS Lambda):** 
It is often recommended to use serverless functions to hide API keys for client side applications. Then the client can use this serverless function as a proxy to call the API through a new endpoint. The developer should also incorporate CORS to identify the header origin so that only the allowed domains are calling the proxy (to prevent unwanted calls to the proxy url from anywhere). This may seem secure but CORS only verifies browser calls and can be easily spoofed or can be called from outside of the browser. A malicious actor can still run up costs with a bot and have the endpoint shut down. Further issues with this technique can arise around provisioning AWS services to support the lambda functions like API gateways, roles, and permissions between cloud services, this can be very time consuming if you are not familiar with the cloud provider. 

![Netlify logo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0q72a1o7nbcsnp61f95k.jpg)
####**Netlify Functions (built on AWS Lambda):** 
Netlify Functions is a wrapper around AWS Lambdas, the main advantage to using this approach over the AWS provisioned proxy is an improved user experience and Netlify helps streamline the deployment for you. Netlify Functions remove the tasks associated with setting up an AWS account and other AWS services required to correctly integrate the API. Similar security issues persist with Netlify Functions as they do with setting up your own AWS provisioned proxy. Even with CORS setup the new Netlify endpoint can be called in unwanted ways and by unwanted agents. This leaves your API susceptible to being shut down, or having costs run up. Furthermore if you are not familiar with writing functions this could present an additional learning curve.  

![KOR Logo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fg4bj3hp3w310mkvzmcz.png)
####**[KOR Connect](https://korconnect.io):** 
KOR Connect is a new way for client-side web apps to integrate APIs. KOR Connect is the quickest way to secure API Keys and connect 3rd party APIs because you do not need to build infrastructure (AWS/ other cloud providers), or code functions (AWS and Netlify Functions). KOR Connect also uses AWS Lambda to secure API keys but the similarities between KOR Connect and the other options end there. The API key is secured on KOR Connect through a one click integration then a snippet containing a new public URL is copy-pasted into the developer’s code. This snippet that is placed into the frontend code contains Google’s Recaptcha V3 which is used as an attestation layer to confirm the origin of the endpoint call as well as block unwanted bot traffic. KOR Connect also has additional layers of security to further protect the API traffic from man-in-the-middle attacks. KOR Connect prevents endpoint calls from malicious actors with and without the browser, secures API keys, and blocks bot attacks. The public URL that is used in the code does not need to be hidden so this frees the developer from having to worry about API secrets ending up in the git repository, API secrets being exposed on the client, having to manually create wrappers around lambda functions, and worrying about unwanted endpoint calls being made. The current feature set KOR Connect is the best option for client-side web apps that want dynamic functionality but may not necessarily want user authentication. (Bonus it’s also free)


**Now let’s walk through integrating YouTube’s music download API using KOR Connect and React.js!** 

Let’s start with the API we want to use which is this [YouTube Mp3 API](https://rapidapi.com/ytjar/api/youtube-mp36/). 

If you already have a [KOR Connect](https://korconnect.io) account you can sign in [here](https://app.korconnect.io/login) or you can [create a new account](https://app.korconnect.io/SignUp).


Let’s start by creating an API connection on KOR Connect by clicking on the “+ Connect API” button. 
![Connect API](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e67o8omiy9frelsro5ub.png)

This will take us to connection details. The credentials needed here are copied directly from RapidAPI (or the API's documentation). More information regarding the API connection module [here.](https://kor-comunity.gitlab.io/kor-connect/adir/GETSTARTED.html)

![Connection details](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rvm9smswm6fip9xhyho6.png)

Once we have our API connection created we enter that connection by selecting view details.

![View details](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zzoe0e4hhi2ip4f6cf58.png)

If you would like, you can test your connection with Postman or another API testing tool.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uuq67dr9ic15n6l6d2x2.png)

Now you just have to copy the Single URL endpoint.


![CopyURL](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n9mdofxd4qtzq3skd1la.png)

And don't forget to copy the Header for your call.


![CopyHeader](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u2cv0pa3kbumxvez5blf.png)

Now we will copy the Single URL and Headers into our frontend.

```
  const handleCreateLink = async () => {
    setLoader(true);
    setInfo(null);

    let code;

    if (URL.includes("youtube.com")) {
      code = URL.replace("https://www.youtube.com/watch?v=", "");
    }

    if (URL.includes("youtu.be")) {
      code = URL.replace("https://youtu.be/", "");
    }

    /* We'll need this constant to make request */
    const timestamp = new Date().toUTCString();
    // You need to append the path of the endpoint you are calling to the KOR Connect base URI
    axios
      .get(`${process.env.REACT_APP_API_URL}/youtube-download/dl?id=${code}`, {
        headers: {
          /* Place your headers here: */
          timestamp,
          "x-api-key": process.env.REACT_APP_API_KEY,
        },
      })
      .then((response) => {
        setInfo(response.data);
        setLoader(false);
        setURL("");
      })
      .catch((error) => {
        console.log(error);
      });
  };
```
Once we are ready to deploy the project to production we have to change the Connection Mode from Test Mode to Production Mode, this will turn on additional security.

[Here](https://kor-comunity.gitlab.io/kor-connect/adir/TESTINGPRODUCTIONMODES.html) is some additional information pertaining to Testing and Production Modes on KOR Connect.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2si6c8z9ln88k7sfrok1.png)
___
>*__Note:__ If you are going to use the provided code from the project in the repo, remember that some of the values need to be modified to comply with the security layers for KOR Connect and your particular project (Connection URL, and usage token). The following image show the values that need to be changed.*

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0od9n5hw03tk8uvc2vd9.png)
___

Done! Now your application is ready to download music from YouTube, for free, and without ads. Try mine out [here](https://music-download.kor-test.com/)

![Finished app](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yjhnycnrywu02wcdtais.png)

#Additional Security

Let’s take a look at how KOR Connect provides an additional layer of security. Follow along if you would like to implement Recaptcha as an attestation layer amongst other security features.

You will have to navigate to the Additional Security section within the View Details of your API connection. 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ohpgbttqwz8x9frf4ef2.png)

Then you will have to turn on Additional Security. When Additional Security is turned on, the Security Type should read Single URL + Additional Security.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/10hd9usumcaq2llxjuew.png)

Now, scroll down to the snippets section and you will add the corresponding snippets of code to your project, in this case we are using ReactJS.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/20ddikncj9wksmkhvd2a.png)

Take a look at the following snippet:
You will need to install some dependecies.

```
npm install --save react-google-recaptcha-v3 axios
```

Add the following script to your index.js project:

```
import React from 'react';
import ReactDOM from 'react-dom';
import {
  GoogleReCaptchaProvider,
} from 'react-google-recaptcha-v3';

ReactDOM.render(
  <GoogleReCaptchaProvider reCaptchaKey={process.env.REACT_APP_RECAPTCHA_KEY}>
    <App />
  </GoogleReCaptchaProvider>,
  document.getElementById('root')
);
```

And then add the following script to your App.js project:

```
function App() {
  const [URL, setURL] = useState("");
  const [info, setInfo] = useState(null);
  const [loader, setLoader] = useState(false);

  // This constant is required for ReCaptcha, which is used by KOR Connect
  const { executeRecaptcha } = useGoogleReCaptcha();

  const handleCreateLink = async () => {
    setLoader(true);
    setInfo(null);

    let code;

    if (URL.includes("youtube.com")) {
      code = URL.replace("https://www.youtube.com/watch?v=", "");
    }

    if (URL.includes("youtu.be")) {
      code = URL.replace("https://youtu.be/", "");
    }

    /* We'll need this constant to make request */
    const token = await executeRecaptcha("submit");
    const timestamp = new Date().toUTCString();
    // You need to append the path of the endpoint you are calling to the KOR Connect base URI
    axios
      .get(`${process.env.REACT_APP_API_URL}/youtube-download/dl?id=${code}`, {
        headers: {
          /* Place your headers here: */
          token,
          timestamp,
          "x-api-key": process.env.REACT_APP_API_KEY,
        },
      })
      .then((response) => {
        setInfo(response.data);
        setLoader(false);
        setURL("");
      })
      .catch((error) => {
        console.log(error);
      });
  };
```

Now, all of the API calls are made to the public URL that KOR Connect provides. KOR Connect will act as a proxy to authenticate as well as send the API information. Furthermore, thanks to reCaptcha V3 (which is implemented automatically) and additional layers of security, several malicious attack vectors are blocked which enhances KOR Connects security.

>*__Note:__ If you need more information, click [here](https://github.com/Clemenshemmerling/music-download) to go to the repo.*

![Finished app](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yjhnycnrywu02wcdtais.png)