A ReactJS and Firebase deployed website based on spotify and data fetching using SpotifyAPI’s

We are going to build a Spotify Clone on React using the Spotify API

The first question should be Why do we even need a App clone when we already have a Spotify API.

The Answer is because App cloning is a useful technique used by a lot of companies to save time.Designing a App from scratch takes a lot of time and investment 

So in this article we are going to create our own spotify clone taking help from the Spotify API.

The prerequisite for creating this clone is a basic knowledge of React and Firebase 

React 

React is a Javascript library that helps us in building interactive and fast web and mobile applications. It was created by Jordan Walke ( software engineer at Facebook. )

React is Developers favourite framework because we can create reusable components which means less coding and more functionality.Also because of the use of Virtual DOM it is faster. Since it compares the current and previous state and only updates the changed component.

You can read more about react on https://reactjs.org/

Firebase 

When you have a mobile or web application you need a backend server to store the data.also in most of the apps you need user authentication.Also for a successful app you need to spread the word to get some new users.

Firebase has all the tools you need to build an app.

Using firebase you can do all kinds of authentications.

It Provides real time database, file storage and hosting solutions.

Helps you Acquire new users using invites,dynamic links and adWords.

Helps you Analyze your app to let you know how your app is performing.

You can read more about the firebase on https://www.javatpoint.com/features-of-firebase

Now How to Actually Create the App.

The very first thing we need is to set up everything ,this includes Setting up the Firebase , the React Project and the Spotify API.

1 – Setting up all the environments.

  1. Setting up the React project
  2. Setting up the Firebase
  3. Setting up Spotify Web API 

a. Setting up the React project

Prerequisite -NPM(Node Package Manager) installed

For the Project we are going to use Visula Studio as the code editor

Step 1 – run the following command on the terminal

npx create-react-app Spotify-Clone

This command will create a project with the name Spotify-Colne (it usually takes a few minutes to create the project.)

The folder Structure looks like this

Spotify_clone

├── README.md

├── node_modules

├── package.json

├── .gitignore

├── public

└── src

Step 2 – Once the project is created you can open the project in visual studio .

To start the project you can simply run the common “npm start” on the visual studio Terminal.this will open the project on your default browser on localhost:3000.

Or You can use https://stackcodify.com:3000  to open the web page on any browser 

Step 3 – Everything that you see on the web page right now is because of the code in the App.js file.

This is how the App.js looks like in the start 

 import logo from "./logo.svg";
 import "./App.css";
 function App() {
   return (
     <div className="App">
       <header className="App-header">
         <img src={logo} className="App-logo" alt="logo" />
         <p>
           Edit <code>src/App.js</code> and save to reload.
         </p>
         <a
           className="App-link"
           href="https://reactjs.org"
           target="_blank"
           rel="noopener noreferrer"
         >
           Learn React
         </a>
       </header>
     </div>
   );
 }
 export default App; 

Delete Everything in  the App.js  return and delete all the content of App.css(We don’t need any of it)

This is how the App.js will look like 

 import "./App.css";
 function App() {
   return (
     <div className="App">
     </div>
   );
 }
 export default App; 

b. Setting up the Firebase

Step 1 – go the the  https://firebase.google.com and signup/login using your google account

Step 2- one you are logged in click on “Add Project” and enter a project name. 

Step 3- follow the instructions afterwards and you will see the message “your new project is ready”

We are done here. We will use this later to deploy our app.

c. Setting up the Spotify API

Step 1 – go the https://developer.spotify.com/

Step 2 – go on the dashboard and click on “create an app” 

You will see a new pop up

Step 3 – give the app a name and app description agree to all terms and condition

Step 4 – once you have created the app copy the “ client id” and save it (we will need this later)

Step 5 – go to the “edit setting option and change the redirect URL to  https://stackcodify.com:8000/  and save the changes .

All the setups are done and we are ready to start creating our Spotify clone 

2 – create your logic page 

For Login page we need to create two files a ‘login.js’ and ‘login.css’

  • In Login.js create a login component
  • Import Login.js in app.js “import Login from “./Login”;”
  • Create a new div in login.js with the classname “login”
  • Add logo in the div
  • Add a link  <a>LOG IN WITH SPOTIFY</a>

 import React from "react";
 function Login() {
   return (
     <div className="login">
       {/* Spotify Logo */}
       {/* <imgsrc="https://getheavy.com/wp-content/uploads/2019/12/spotify2019-830x350.jpg" /> */}
       {/* Login with Button */}
       <a href={loginUrl}>LOG IN WITH SPOTIFY</a>
     </div>
   );
 }
 export default Login; 

Now it’s time to add some styling to the login component

  • In login.css add the following code to add styling 
 .login {
   display: grid;
   place-items: center;
   height: 100vh;
   background-image: url("https://getheavy.com/wp-content/uploads/2019/12/spotify2019-830x350.jpg");
   background-color: #123;
 }
 .login > img {
   width: 100%;
 }
 .login > a {
   padding: 20px;
   border-radius: 99px;
   background-color: #1db954;
   font-weight: 800;
   color: white;
   text-decoration: none;
   -webkit-border-radius: 99px;
   -moz-border-radius: 99px;
   -ms-border-radius: 99px;
   -o-border-radius: 99px;
 } 

Next we are going to render this login component to the App.js by adding <Login/>

In the App.js <div>

 import React, { useEffect, useState } from "react";
 import "./App.css";
 import Login from "./Login";
   return (
     <div className="App">
       {token ? <Player /> : <Login />}
       {/* Spotify Logo*/}
     </div>
   );
 }
 export default App; 

Now the login page is ready and we are good to go on the second step.

Next step is where should the web application go when the user enters the login link we created.

Obviously we need to authorize the user.now the good part about using an api is that we don’t have to worry about the authentication.The spotify API will take care of the authentication.

How?

Let’s see that in the next step

3 – authentication 

 authentication  has 3 steps

i- click on the login button

ii- redirect to the spotify login page(where spotify api will authenticate the user

Iii- redirect to the home page one the user is authenticated.

To do so following steps are required

  • Create a new file called spotify.js
  • Add three variable endPoint,redirect and client id 
  • Add scope array
  • Create a URL using the information we created above
 export const endPoint = "https://accounts.spotify.com/authorize";
 const redirect = "https://localhost:3000/";
 const clientId = "6ea5088f640e4862a0c09ecd6e689bc8";
 const scopes = [
   "user-read-currently-playing",
   "user-read-recently-played",
   "user-read-playback-state",
   "user-top-read",
   "user-modify-playback-state",
 ];
 export const loginUrl = `${endPoint}?client_id=${clientId}&redirect_uri=${redirect}&scope=${scopes.join(
   "%20")}&response_type=token&show_dialog=true`; 

 export const loginUrl = `${endPoint}?client_id=${clientId}&redirect_uri=${redirect}&scope=${scopes.join(
   "%20")}&response_type=token&show_dialog=true`; 
  • Now use this loginUrl in the login.js such that when user clicks on the ‘login’ button the page redirects to the spotify app for authentication 

Now the ‘Login with Spotify’ button works button and it will redirect you to the spotify app in the browser where you will be asked to authenticate.Once the authentication is done you will be back to your Spotify clone.

You will notice URL has a token.we need this token to to authenticate user.

To do so we are gonna add a new function in the spotify.js file to extract token from the url

 export const authEndPoint = "https://accounts.spotify.com/authorize";
 const redirectUri = window.location.href;
 const clientId = "6ea5088f640e4862a0c09ecd6e689bc8";
 const scopes = [
   "user-read-currently-playing",
   "user-read-recently-played",
   "user-read-playback-state",
   "user-top-read",
   "user-modify-playback-state",
 ];
 export const ExtractToken= () => {
   return window.location.hash
     .substring(1)
     .split("&")
     .reduce((initial, item) => {
       let parts = item.split("=");
       initial[parts[0]] = decodeURIComponent(parts[1]);
       return initial;
     }, {});
 };
 export const loginUrl = `${authEndPoint}?client_id=${clientId}&redirect_uri=${redirectUri}&scope=${scopes.join(
   "%20"
 )}&response_type=token&show_dialog=true`; 

Now if the user is authenticated we get the token and  the webpage should move to player but if the user is not logged it it will go back to the login page.

To do so we are gonna write set of code in App.js that will allow the user to go on the player page if the authentication was successful or else back to login page.

  • We will use useEffect block to make sure that the code runs only when the page is Loaded. 
  • Next using the ExtractToken() function we will save the token in the state.
  • If the token exist while rendering, the next page (player) will be shown (player is made in the future steps)
  • If the token does not exist the user will see the login page 

Note –  URL needs to be reset so that token is not visible in the URL

 import React, { useEffect, useState } from "react";
 import "./App.css";
 import Login from "./Login";
 import {ExtractToken } from "./spotify";
 function App() {
   const [token, setToken] = useState(null);
   useEffect(() => {
     const hash = ExtractToken();
     window.location.hash = "";
     const _token = hash.access_token;
     if (_token) {
       setToken(_token);
            });
   return (
     <div className="App">
       {token ?<h1>Successfully logged it<h1> : <Login />}
       {/* Spotify Logo*/}
     </div>
   );
 }
 export default App; 

4 – connect to Spotify API

Only logging in is not good enough for a spotify clone.We need to connect this to the spotify api to be able to do all the other tasks.To do so first we are going to install the spotify api into our project to do so run the following command on your terminal “npm install spotify-web-api-js”.

It is a wrapper around the spotify api that allows us to connect to the spotify services in an easy way.

Now to use this api 

  • we are going to import the api into App.js
  • Initialize an object named  ‘Spotify’ using the SpotifyWebApi constructor
  • Now if the Token exist we are going to set it equal to the Spotify Access token using setAccessToken() function
 import React, { useEffect, useState } from "react";
 import "./App.css";
 import Login from "./Login";
 import {ExtractToken } from "./spotify";
 import SpotifyWebApi from "spotify-web-api-js";
 const spotify = new SpotifyWebApi();
 function App() {
   const [token, setToken] = useState(null);
   useEffect(() => {
     const hash = ExtractToken();
     window.location.hash = "";
     const _token = hash.access_token;
     if (_token) {
       setToken(_token);
 spotify.setAccessToken(_token)
            });
   return (
     <div className="App">
       {token ?<h1>Successfully logged it<h1> : <Login />}
       {/* Spotify Logo*/}
     </div>
   );
 }
 export default App; 

5 – Solve the Prop drilling problem

Now before solving the Prop drilling problem we first need to understand it.

This problem arises when you have components on one another and when you try to pass or extract data from the bottom but you have to go through all the components from top to bottom.

For example in our project we have app.js and then on the second layer we have login and then we will add a player component. Now this player component will have multiple components like a sidebar , a footer and a main body.

Now these multiple levels of components cause prop drilling.

There are many alternatives, one of them is Context API which we are using in this project

To do so first we are going to add a DataLayer 

1 – create a file DataLayer.js

2 – 

6- Adding more components in the App

After the authentication The user goes to the Player component 

The Player component  will have 3 main component 

  • Sidebar – it will show the playlist 
  • Body – where user will see the current song 
  • Footer – it consists the play and  pause buttons 

For all the components mentioned above we are going to create js and css files

Let’s start with the Sidebar

Before working on Sidebar we are going to create a Sidebaroptions component to wrap icon and option .

To do so create a “sidebarOption.js” and “sidebarOption.css”

sidebarOption.js

 import React from "react";
 import "./SidebarOption.css";
 function SidebarOption({ option, Icon }) {
   return (
     <div className="sidebarOption">
       {Icon && <Icon className="sidebarOption__icon" />}
       {Icon ? <h4>{option}</h4> : <p>{option}</p>}
     </div>
   );
 }
 export default SidebarOption; 

sidebarOption.css

 .sidebarOption {
   display: flex;
   cursor: pointer;
   align-items: center;
   height: 40px;
   color: grey;
   transition: 200ms color ease-in;
 }
 .sidebarOption:hover {
   color: white;
 }
 .sidebar > hr {
   border: 1px solid #282828;
   width: 90%;
   margin: 10px auto;
 }
 .sidebarOption__icon {
   padding-left: 10px;
   padding-right: 10px;
 }
 .sidebarOption > p {
   margin-top: 10px;
   margin-left: 20px;
   font-size: 14px;
 } 

Sidebar has three sidebar options “home” , “search”, “option” and “your library”

And a playlist. To get the playlist we are going to map it with all the playlist in the Spotify API.

Sidebar.js

 import React from "react";
 import "./Sidebar.css";
 import HomeIcon from "@material-ui/icons/Home";
 import SearchIcon from "@material-ui/icons/Search";
 import LibraryMusicIcon from "@material-ui/icons/LibraryMusic";
 import SidebarOption from "./SidebarOption";
 import { isCompositeComponent } from "react-dom/test-utils";
 import { useDataLayerValue } from "../DataLayer";
 function Sidebar() {
   const [{ playlists }, dispatch] = useDataLayerValue();
   return (
     <div className="sidebar">
       <img
         className="sidebar__logo"
         src="https://getheavy.com/wp-content/uploads/2019/12/spotify2019-830x350.jpg"
         alt=""
       />
       <SidebarOption Icon={HomeIcon} option="Home" />
       <SidebarOption Icon={SearchIcon} option="Search" />
       <SidebarOption Icon={LibraryMusicIcon} option="Your Library" />
       <br />
       <strong className="sidebar__title">PLAYLISTS</strong>
       <hr />
       {playlists?.items?.map((playlists) => (
         <SidebarOption option={playlists.name} />
       ))}
       <SidebarOption option="Hip-hop" />
     </div>
   );
 }
 export default Sidebar; 

Note – to get the icons the “Material UI Icons package” is used 

So you need to download the package using the following command 

npm install @material-ui/core @material-ui/icons

Now it’s time to give some styling to the sidebar component 

 .sidebar {
   display: flex;
   flex-direction: column;
   flex: 0.2;
   padding-left: 10px;
   padding-right: 10px;
   min-width: 230px;
   height: 100vh;
   color: white;
   background-color: #040404;
 }
 .sidebar__title {
   margin-left: 10px;
   padding: 5px;
   font-size: 12px;
 }
 .sidebar__logo {
   margin-right: auto;
   object-fit: contain;
   height: 70px;
   padding: 10px;
 } 

Now similarly you need to create the body component and the footer component.

(hint : you can further divide the body component into smaller component like SongList and searchbar)

Once you are done with all the components it’s time to put it all together in the player component.

To do so we are going to import all the component(footer , body and sidebar) in player.js .

 import React from "react";
 import Body from "./components/Body";
 import Footer from "./components/Footer";
 import "./Player.css";
 import Sidebar from "./components/Sidebar";
 function Player({ spotify }) {
   return (
     <div className="player">
       <div className="player__body">
         {/* sidebar */}
         <Sidebar />
         {/* BODY */}
         <Body spotify={spotify} />
       </div>
       {/* Footer */}
       <Footer />
     </div>
   );
 }
 export default Player; 

Change the display style to flex in Player.css 

 .player__body {
   display: flex;
 } 

You can take reference from the original spotify app to get the styling right or if you want you can make it different . Now it’s your app so you can make it your way.

You can add extra functionality or maybe you can personalize it with styling of your choice.Once you are satisfied with your app you can move on to the next step.

7 -Deploy the spotify clone to firebase

Step 1 – first you have to install the firebase-tools using the following command

npm install -g firebase-tools

Step 2 – Login to your firebase using the command firebase login

Step 3 – initialize firebase into the project using the command firebase init 

Now your site is ready for deployment

Step 4 – use the following common for deployment

npm run build && firebase deploy

Step 5 – Now we have the change the redirectUri

const redirectUri = “https://<Project name>.web.app/”;

Step 6 – change the URL in the spotify dashboard too.(which we changed while we were setting up the spotify api)

Step 7 – Run the Deployment command again 

npm run build && firebase deploy

Your project is deployed and ready to use.

So what we learned while creating this clone.

1- how to use API

2 React components

3 Context API

4 – how to deploy using Firebase 

Karishma Upadhyay
Data Structure and Algorithm Expert (C++, Python , C, Java, JS) I am new at Stackcodify so i will give my 200 percent to help out people who want to start coding or want to fall in love with coding. My strengths are Data structure and algorithms, OOPS

Related Articles

Leave A Reply

Please enter your comment!
Please enter your name here

Stay on Top - Get the daily news in your inbox