Skip to content

Instantly share code, notes, and snippets.

@L1fescape
Last active May 8, 2019 22:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save L1fescape/c0398e47b023d4c91a1d023900604d2e to your computer and use it in GitHub Desktop.
Save L1fescape/c0398e47b023d4c91a1d023900604d2e to your computer and use it in GitHub Desktop.

Spotify Token

Generate authentication tokens for your Spotify application via node

Usage

$ SPOTIFY_CLIENT_ID=<clientID> npm start

Configure the Spotify Application

  • Create a Spotify application via their developer dashboard.
  • Whitelist your callback url (default is http://localhost:3000/callback)

Issues

  • INVALID_CLIENT: Invalid redirect URI: whitelist your callback url by adding it to the list of Redirect URIs in your spotify application's settings
{
"name": "spotify-token",
"version": "1.0.0",
"description": "Generate Spotify access tokens via node",
"main": "spotify-token.js",
"author": "L1fescape <akennedy2292@gmail.com>",
"license": "MIT",
"scripts": {
"start": "node spotify-token.js"
},
"dependencies": {
"opn": "^6.0.0"
}
}
const http = require('http')
const url = require('url')
const querystring = require('querystring')
const crypto = require('crypto')
const opn = require('opn')
const { SPOTIFY_CLIENT_ID, HOST, PORT, CALLBACK } = process.env
const host = HOST || 'http://localhost'
const port = PORT || 3000
const callbackPath = CALLBACK || 'callback'
const spotifyAuthEndpoint = 'https://accounts.spotify.com/authorize'
if (!SPOTIFY_CLIENT_ID) {
console.error('Please provide a client ID.')
process.exit()
}
const state = crypto.randomBytes(16).toString('hex')
const queryParams = querystring.stringify({
response_type: 'code',
client_id: SPOTIFY_CLIENT_ID,
redirect_uri: `${host}:${port}/${callbackPath}`,
state,
})
const server = http.createServer((req, res) => {
const urlParts = url.parse(req.url, true)
const { query, pathname } = urlParts
let message = ''
if (pathname === `/${callbackPath}`) {
if (query.error) {
message = `Error: ${query.error}`
} else if (query.state !== state) {
message = 'Error: state mismatch'
} else if (query.code) {
message = `Access Token: ${query.code}`
} else {
message = 'No code returned'
}
console.log(message)
} else {
message = '404: path not found'
}
res.write(`<html><body><p>${message}</p></body></html>`)
res.end()
server.close(() => process.exit())
})
server.listen(port)
const spotifyAuthURL = `${spotifyAuthEndpoint}?${queryParams}`
console.log('Opening', spotifyAuthURL)
opn(spotifyAuthURL)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment