DEV Community

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

Posted 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 select the snippet section.

Alt Text

Now select the react tab.
React tab

Now we will copy the first snippet into our frontend code to help us install all the dependencies that KOR Connect needs.

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

We will then paste the second snippet into our index.js file.

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import {
  GoogleReCaptchaProvider,
} from 'react-google-recaptcha-v3';


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

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
Enter fullscreen mode Exit fullscreen mode

The third snippet requires a little modification so that it works with our app, if you have any questions regarding this I left the repository code for this project so that you can use it and see the changes that I made here.

  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

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.

Alt Text


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 (Recaptcha ID, connection URL, and usage token). The following images show the values that need to be changed.
Recaptcha ID
User token connection URL


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

Finished app

Discussion (1)

Collapse
johnny93u profile image
John Uil

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