I'm building a pretty simple music search function in a new project right now, powered by Spotify’s web API. In a lot of the StackOverflow threads and tutorials I found, they give examples of using Spotify’s API, but with front-end user authentication.

For my project, I don’t really need (or want to) require users to sign into Spotify to access some of the basic functions like search. The problem, however, to use the Search API requires you to authenticate to retrieve an access token, which then needs to get passed into search. So I devised a quick way to accomplish the search for front-end users.

For my project, I'm using NextJS, and Axios for making requests, but the code can be adapted pretty easily for any Javascript-based project. The first step is registering your app in Spotify. Fill out everything you normally would, then grab your CLIENT_ID and CLIENT_SECRET.

Next, we’re going to create a way to get our access token with our CLIENT_ID and CLIENT_SECRET:

const basic = Buffer.from(`${publicRuntimeConfig.SPOTIFY_CLIENT_ID}:${publicRuntimeConfig.SPOTIFY_CLIENT_SECRET}`).toString(`base64`)
const getSpotifyAccessToken = async () => {
  const requestOptions = {
    headers: {
      Authorization: `Basic ${basic}`,
      "Content-Type": `application/x-www-form-urlencoded`,
    },
  }
  const body = new URLSearchParams()
  body.append(`grant_type`, `client_credentials`)
  const response = await axios.post(`https://accounts.spotify.com/api/token`, body, requestOptions)
  //console.log(response)
  return response.data
}

One thing to note here: Instead of retrieving my ID and secret directly from an .env file, I'm loading it in NextJS’s configure first, thus the publicRuntimeConfig.SPOTIFY_CLIENT_ID

Next, I'm going to make an async function that calls getSpotifyAccessToken when I make a get request:

async function spotifyGet(url) {
  const { access_token } = await getSpotifyAccessToken()
  const requestOptions = {
    headers: {
      "Content-Type": `application/json`,
      Accept: `application/json`,
      Authorization: `Bearer ${access_token}`,
    },
  }
  const response = await axios.get(url, requestOptions)
  return handleResponse(response)
}

Now when I use spotifyGet(), I'm making a POST request first to generate my access token, then pass it into the new GET request with the access token in the header.

Finally, my actual search looks something like this:

import { fetchWrapper } from "../helpers"

const [musicSearchq, setMusicSearchq] = useState(``)
const [musicSearchResuts, setMusicSearchResuts] = useState({})

const handleMusicSearch = async (e) => {
    const q = musicSearchq
    try {
      const res = await fetchWrapper.spotifyGet(`https://api.spotify.com/v1/search?q=${q}&type=track&limit=5`)
      console.log(res)
      setMusicSearchResuts(res.tracks.items)
    } catch (err) {
      console.log(err)
    }
  }

In the search form itself, I'm saving the search term in a state, then on submit, inserting it into the URL. The results then get added to another state.

There could be a lot more to expand on here, like storing the access token locally or in the cache so we're not having to make the extra request every time, but for some basic testing, Spotify's API is pretty fast, that the extra lookup isn't even noticeable.