In a previous post, we discussed how to generate refresh tokens for Spotify API calls. Now, let’s dive into the exciting part: using Cloudflare Workers to interact with the Spotify API.. Now, let’s dive into the exciting part: using Cloudflare Workers to interact with the Spotify API.
Before we begin, make sure you have a basic understanding of Cloudflare Workers and have set up a blank Worker with a configured route. If you need guidance on this, refer to our post on custom domains and routes in Cloudflare Workers.
In your wrangler.toml file, define non-sensitive variables you’ll use in your Worker. For example, let’s specify a list of allowed origins:
However, for sensitive information like your Spotify Client ID and tokens, follow these steps:
During local development, create a .dev.vars file at the root of your project to store secrets that will be available when running wrangler dev. This file should follow a dotenv-like format:
Depending on your preference, you can structure your source code. For instance, I prefer splitting it into two files: index.ts and spotify.ts.
In spotify.ts, you can encapsulate the logic related to Spotify API interactions. In index.ts, you can handle the routing and overall structure of your Cloudflare Worker.
I hope you have fun playing around and exploring Cloudflare Worker and Vite/Vue. You should always know there is a limit for the number of requests for a Worker in Cloudflare free account and you should take that into account when implementing it on your site.