Implement Mixed Server and Client Side Authentication
mainUse this pattern if you want your Node.js server to interact with Spotify 'as a specific user' by performing a client-side Authorization Code Flow with PKCE and passing the resulting token to your server.
1. Client Side: Trigger Authorization
Use performUserAuthorization to trigger the redirect and handle the token exchange. You can provide a callback for custom post-back logic.
// Redirect to a specific backend endpoint
SpotifyApi.performUserAuthorization("client-id", "https://localhost:3000", ["scope1"], "https://your-backend-server.com/accept-user-token");
// OR use a custom callback
SpotifyApi.performUserAuthorization("client-id", "https://localhost:3000", ["scope1"], (accessToken) => {
/* perform custom postback here */
});2. Server Side: Accept Token
Create an endpoint on your server to receive the token and initialize the SDK instance.
const { SpotifyApi } = require("@spotify/web-api-ts-sdk");
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
let sdk;
app.post('/accept-user-token', (req, res) => {
let data = req.body;
// Initialize SDK as the specific user
sdk = SpotifyApi.withAccessToken("client-id", data);
});
app.listen(3000);// Client Side
SpotifyApi.performUserAuthorization("client-id", "https://localhost:3000", ["scope1"], "https://your-backend-server.com/accept-user-token");
// Server Side
app.post('/accept-user-token', (req, res) => {
let data = req.body;
sdk = SpotifyApi.withAccessToken("client-id", data);
});