• Stars
    star
    291
  • Rank 142,563 (Top 3 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created almost 6 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A simple player for Spotify's web playback

react-spotify-web-playback

npm version CI Quality Gate Status Coverage

A Spotify player with Spotify's Web Playback SDK.

View the demo

Check the supported browser list. This library will try to use the user's devices to work with unsupported browsers.

Setup

npm i react-spotify-web-playback

Getting Started

import SpotifyPlayer from 'react-spotify-web-playback';

<SpotifyPlayer
  token="BQAI_7RWPJuqdZxS-I8XzhkUi9RKr8Q8UUNaJAHwWlpIq6..."
  uris={['spotify:artist:6HQYnRM4OzToCYPpVBInuU']}
/>;

Client-side only

This library requires the window object.
If you are using an SSR framework, you'll need to use a dynamic import or a Client Component to load the player.

Spotify Token

It needs a Spotify token with the following scopes:

  • streaming
  • user-read-email
  • user-read-private
  • user-read-playback-state (to read other devices' status)
  • user-modify-playback-state (to update other devices)

If you want to show the Favorite button (πŸ’š), you'll need the additional scopes:

  • user-library-read
  • user-library-modify

Please refer to Spotify's Web API docs for more information.

This library doesn't handle token generation and expiration. You'll need to handle that by yourself.

Props

callback (state: CallbackState) => void
Get status updates from the player.

Type Definition
type ErrorType = 'account' | 'authentication' | 'initialization' | 'playback' | 'player';
type RepeatState = 'off' | 'context' | 'track';
type Status = 'ERROR' | 'IDLE' | 'INITIALIZING' | 'READY' | 'RUNNING' | 'UNSUPPORTED';
type Type =
  | 'device_update'
  | 'favorite_update'
  | 'player_update'
  | 'progress_update'
  | 'status_update'
  | 'track_update';

interface CallbackState extends State {
  type: Type;
}

interface State {
  currentDeviceId: string;
  deviceId: string;
  devices: SpotifyDevice[];
  error: string;
  errorType: ErrorType | null;
  isActive: boolean;
  isInitializing: boolean;
  isMagnified: boolean;
  isPlaying: boolean;
  isSaved: boolean;
  isUnsupported: boolean;
  needsUpdate: boolean;
  nextTracks: SpotifyTrack[];
  playerPosition: 'bottom' | 'top';
  position: number;
  previousTracks: SpotifyTrack[];
  progressMs: number;
  repeat: RepeatState;
  shuffle: boolean;
  status: Status;
  track: SpotifyTrack;
  volume: number;
}

components CustomComponents
Custom components for the player.

Type Definition
interface CustomComponents {
  /**
   * A React component to be displayed before the previous button.
   */
  leftButton?: ReactNode;
  /**
   * A React component to be displayed after the next button.
   */
  rightButton?: ReactNode;
}

getOAuthToken (callback: (token: string) => void) => Promise<void>
The callback Spotify SDK uses to get/update the token.
Use it to generate a new token when the player needs it.

Example
import { useState } from 'react';
import SpotifyPlayer, { Props } from 'react-spotify-web-playback';

import { refreshTokenRequest } from '../some_module';

export default function PlayerWrapper() {
  const [accessToken, setAccessToken] = useState('');
  const [refreshToken, setRefreshToken] = useState('');
  const [expiresAt, setExpiresAt] = useState(0);

  const getOAuthToken: Props['getOAuthToken'] = async callback => {
    if (expiresAt > Date.now()) {
      callback(accessToken);

      return;
    }

    const { acess_token, expires_in, refresh_token } = await refreshTokenRequest(refreshToken);

    setAccessToken(acess_token);
    setRefreshToken(refresh_token);
    setExpiresAt(Date.now() + expires_in * 1000);

    callback(acess_token);
  };

  return <SpotifyPlayer getOAuthToken={getOAuthToken} token={accessToken} uris={[]} />;
}

getPlayer (player: SpotifyPlayer) => void
Get the Spotify Web Playback SDK instance.

hideAttribution boolean β–ΆοΈŽ false
Hide the Spotify logo.

hideCoverArt boolean β–ΆοΈŽ false
Hide the cover art

initialVolume number between 0 and 1. β–ΆοΈŽ 1
The initial volume for the player. It's not used for external devices.

inlineVolume boolean β–ΆοΈŽ true
Show the volume inline for the "responsive" layout for 768px and above.

layout 'compact' | 'responsive' β–ΆοΈŽ 'responsive'
The layout of the player.

locale Locale
The strings used for aria-label/title attributes.

Type Definition
interface Locale {
  currentDevice?: string; // 'Current device'
  devices?: string; // 'Devices'
  next?: string; // 'Next'
  otherDevices?: string; // 'Select other device'
  pause?: string; // 'Pause'
  play?: string; // 'Play'
  previous?: string; // 'Previous'
  removeTrack?: string; // 'Remove from your favorites'
  saveTrack?: string; // 'Save to your favorites'
  title?: string; // '{name} on SPOTIFY'
  volume?: string; // 'Volume'
}

magnifySliderOnHover: boolean β–ΆοΈŽ false
Magnify the player's slider on hover.

name string β–ΆοΈŽ 'Spotify Web Player'
The name of the player.

offset number
The position of the list/tracks you want to start the player.

persistDeviceSelection boolean β–ΆοΈŽ false
Save the device selection.

play boolean
Control the player's status.

showSaveIcon boolean β–ΆοΈŽ false
Display a Favorite button. It needs additional scopes in your token.

styles object
Customize the player's appearance. Check StylesOptions in the types.

syncExternalDevice boolean β–ΆοΈŽ false
If there are no URIs and an external device is playing, use the external player context.

syncExternalDeviceInterval number β–ΆοΈŽ 5
The time in seconds that the player will sync with external devices.

token string REQUIRED
A Spotify token. More info is below.

updateSavedStatus (fn: (status: boolean) => any) => any
Provide you with a function to sync the track saved status in the player.
This works in addition to the showSaveIcon prop, and it is only needed if you keep track's saved status in your app.

uris string | string[] REQUIRED
A list of Spotify URIs.

Spotify API

The functions that interact with the Spotify API are exported for your convenience.
Use them at your own risk.

import { spotifyApi } from 'react-spotify-web-playback';

checkTracksStatus(token: string, tracks: string | string[]): Promise<boolean[]>

getDevices(token: string): Promise<SpotifyApi.UserDevicesResponse>

getPlaybackState(token: string): Promise<SpotifyApi.CurrentlyPlayingObject | null>

getQueue(token: string): Promise<SpotifyApi.UsersQueueResponse>

pause(token: string, deviceId?: string): Promise<void>

play(token: string, options: SpotifyPlayOptions): Promise<void>

interface SpotifyPlayOptions {
  context_uri?: string;
  deviceId: string;
  offset?: number;
  uris?: string[];
}

previous(token: string, deviceId?: string): Promise<void>

next(token: string, deviceId?: string): Promise<void>

removeTracks(token: string, tracks: string | string[]): Promise<void>

repeat(token: string, state: 'context' | 'track' | 'off', deviceId?: string): Promise<void>

saveTracks(token: string, tracks: string | string[]): Promise<void>

seek(token: string, position: number, deviceId?: string): Promise<void>

setDevice(token: string, deviceId: string, shouldPlay?: boolean): Promise<void>

setVolume(token: string, volume: number, deviceId?: string): Promise<void>

shuffle(token: string, state: boolean, deviceId?: string): Promise<void>

Styling

You can customize the UI with a styles prop. Check all the available options here.

<SpotifyWebPlayer
  // ...
  styles={{
    activeColor: '#fff',
    bgColor: '#333',
    color: '#fff',
    loaderColor: '#fff',
    sliderColor: '#1cb954',
    trackArtistColor: '#ccc',
    trackNameColor: '#fff',
  }}
/>

rswp-styles

Issues

If you find a bug, please file an issue on our issue tracker on GitHub.

License

MIT

More Repositories

1

logos

A huge collection of SVG logos
SVG
6,086
star
2

react-joyride

Create guided tours in your apps
TypeScript
6,046
star
3

react-inlinesvg

An SVG loader component for ReactJS
TypeScript
1,249
star
4

react-redux-saga-boilerplate

Starter kit with react-router, react-helmet, redux, redux-saga and styled-components
TypeScript
607
star
5

react-floater

Advanced tooltips for React
TypeScript
189
star
6

disable-scroll

Prevent page scrolling
TypeScript
143
star
7

react-redux-observables-boilerplate

Starter kit for React with Router, Redux, Observable + RxJS
JavaScript
89
star
8

react-redux-starter

React starter kit with redux and react-router
JavaScript
68
star
9

alfred-workflows

Collection of Alfred workflows
PHP
33
star
10

react-from-dom

Convert HTML/XML source code or DOM nodes to React elements
TypeScript
25
star
11

codeclimate-stylelint

A Code Climate engine for the mighty, modern CSS linter
Less
24
star
12

tree-changes

Compare changes between two datasets
TypeScript
21
star
13

styled-minimal

Minimal UI theme with styled-components
JavaScript
18
star
14

is-lite

Type check tool
TypeScript
17
star
15

Turntable.fm-Playlists

Add playlists to turntable.fm
JavaScript
16
star
16

react-joyride-demo

Demo for React-Joyride
TypeScript
15
star
17

components

A collection of imperfect React components
TypeScript
15
star
18

react-web-session

Keep user data between visits
TypeScript
12
star
19

mdn-search

Search MDN with Alfred 2
PHP
11
star
20

generator-web

Generate a front-end website
JavaScript
11
star
21

colormeup

a tool to inspect a color and play with its many variations
JavaScript
10
star
22

helpers

Collection of useful functions
TypeScript
9
star
23

colorizr

Color conversion, manipulation, comparison and analysis
TypeScript
8
star
24

cpf-cnpj-generator

Generate fake brazilian CPF and CNPJ
PHP
8
star
25

hooks

Collection of useful React hooks
TypeScript
7
star
26

object-to-dot-notation

Convert simple objects to dot notation
TypeScript
6
star
27

links

Useful links for development
5
star
28

cloudinary

A tiny alternative to cloudinary-npm
JavaScript
5
star
29

react-starter

React starter kit with flux, router and bootstrap with a Hacker News reader
JavaScript
4
star
30

resume-v1

Developer Resume
ApacheConf
4
star
31

react-range-slider

A range slider component for React
TypeScript
4
star
32

genpass-alfred

Generate passwords from strings
JavaScript
3
star
33

dotfiles

sensible hacker default for macOS
Vim Script
3
star
34

git-rev-webpack-plugin

Webpack plugin to use git branch, hash and tag as substitutions for file names
Shell
3
star
35

s3-api

JavaScript
3
star
36

react-bot

A guided chat for interviewing users
3
star
37

deep-equal

Lightweight deep equal comparator
TypeScript
3
star
38

web-session

Keep user sessions between visits
TypeScript
3
star
39

idea-settings

IDEA Settings
2
star
40

tsconfig

Shared Typescript config
2
star
41

crashplan-control

Control CrashPlan with Alfred
Shell
2
star
42

types

Reusable typescript typings
TypeScript
2
star
43

git-hooks

A collection of useful git hooks
Shell
2
star
44

js-codemod

Codemod scripts to transform code
JavaScript
2
star
45

hadio

Airtime custom player
JavaScript
1
star
46

react-celebration

1
star
47

big-list

Technologies that you should learn (or at least now what it is about)
1
star
48

cookies

Lightweight cookie client
TypeScript
1
star
49

react-money

1
star
50

prettier-config

Shared Prettier config
1
star
51

learning

Books, courses and presentations that I've engaged.
1
star
52

react-party

It's a party
1
star
53

github-labels

1
star
54

eslint-config

Shared ESLint config
JavaScript
1
star
55

ttRoomie

A lightweight Users List for turntable.fm
JavaScript
1
star
56

gilbarbara.github.io

My Resume
ApacheConf
1
star
57

react-dropdown

Flexible dropdown component for React
TypeScript
1
star
58

wabi-sabi

1
star
59

fluxy

Flux Playground
JavaScript
1
star
60

react-floater-demo

Demo for react-floater
TypeScript
1
star
61

simple-react-router-redux

Tiny redux bindings for react-router
JavaScript
1
star
62

raycast-extensions

Raycast Extensions
TypeScript
1
star
63

TT-Bot

room bot and dj queue manager for turntable.fm
JavaScript
1
star
64

repo-tools

Useful CLI commands for working with remote repositories.
TypeScript
1
star
65

bitbar-plugins

BitBar plugins
JavaScript
1
star
66

kollectiv-syntax

Another dark theme with cool colors
CSS
1
star
67

intera-demo

Demo for Intera
TypeScript
1
star
68

wc14

World Cup 2014
JavaScript
1
star
69

requird

Wordpress plugin to require users to fill selected fields before posting.
PHP
1
star
70

generator-marionette-2

A Marionette 2 generator for Yeoman
JavaScript
1
star
71

little-alchemy-helper

Little Alchemy Helper - Interactive app with a bookmarklet to help while you play the game Little Alchemy.
JavaScript
1
star