Giter Site home page Giter Site logo

react-spotify-auth's Introduction

react-spotify-auth

Easy Spotify Authentication, written in React

NPM JavaScript Style Guide Build Status GitHub stars FOSSA Status

Install

yarn add react-spotify-auth
npm install --save react-spotify-auth

Demos

User's top tracks (all user accounts)

Spotify Web Player (Premium Spotify accounts only, must be listening to a track prior to using)

Got something to add, or a feature you want? Send a PR or create an issue!

Quickstart

import { SpotifyAuth, Scopes } from 'react-spotify-auth'
import 'react-spotify-auth/dist/index.css' // if using the included styles

function App = () => {
  <SpotifyAuth
    redirectUri='http://localhost:3000/callback'
    clientID='your client id from spotify here'
    scopes={[Scopes.userReadPrivate, Scopes.userReadEmail]}
  />
}

Usage

import React from 'react'
import { SpotifyApiContext } from 'react-spotify-api'
import Cookies from 'js-cookie'

import { SpotifyAuth, Scopes } from 'react-spotify-auth'
import 'react-spotify-auth/dist/index.css'

const App = () => {
    const [token, setToken] = React.useState(Cookies.get("spotifyAuthToken"))
  return (
    <div className='app'>
      {token ? (
        <SpotifyApiContext.Provider value={token}>
          {/* Your Spotify Code here */}
          <p>You are authorized with token: {token}</p>
        </SpotifyApiContext.Provider>
      ) : (
        // Display the login page
        <SpotifyAuth
          redirectUri='http://localhost:3000/callback'
          clientID='1a70ba777fec4ffd9633c0c418bdcf39'
          scopes={[Scopes.userReadPrivate, 'user-read-email']} // either style will work
          onAccessToken={(token) => setToken(token)}
        />
      )}
    </div>
  )
}
export default App

API

SpotifyAuth

Here's some props that can be used to customize the button. Please enter your own values for redirectUri and clientID, otherwise your project may not work correctly.

Name Required Default Description
redirectUri http://localhost:3000 Spotify redirect URI. In most cases, this is the URL of your webpage. It must be set in your Developer Console.
clientID Spotify app Client ID. Can be found from the Spotify Developer Console.
scopes ['user-read-private', 'user-read-email'] Array of camelCased equivalent for the scopes you are requesting. For example, if you wanted the scope user-read-recently-played you can enter [Scopes.userReadRecentlyPlayed].
onAccessToken (token) => {} Function that gets triggered when the component recognizes an access token after an auth grant. Is called with the parameter accessToken.
title "Continue with Spotify" Message inside the button.
btnClassName style included in package Class(es) that is given to the button.
logoClassName style included in package Class(es) given to the svg that draws the Spotify logo. Make sure to add a width if you use a custom class, otherwise it will not appear.
noLogo false Removes the Spotify logo from the button.
localStorage false Uses window.localStorage as a method to store the token. Note that localstorage does not have an expiry.
noCookie false When true, it does not store the auth token in a cookie named SpotifyAuthToken
showDialog false Whether or not to force the user to approve the app again if they’ve already done so. If false (default), a user who has already approved the application may be automatically redirected to the URI specified by redirect_uri. If true, the user will not be automatically redirected and will have to approve the app again.

SpotifyAuthListener

A simplified version of the SpotifyAuth component, returning nothing but still listening for any tokens that it might get.

Name Required Default Description
onAccessToken (token) => {} Function that gets called when an access token is found
localStorage false When true, it will also store the token in window.localStorage under spotifyAuthToken.
noCookie false When true, it does not store the auth token in a cookie named SpotifyAuthToken
// place this on a page that you will redirect to
// if a <SpotifyAuth /> component isn't there already.
<SpotifyAuthListener />

Scopes

As indicated in the table above, scopes are accessible by the camelCased name given by Spotify. A full list can be found here along with their descriptions. These are included in the package mainly to help autocomplete and prevent annoying typos.

import { Scopes } from 'react-spotify-auth'

console.log(Scopes.appRemoteControl) // -> 'app-remote-control'

Persistence

Logging in every time a user wants to use your service is annoying.

To solve that problem, an entry is added to the user's cookies under spotifyAuthToken. As per Spotify docs, it has an expiration time of 2 hours after which the token will stop working. If you want to disable the cookie, you can pass in the prop noCookie.

You can access it directly through cookies.get() or through a library like js-cookie.

If you prefer working with the localStorage API, a prop of localStorage can be passed into the component, which can be accessed at spotifyAuthToken. Keep in mind however, that this does not offer the 2h expiry window.

Changelog

1.4.2 - 1.4.3

  • Dependency upgrades

1.4.1

  • Allowed to be used in iframe (thanks @ffleandro !)

1.3.2 - 1.3.5

  • Dependency upgrades

1.3.1

  • Add show dialogue parameter to url

1.2.1

  • Move to React 17

1.1.0 - 1.1.4

  • Dependency upgrades

1.1.0

  • The real 1.0 update!

  • Added SpotifyAuthListener for multipage applications. This means you don't have to render a SpotifyAuth button on every page that you want to redirect to, or otherwise aquire Spotify credentials.

  • Scopes.all now gives you all the permissions available. Use with caution.

  • Clear up localstorage code to be up to date with documentation

    1.0.1

  • Update readme to remove warning

    1.0.0

  • Added button logo classes

    0.5.3

  • Bump deps for security

    0.5.1

  • Potentially breaking changes by changing the values of default props, and adding new ones. Also better docs woo!

  • Default props:

  • Added props:

    • localStorage, noCookie

License & Attribution

MIT © kevin51jiang

Inspired by this StackOverflow question

FOSSA Status

react-spotify-auth's People

Contributors

dependabot[bot] avatar fossabot avatar kevin51jiang avatar rpeyron avatar timmikeladze avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

react-spotify-auth's Issues

Refresh token?

Hello,

From what I'm reading, you're supposed to always get a refresh token along with your access token. However, I'm not seeing one in the URL after I return from the auth. Is there something I'm missing?

Console.log scopes

When using the main template where would I console.log my scopes? I'd like to get my user to be able to see the data from scopes.
const App = () => { const token = Cookies.get('spotifyAuthToken') return ( <div className='app'> {token ? ( <SpotifyApiContext.Provider value={token}> {/* Your Spotify Code here */} <p>You are authorized with token: {token}</p> </SpotifyApiContext.Provider> ) : ( // Display the login page <SpotifyAuth redirectUri='http://localhost:3000/callback' clientID='1a70ba777fec4ffd9633c0c418bdcf39' scopes={[Scopes.userReadPrivate, 'user-read-email']} // either style will work /> )} </div> ) {console.log(scopes)} (I put it here and it doesn't give back the credentials) } export default App

React 16 or React 17?

The changelog says this:

1.2.1

Move to React 17

But package.json still has this:

 "peerDependencies": {
    "react": "^16.0.0"
  },

And I'm getting dependency conflicts when I install into an ecosystem that uses React 17. So it seems like the changelog is wrong, and this package is still on React 16. Is that correct? If so, can it be upgraded to React 17?

Error: Invalid hook call

Hey! I copied the files that you have in the examples files, trying to replicate the app to see the top tracks of a user, but I'm getting this error when I'm logged (When I have a token in the cookies). Do you know how can I fix it? Thanks!

Cookie keeps getting restored after being deleted?

It seems as if when I am authenticated and I try to delete the cookie with a package like js-cookie or universal-cookie, the cookie keeps getting restored. Sometimes when I try printing the value of spotifyAuthToken using

console.log(Cookies.get('spotifyAuthToken'));

it logs undefined even when I clearly see the token under the Cookies section in developer tools. Why does this happen?

clientID is undefined

When i press the 'Continue with Spotify' button, i get redirected to this url:
https://accounts.spotify.com/authorize?response_type=token&client_id=undefined&scope=user-read-private%20user-read-email&redirect_uri=http://localhost:3000&show_dialog=true

Where client_id is undefined is the url parameter.

import { SpotifyApiContext } from 'react-spotify-api'
import { SpotifyAuth, Scopes } from 'react-spotify-auth';
import { useCookies } from 'react-cookie';
...
const [cookies] = useCookies();
const token = cookies.spotifyAuthToken
    return (
        <>
            {token ?
                (
                    <SpotifyApiContext.Provider value={token}>
                        {/* Your Spotify Code here */}
                        <p>You are authorized with token: {token}</p>
                    </SpotifyApiContext.Provider>
                ) :
                (
                    <SpotifyAuth
                        redirectUri='http://localhost:3000/callback'
                        clientID='my client id'
                        scopes={[Scopes.userReadPrivate, Scopes.userReadEmail]}
                    />
                )}
        </>

Error: Invalid hook call.

I am getting below error after getting token.

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

  1. You might have mismatching versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. You might have more than one copy of React in the same app
    See https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.

I tried all solutions mentioned above.
Please help

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.