A Node.js server implementing Spotify's OAuth2 Authorization Code flow for web applications. Optimized for deployment on Vercel with GitHub integration.
- ✅ Complete Spotify OAuth2 authorization code flow
- ✅ Environment variable configuration
- ✅ Ready for Vercel deployment
- ✅ Health check endpoint
- ✅ CORS enabled for cross-origin requests
- ✅ Error handling and validation
- Clone and setup:
git clone https://github.com/munzert/spotify-auth
cd spotify-auth
npm install- Environment configuration:
cp .env.example .env
# Edit .env with your Spotify app credentials- Start the server:
npm startYour server will be running at http://localhost:5000
- Go to the Spotify for Developers Dashboard
- Create a new application
- Add these redirect URIs in your app settings:
- For local development:
http://localhost:5000/callback - For production:
https://your-domain.com/callback
- For local development:
Vercel provides the best GitHub integration for hosting Node.js applications with automatic deployments.
-
Connect to GitHub:
- Go to vercel.com
- Sign up with your GitHub account
- Import your repository
-
Set Environment Variables in Vercel Dashboard:
CLIENT_ID- Your Spotify client IDCLIENT_SECRET- Your Spotify client secretREDIRECT_URI-https://your-project.vercel.app/callbackALLOWED_ORIGINS- Comma-separated list of allowed domains (e.g.,https://your-project.com)NODE_ENV- Set toproductionfor enhanced security
-
Deploy: Every push to main automatically deploys!
For automated deployment with environment variable management, the included GitHub Actions workflow requires these secrets:
SPOTIFY_CLIENT_ID- Your Spotify app's client IDSPOTIFY_CLIENT_SECRET- Your Spotify app's client secretSPOTIFY_REDIRECT_URI- Your production redirect URIVERCEL_TOKEN- Your Vercel tokenVERCEL_ORG_ID- Your Vercel organization IDVERCEL_PROJECT_ID- Your Vercel project ID
- Go to your GitHub repository
- Settings → Secrets and variables → Actions
- Click "New repository secret" for each required secret
GET /- Serves the main authentication pageGET /login- Initiates Spotify OAuth flow- Security: Origin is automatically detected from the
Refererheader - In production, requests without a valid Referer are rejected
- Scopes are hardcoded:
user-read-private user-read-email user-read-playback-state user-modify-playback-state streaming
- Security: Origin is automatically detected from the
GET /callback- Handles OAuth callback from SpotifyGET /refresh_token?refresh_token=TOKEN- Refreshes an access tokenGET /health- Health check endpoint
After deployment to Vercel, you can use this server from your web application:
Important: Users must initiate login by clicking a button/link on your website. The server automatically detects the origin from the browser's Referer header for security.
<!-- In your HTML -->
<button onclick="loginWithSpotify()">Login with Spotify</button>
<script>
function loginWithSpotify() {
window.location.href = 'https://your-project.vercel.app/login';
}
// Handle the callback (tokens will be in URL hash)
window.addEventListener('load', function() {
const urlParams = new URLSearchParams(window.location.hash.substring(1));
const accessToken = urlParams.get('access_token');
const refreshToken = urlParams.get('refresh_token');
const expiresIn = urlParams.get('expires_in');
if (accessToken) {
// User is authenticated, use the access token
console.log('Authenticated with Spotify!');
// Store tokens securely and make Spotify API calls
}
const error = urlParams.get('error');
if (error) {
console.error('Authentication error:', error);
}
});
</script>The server requests these Spotify permissions:
user-read-private- Read user's subscription detailsuser-read-email- Read user's email addressuser-read-playback-state- Read user's playback stateuser-modify-playback-state- Control playbackstreaming- Control playback on Spotify clients
For more scopes: See Spotify Authorization Scopes. To change scopes, modify the hardcoded value in index.js.
Critical Security Feature: For security, the server uses the Referer header to determine where to redirect tokens. Only domains in your ALLOWED_ORIGINS whitelist are accepted.
ALLOWED_ORIGINS=http://localhost:8888,https://yourdomain.comWhen NODE_ENV=production:
- ✅ Origin is only determined from the
Refererheader (secure) - ✅ Query parameters are ignored (prevents phishing attacks)
- ✅ Requests without a valid Referer are rejected
- ✅ Only whitelisted domains can receive tokens
Default (development mode):
- Query parameters are allowed as fallback for testing
- Default fallback to
localhost:8888
| Variable | Description | Required |
|---|---|---|
CLIENT_ID |
Spotify application client ID | Yes |
CLIENT_SECRET |
Spotify application client secret | Yes |
REDIRECT_URI |
OAuth callback URL (e.g., https://your-project.vercel.app/callback) |
Yes |
ALLOWED_ORIGINS |
Comma-separated list of allowed origin URLs for enhanced security (disables fallbacks) | Recommended |
PORT |
Server port (default: 5000) | No |
HOST |
Server host (default: localhost) | No |
* If not set, defaults to http://localhost:8888,http://localhost:3000
- Never expose your
CLIENT_SECRETin client-side code - Always use HTTPS in production
- Store tokens securely (consider using sessionStorage instead of localStorage)
- Set
NODE_ENV=productionin your deployment - Implement token refresh before expiration (use
expires_invalue) - Validate tokens on your backend before making sensitive operations
MIT License - see LICENSE file for details.