I am using SvelteKit to run a server on localhost:5173. On the front end, when a button is clicked it calls the /login
endpoint of my server. That endpoint builds the query params and redirects to the Spotify /Authorize end points, as outlined in their docs..
My /login
endpoint looks like this (client ID ommitted):
export function GET(url){
let params = new URLSearchParams({
response_type: 'code',
client_id: '...',
scope: 'playlist-modify-private playlist-read-private',
redirect_uri: `localhost:5173`
});
let endpoint = 'https://accounts.spotify.com/authorize?';
throw new redirect(308, endpoint + params.toString())
}
The response I get when is the following:
Access to fetch at 'https://accounts.spotify.com/authorize?response_type=code&client_id=...&scope=playlist-modify-private+playlist-read-private&redirect_uri=localhost%3A5173' (redirected from 'http://localhost:5173/login') from origin 'http://localhost:5173' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I am assuming I need to setup the proper CORS access origin, but I am not sure where to do that in SveletKit, specifically when throwing redirects as well.
So, CORS happens when your app is trying to request a domain that you haven't specified that it should be permitted to get resources from there.
A quick "fix" to this would just install the cors
package:
npm i cors
Then add it to your express app as such:
const cors = require('cors');
const app = express();
app.use(cors());
However, it would be more secure if you specified what domains exactly you want to bypass CORS, like this:
app.use(cors({
origin: // List of domains
}));
Here's a great link that provides more insight into this matter: https://www.section.io/engineering-education/how-to-use-cors-in-nodejs-with-express/