DEV Community

Cover image for Music Downloader API Secured on the Frontend
Clemenshemmerling for KOR Connect

Posted on • Updated on

Music Downloader API Secured on the Frontend

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 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.

Ways of integrating 3rd party APIs without backend infrastructure:

Lambda image

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

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

KOR Connect:

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.

If you already have a KOR Connect account you can sign in here or you can create a new account.

Let’s start by creating an API connection on KOR Connect by clicking on the “+ Connect API” button.
Connect API

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.

Connection details

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

View details

If you would like, you can test your connection with Postman or another API testing tool.
Alt Text

Now you just have to copy the Single URL endpoint.

CopyURL

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

CopyHeader

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);
      });
  };
Enter fullscreen mode Exit fullscreen mode

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 is some additional information pertaining to Testing and Production Modes on KOR Connect.

Image description


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


Done! Now your application is ready to download music from YouTube, for free, and without ads. Try mine out here

Finished app

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

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

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

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

npm install --save react-google-recaptcha-v3 axios
Enter fullscreen mode Exit fullscreen mode

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')
);
Enter fullscreen mode Exit fullscreen mode

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);
      });
  };
Enter fullscreen mode Exit fullscreen mode

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 to go to the repo.

Finished app

Top comments (1)

Collapse
 
johnny93u profile image
John Uil

This looks awesome! I'm going to try and built something with this for my GF.