Skip to main content

Overview

The Spotify Player feature allows users to search for songs, artists, and albums, then play them directly in the browser using Spotify’s embedded player. The player uses the Spotify Web API for search functionality and displays results in an interactive interface.
This feature requires a valid Spotify access token to function. The token is automatically fetched from the backend on page load.

Key Features

Real-time Search

Search for songs, artists, and albums with instant results from Spotify’s catalog

Embedded Playback

Play tracks directly in the browser using Spotify’s embedded player

Track Information

View track names and artist information in search results

Dark Theme

Spotify-inspired dark interface optimized for music listening

How It Works

The Spotify Player consists of three main components:
1

Authentication

The application fetches a Spotify access token from the backend server when the page loads.
2

Search

Users enter search terms, which are sent to the Spotify API to retrieve matching tracks.
3

Playback

Clicking a search result loads the track into the embedded Spotify player iframe.

Core Functions

getAccessToken()

Fetches the Spotify access token from the backend server. This function runs automatically when the page loads.
index.html
async function getAccessToken() {
    const response = await fetch('https://jsnode-ab0e.onrender.com', { method: 'POST' });
    const data = await response.json();
    accessToken = data.access_token;
}
Usage:
window.onload = getAccessToken;

searchSongs()

Searches for tracks based on user input and displays results in a clickable list.
index.html
async function searchSongs() {
    const query = document.getElementById('search-query').value.trim();
    if (!query) {
        alert('Por favor, ingresa un término de búsqueda.');
        return;
    }

    const response = await fetch(`https://jsnode-ab0e.onrender.com/search?query=${encodeURIComponent(query)}&type=track&accessToken=${accessToken}`);
    const data = await response.json();

    const songList = document.getElementById('song-list');
    songList.innerHTML = ''; // Limpiar resultados anteriores

    data.tracks.items.forEach(track => {
        const li = document.createElement('li');
        li.textContent = `${track.name} - ${track.artists.map(artist => artist.name).join(', ')}`;
        li.dataset.embedUrl = `https://open.spotify.com/embed/track/${track.id}?utm_source=generator&theme=0`;
        li.addEventListener('click', () => playTrack(li.dataset.embedUrl));
        songList.appendChild(li);
    });
}
Parameters:
  • query: Search term from the input field
  • type: Search type (default: “track”)
  • accessToken: Spotify API access token
Response Structure:
{
  "tracks": {
    "items": [
      {
        "id": "3n3Ppam7vgaVa1iaRUc9Lp",
        "name": "Song Title",
        "artists": [
          { "name": "Artist Name" }
        ]
      }
    ]
  }
}

playTrack()

Loads a track into the embedded Spotify player by updating the iframe source URL.
index.html
function playTrack(embedUrl) {
    const player = document.getElementById('player');
    player.src = embedUrl; // Actualiza el atributo src del iframe con el nuevo URL
}
Parameters:
  • embedUrl: Spotify embed URL in the format https://open.spotify.com/embed/track/{trackId}

UI Components

The search interface includes an input field and search button:
index.html
<div class="search-bar">
    <input type="text" id="search-query" placeholder="Busca por canción, artista o álbum" />
    <button onclick="searchSongs()">Buscar</button>
</div>

Search Results

Results are displayed as clickable list items:
index.html
<p>Resultados de la búsqueda:</p>
<ul id="song-list"></ul>
Styling:
index.html
li {
    margin: 10px 0;
    cursor: pointer;
    color: #1db954;
}

li:hover {
    text-decoration: underline;
}

Embedded Player

The Spotify player is embedded using an iframe:
index.html
<div id="player-container">
    <iframe
        id="player"
        style="border-radius:12px;"
        width="100%"
        height="152"
        frameBorder="0"
        allowfullscreen=""
        allow="autoplay; clipboard-write; encrypted-media; fullscreen; picture-in-picture"
        loading="lazy"
        src="">
    </iframe>
</div>
The iframe’s allow attribute enables essential features like autoplay and encrypted media playback.

Styling

The player uses Spotify’s signature green color (#1db954) and a dark theme:
index.html
body {
    font-family: 'Roboto', sans-serif;
    background-color: #121212;
    color: white;
    padding: 20px;
    text-align: center;
}

button {
    padding: 10px 20px;
    border: none;
    border-radius: 5px;
    background-color: #1db954;
    color: white;
    cursor: pointer;
}

button:hover {
    background-color: #14833b;
}

Responsive Design

The player maintains a fixed width of 1024px for desktop-like experience:
index.html
body {
    width: 1024px;
    margin: 0 auto;
    overflow-x: hidden;
}

@media (max-width: 1024px) {
    body {
        width: 1024px;
    }
}
The current implementation forces a 1024px width even on mobile devices, which may cause horizontal scrolling on smaller screens.

Implementation Files

The Spotify Player is implemented in two main files:
  • index.html: Primary Spotify player with fixed width (1024px)
  • index3.html: Alternative version with responsive mobile design

Differences Between Versions

index.html:
  • Fixed 1024px width for desktop experience
  • Token endpoint: https://jsnode-ab0e.onrender.com
  • Forced desktop layout on mobile
index3.html:
  • Responsive design with media queries
  • Token endpoint: https://jsnode-ab0e.onrender.com/get-token
  • Reduced player height (80px) on mobile devices

API Endpoints

// POST request to backend
const response = await fetch('https://jsnode-ab0e.onrender.com', { 
  method: 'POST' 
});
const data = await response.json();
// Returns: { access_token: "BQA..." }

Best Practices

Input Validation

Always validate that the search query is not empty before making API requests

URL Encoding

Use encodeURIComponent() to properly encode search queries for URL parameters

Clear Previous Results

Clear the song list before displaying new search results to avoid confusion

Artist Names

Use .map() and .join() to properly format multiple artist names

Limitations

Token Expiration: Spotify access tokens expire after a certain period. The current implementation doesn’t handle token refresh automatically.
Playback Restrictions: The embedded player requires users to have a Spotify account. Free users may experience limited playback (30-second previews).

Next Steps

YouTube Player

Explore the alternative YouTube-based player

Download Generator

Learn how to generate download links for Spotify tracks

Build docs developers (and LLMs) love