const { createProxyMiddleware } = require('http-proxy-middleware'); let axios = require('axios') let qs = require('querystring') // The authorization token to use with the Spotify API. // Will need to be refreshed once in a while. var authToken: string | null = null; async function updateToken(clientId: string, clientSecret: string) { if (authToken) { return; } let buf = Buffer.from(clientId + ':' + clientSecret) let encoded = buf.toString('base64'); let response = await axios.post( 'https://accounts.spotify.com/api/token', qs.stringify({ 'grant_type': 'client_credentials' }), { 'headers': { 'Authorization': 'Basic ' + encoded, 'Content-Type': 'application/x-www-form-urlencoded' } } ); authToken = (await response).data.access_token; } let onProxyReq = (proxyReq: any, req: any, res: any) => { proxyReq.setHeader("Authorization", "Bearer " + req._access_token) console.log("Proxying request", { 'path': req.path, 'originalUrl': req.originalUrl, 'baseUrl': req.baseUrl, }, { 'path': proxyReq.path, 'originalUrl': proxyReq.originalUrl, 'baseUrl': req.baseUrl, }, ); } export function useSpotifyClientCreds(app: any) { // First add a layer which creates a token and saves it in the request. app.use((req: any, res: any, next: any) => { updateToken('c3e5e605e7814cdf94cd86eeba6f4c4f', '5d870c84a3c34aa3a4cf803aa95cb96a') .then(() => { req._access_token = authToken; next(); }) }) app.use( '/spotifycc', createProxyMiddleware({ target: 'https://api.spotify.com/', changeOrigin: true, onProxyReq: onProxyReq, logLevel: 'debug', pathRewrite: { '^/spotifycc': '' }, }) ) }