Integrate Authenticated Images with API Keys in ReactJS

This tutorial demonstrates how to Authenticated Images with ReactJS through BoltonSea API

Image depicting API lock

Prerequisite

Implementation

  1. Project Setup:

    • First, create a new React project using Create React App:
      npx create-next-app@latest
      cd my-app
    • Here are the customised options I used for this tutorial:
    ✔ What is your project named? … my-app
    ✔ Would you like to use TypeScript? … No
    ✔ Would ... code inside a `src/` directory? / Yes
    ✔ Would ... use Turbopack? (recommended)/ Yes
    ✔ Would ... import alias (`@/*` by default)? … No
    ✔ Creating a new Next.js app in my-app? Enter
    

  1. Basic Component (index.js):
  1. Library JS File (lib.js):

    • Create src/pages/lib.js to create a librayr file with functions to make API requests:
      // Triggers the API call to the backend service & applying the API_KEY with the request
      export async function getImageData(url, api_key) {
      const response = await fetch(url, {
      method: "GET",
      headers: { "X-API-KEY": api_key },
      responseType: "arraybuffer",
      });
      if (!response.ok) {
      console.error(`error: ${response.status}`);
      return null;
      }
      const blob = await response.blob();
      return imageBlobToBase64(blob);
      }
      // Converts an Image FileStream to Base64Blob
      async function imageBlobToBase64(blob) {
      return new Promise((onSuccess, onError) => {
      try {
      const reader = new FileReader();
      reader.onload = function () {
      onSuccess(this.result);
      };
      reader.readAsDataURL(blob);
      } catch (e) {
      onError(e);
      }
      });
      }
  2. Running the Application: Start the development server:

    npm run dev
  3. Browser Page

Conclusion

The screenshot above has a Chrome Broswer displaying what the HTML image tag with a base64 content as source (src).

The getImageData(url, api_key) function makes an API call by appending the API_KEY in the request, then passes the response's FileStreem blob into function imageBlobToBase64(blob) which converts the blob into a Base64 blog.

Note: