This guide shows how to implement the backend endpoints to handle all data sent from the frontend.
URL: POST /api/v1/auth/spotify-tokens/store
Request Body:
{
"spotifyEmail": "user@example.com",
"invitationCode": "ABC123DEF",
"accessToken": "BQBP...",
"refreshToken": "AQB...",
"expiresAt": 1640995200000
}Backend Implementation (Node.js/Express):
// POST /api/v1/auth/spotify-tokens/store
app.post('/api/v1/auth/spotify-tokens/store', async (req, res) => {
try {
const { spotifyEmail, invitationCode, accessToken, refreshToken, expiresAt } = req.body;
// Validate required fields
if (!spotifyEmail || !refreshToken) {
return res.status(400).json({
success: false,
message: 'Missing required fields'
});
}
// Encrypt tokens before storing
const encryptedAccessToken = await encrypt(accessToken);
const encryptedRefreshToken = await encrypt(refreshToken);
// Store in database
await db.spotifyConnections.upsert({
where: { spotifyEmail },
update: {
accessToken: encryptedAccessToken,
refreshToken: encryptedRefreshToken,
expiresAt: new Date(expiresAt),
invitationCode,
updatedAt: new Date()
},
create: {
spotifyEmail,
accessToken: encryptedAccessToken,
refreshToken: encryptedRefreshToken,
expiresAt: new Date(expiresAt),
invitationCode,
createdAt: new Date(),
updatedAt: new Date()
}
});
res.json({
success: true,
message: 'Tokens stored successfully',
data: { spotifyEmail, expiresAt }
});
} catch (error) {
console.error('Error storing tokens:', error);
res.status(500).json({
success: false,
message: 'Failed to store tokens'
});
}
});URL: POST /api/v1/auth/spotify-tokens/get
Request Body:
{
"spotifyEmail": "user@example.com"
}Backend Implementation:
// POST /api/v1/auth/spotify-tokens/get
app.post('/api/v1/auth/spotify-tokens/get', async (req, res) => {
try {
const { spotifyEmail } = req.body;
if (!spotifyEmail) {
return res.status(400).json({
success: false,
message: 'Spotify email is required'
});
}
// Get from database
const connection = await db.spotifyConnections.findUnique({
where: { spotifyEmail }
});
if (!connection) {
return res.status(404).json({
success: false,
message: 'No tokens found for this email'
});
}
// Decrypt tokens
const accessToken = await decrypt(connection.accessToken);
const refreshToken = await decrypt(connection.refreshToken);
res.json({
success: true,
message: 'Tokens retrieved successfully',
data: {
accessToken,
refreshToken,
expiresAt: connection.expiresAt.getTime(),
spotifyEmail: connection.spotifyEmail
}
});
} catch (error) {
console.error('Error retrieving tokens:', error);
res.status(500).json({
success: false,
message: 'Failed to retrieve tokens'
});
}
});URL: POST /api/v1/auth/spotify-tokens/refresh
Request Body:
{
"refreshToken": "AQB..."
}Backend Implementation:
// POST /api/v1/auth/spotify-tokens/refresh
app.post('/api/v1/auth/spotify-tokens/refresh', async (req, res) => {
try {
const { refreshToken } = req.body;
if (!refreshToken) {
return res.status(400).json({
success: false,
message: 'Refresh token is required'
});
}
// Exchange refresh token for new access token
const tokenResponse = await fetch('https://accounts.spotify.com/api/token', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `Basic ${Buffer.from(
`${process.env.SPOTIFY_CLIENT_ID}:${process.env.SPOTIFY_CLIENT_SECRET}`
).toString('base64')}`
},
body: new URLSearchParams({
grant_type: 'refresh_token',
refresh_token: refreshToken
})
});
if (!tokenResponse.ok) {
const errorData = await tokenResponse.json();
return res.status(400).json({
success: false,
message: 'Failed to refresh token',
details: errorData
});
}
const tokenData = await tokenResponse.json();
// Update database with new tokens
const encryptedAccessToken = await encrypt(tokenData.access_token);
const encryptedRefreshToken = await encrypt(tokenData.refresh_token || refreshToken);
await db.spotifyConnections.update({
where: { refreshToken: encryptedRefreshToken },
data: {
accessToken: encryptedAccessToken,
refreshToken: encryptedRefreshToken,
expiresAt: new Date(Date.now() + (tokenData.expires_in * 1000)),
updatedAt: new Date()
}
});
res.json({
success: true,
message: 'Access token refreshed successfully',
data: {
accessToken: tokenData.access_token,
refreshToken: tokenData.refresh_token || refreshToken,
expiresAt: Date.now() + (tokenData.expires_in * 1000),
expiresIn: tokenData.expires_in
}
});
} catch (error) {
console.error('Error refreshing token:', error);
res.status(500).json({
success: false,
message: 'Failed to refresh token'
});
}
});URL: POST /api/v1/auth/spotify-connect-comprehensive
Request Body:
{
"spotifyEmail": "user@example.com",
"invitationCode": "ABC123DEF",
"spotifyData": {
"profile": { /* user profile */ },
"topTracks": [ /* top tracks */ ],
"recentlyPlayed": [ /* recently played */ ],
"playlists": [ /* playlists */ ],
"refreshToken": "AQB..."
},
"listeningStats": {
"totalTracksPlayed": 20,
"uniqueArtistsCount": 15,
"totalListeningTimeMs": 3600000,
"anonymousTrackCount": 2,
"topTracks": [ /* top 5 tracks */ ],
"topArtists": [ /* top 5 artists */ ]
}
}Backend Implementation:
// POST /api/v1/auth/spotify-connect-comprehensive
app.post('/api/v1/auth/spotify-connect-comprehensive', async (req, res) => {
try {
const { spotifyEmail, invitationCode, spotifyData, listeningStats } = req.body;
// Validate required fields
if (!spotifyEmail || !invitationCode || !spotifyData) {
return res.status(400).json({
success: false,
message: 'Missing required fields'
});
}
// Verify invitation code
const invitationValid = await verifyInvitationCode(invitationCode);
if (!invitationValid) {
return res.status(400).json({
success: false,
message: 'Invalid invitation code'
});
}
// Store user data
const user = await db.users.upsert({
where: { email: spotifyEmail },
update: {
spotifyConnected: true,
lastLoginAt: new Date(),
updatedAt: new Date()
},
create: {
email: spotifyEmail,
invitationCode,
spotifyConnected: true,
createdAt: new Date(),
updatedAt: new Date()
}
});
// Store Spotify profile
await db.spotifyProfiles.upsert({
where: { spotifyEmail },
update: {
displayName: spotifyData.profile.display_name,
spotifyId: spotifyData.profile.id,
country: spotifyData.profile.country,
product: spotifyData.profile.product,
profileImage: spotifyData.profile.images?.[0]?.url,
updatedAt: new Date()
},
create: {
spotifyEmail,
displayName: spotifyData.profile.display_name,
spotifyId: spotifyData.profile.id,
country: spotifyData.profile.country,
product: spotifyData.profile.product,
profileImage: spotifyData.profile.images?.[0]?.url,
createdAt: new Date(),
updatedAt: new Date()
}
});
// Store listening statistics
await db.listeningStats.upsert({
where: { spotifyEmail },
update: {
totalTracksPlayed: listeningStats.totalTracksPlayed,
uniqueArtistsCount: listeningStats.uniqueArtistsCount,
totalListeningTimeMs: listeningStats.totalListeningTimeMs,
anonymousTrackCount: listeningStats.anonymousTrackCount,
topTracks: JSON.stringify(listeningStats.topTracks),
topArtists: JSON.stringify(listeningStats.topArtists),
updatedAt: new Date()
},
create: {
spotifyEmail,
totalTracksPlayed: listeningStats.totalTracksPlayed,
uniqueArtistsCount: listeningStats.uniqueArtistsCount,
totalListeningTimeMs: listeningStats.totalListeningTimeMs,
anonymousTrackCount: listeningStats.anonymousTrackCount,
topTracks: JSON.stringify(listeningStats.topTracks),
topArtists: JSON.stringify(listeningStats.topArtists),
createdAt: new Date(),
updatedAt: new Date()
}
});
// Store top tracks
await db.spotifyTracks.deleteMany({ where: { spotifyEmail } });
for (const track of spotifyData.topTracks.slice(0, 10)) {
await db.spotifyTracks.create({
data: {
spotifyEmail,
trackId: track.id,
trackName: track.name,
artistName: track.artists[0]?.name || 'Unknown',
albumName: track.album.name,
popularity: track.popularity,
durationMs: track.duration_ms,
createdAt: new Date()
}
});
}
// Store recently played
await db.recentlyPlayed.deleteMany({ where: { spotifyEmail } });
for (const item of spotifyData.recentlyPlayed.slice(0, 10)) {
await db.recentlyPlayed.create({
data: {
spotifyEmail,
trackId: item.track.id,
trackName: item.track.name,
artistName: item.track.artists[0]?.name || 'Unknown',
playedAt: new Date(item.played_at),
createdAt: new Date()
}
});
}
// Store playlists
await db.spotifyPlaylists.deleteMany({ where: { spotifyEmail } });
for (const playlist of spotifyData.playlists.slice(0, 10)) {
await db.spotifyPlaylists.create({
data: {
spotifyEmail,
playlistId: playlist.id,
playlistName: playlist.name,
description: playlist.description,
trackCount: playlist.tracks.total,
ownerName: playlist.owner.display_name,
createdAt: new Date()
}
});
}
res.json({
success: true,
message: 'Spotify data stored successfully',
data: {
userId: user.id,
spotifyEmail,
profileComplete: true
}
});
} catch (error) {
console.error('Error storing Spotify data:', error);
res.status(500).json({
success: false,
message: 'Failed to store Spotify data'
});
}
});-- Users table
CREATE TABLE users (
id SERIAL PRIMARY KEY,
email VARCHAR(255) UNIQUE NOT NULL,
invitation_code VARCHAR(255),
spotify_connected BOOLEAN DEFAULT FALSE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
last_login_at TIMESTAMP
);
-- Spotify connections (tokens)
CREATE TABLE spotify_connections (
id SERIAL PRIMARY KEY,
spotify_email VARCHAR(255) UNIQUE NOT NULL,
invitation_code VARCHAR(255),
access_token TEXT NOT NULL, -- ENCRYPTED
refresh_token TEXT NOT NULL, -- ENCRYPTED
expires_at TIMESTAMP NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- Spotify profiles
CREATE TABLE spotify_profiles (
id SERIAL PRIMARY KEY,
spotify_email VARCHAR(255) UNIQUE NOT NULL,
spotify_id VARCHAR(255) NOT NULL,
display_name VARCHAR(255),
country VARCHAR(10),
product VARCHAR(50),
profile_image TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- Listening statistics
CREATE TABLE listening_stats (
id SERIAL PRIMARY KEY,
spotify_email VARCHAR(255) UNIQUE NOT NULL,
total_tracks_played INTEGER DEFAULT 0,
unique_artists_count INTEGER DEFAULT 0,
total_listening_time_ms BIGINT DEFAULT 0,
anonymous_track_count INTEGER DEFAULT 0,
top_tracks JSONB,
top_artists JSONB,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- Top tracks
CREATE TABLE spotify_tracks (
id SERIAL PRIMARY KEY,
spotify_email VARCHAR(255) NOT NULL,
track_id VARCHAR(255) NOT NULL,
track_name VARCHAR(500) NOT NULL,
artist_name VARCHAR(255),
album_name VARCHAR(500),
popularity INTEGER,
duration_ms INTEGER,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- Recently played
CREATE TABLE recently_played (
id SERIAL PRIMARY KEY,
spotify_email VARCHAR(255) NOT NULL,
track_id VARCHAR(255) NOT NULL,
track_name VARCHAR(500) NOT NULL,
artist_name VARCHAR(255),
played_at TIMESTAMP NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- Playlists
CREATE TABLE spotify_playlists (
id SERIAL PRIMARY KEY,
spotify_email VARCHAR(255) NOT NULL,
playlist_id VARCHAR(255) NOT NULL,
playlist_name VARCHAR(500) NOT NULL,
description TEXT,
track_count INTEGER DEFAULT 0,
owner_name VARCHAR(255),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- Indexes
CREATE INDEX idx_spotify_connections_email ON spotify_connections(spotify_email);
CREATE INDEX idx_spotify_profiles_email ON spotify_profiles(spotify_email);
CREATE INDEX idx_listening_stats_email ON listening_stats(spotify_email);
CREATE INDEX idx_spotify_tracks_email ON spotify_tracks(spotify_email);
CREATE INDEX idx_recently_played_email ON recently_played(spotify_email);
CREATE INDEX idx_spotify_playlists_email ON spotify_playlists(spotify_email);- Encrypt sensitive data (tokens, personal info)
- Validate all input data
- Rate limiting on API endpoints
- Authentication/Authorization for protected routes
- Input sanitization to prevent SQL injection
- HTTPS only in production
- Log security events
- Set up database with the schema above
- Implement encryption utilities
- Create API endpoints as shown above
- Add validation middleware
- Test all endpoints
- Add error handling and logging
- Deploy and monitor
This provides a complete backend implementation to handle all the data sent from your frontend! π―