-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
73 lines (64 loc) · 2.86 KB
/
Copy pathserver.js
File metadata and controls
73 lines (64 loc) · 2.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import express from 'express'
const app = express();
// getToken(): asks Spotify for a new app-only access token using your
// CLIENT_ID and CLIENT_SECRET. Returns JSON with access_token and expiry info.
const getToken = async () => {
const currentTimestamp = Math.floor(Date.now() / 1000)
if (!process.env.CLIENT_ID || !process.env.CLIENT_SECRET) {
throw new Error('Missing CLIENT_ID or CLIENT_SECRET in environment')
}
console.log('Fetching new token at ' + currentTimestamp)
// Spotify Uses Basic Authentication
// See also: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Authorization#basic_authentication
const authString = Buffer
.from(process.env.CLIENT_ID + ':' + process.env.CLIENT_SECRET)
.toString('base64')
// construct fetch headers including the authString and grant_type
// as required by Spotify
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + authString
},
body: new URLSearchParams({ 'grant_type': 'client_credentials' })
}
const response = await fetch('https://accounts.spotify.com/api/token', options)
if (!response.ok) {
const text = await response.text().catch(() => '')
throw new Error('Spotify token request failed: ' + response.status + ' ' + text)
}
const data = await response.json()
data.expires_at = currentTimestamp + (data.expires_in || 0)
console.log('Fetched new token, valid until ' + data.expires_at)
return data
}
// Serve static files locally; Vercel ignores express.static in production and serves public/** at the edge
app.use(express.static('public'))
// In production on Vercel, requests to '/' won't be handled by express.static.
// Redirect to the static index.html which Vercel serves from public/ via the Edge Network.
// Route handler: sends the browser to /index.html so your static page loads.
app.get('/', (req, res) => {
// Avoid Express's sendFile absolute path requirement in serverless envs
// and let Vercel's static hosting serve /public/index.html at /index.html
res.redirect('/index.html')
})
// Route handler /token: returns a fresh token to the frontend, with short-lived cache headers disabled.
app.get('/token', async (req, res) => {
try {
const freshToken = await getToken()
// Prevent any intermediary caching
res.set('Cache-Control', 'no-store, no-cache, must-revalidate')
// Return only what the client needs
res.json({ access_token: freshToken.access_token, expires_at: freshToken.expires_at })
} catch (e) {
console.error(e)
res.status(500).json({ error: 'Failed to fetch token' })
}
})
const port = 3000
// app.listen(...): starts the web server and prints a message when it's ready.
// You can then open the URL in your browser to use the app locally.
app.listen(port, () => {
console.log(`Express is live at http://localhost:${port}`)
})