Skip to content

Instantly share code, notes, and snippets.

@chevcast
Created December 11, 2019 04:37
Show Gist options
  • Save chevcast/49af0d5dd02907ba30dc3fd263a6f92d to your computer and use it in GitHub Desktop.
Save chevcast/49af0d5dd02907ba30dc3fd263a6f92d to your computer and use it in GitHub Desktop.

Step 1 - Redirect user to spotify so they can authorize their account.

res.redirect(
  `${spotifyRootUrl}/authorize?response_type=code&client_id=${spotifyClientId}&redirect_uri=${encodeURIComponent(redirectUri)}`
);

Step 2 - Create an endpoint for Spotify to redirect the user to and get the authorization code Spotify passed in.

app.get("/auth/spotify/callback", (req, res) => {
  const authCode = req.query.code;
  /* TODO */
});

Step 3 - Make a call to Spotify to turn the authorization code into an access token.

app.get("/auth/spotify/callback", (req, res) => {
  // Combine client ID and secret with a colon, then base64 encode them.
  const authHeader = Buffer.from(
    `${spotifyClientId}:${spotifyClientSecret}`
  ).toString("base64");

  // Make call to get access token.
  const response = await axios({
    url: "https://accounts.spotify.com/api/token",
    method: "POST",
    headers: {
      Authorization: `Basic ${authHeader}`
    },
    params: {
      grant_type: "authorization_code",
      code: authCode,
      redirect_uri: redirectUri
    }
  });

  /* Store access token somewhere */
  console.log(response.data.access_token);:
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment