Skip to content

Instantly share code, notes, and snippets.

@klequis
Last active March 29, 2024 01:18
Show Gist options
  • Save klequis/fd9c3cf5b025cc26a282ea30ef8ff6da to your computer and use it in GitHub Desktop.
Save klequis/fd9c3cf5b025cc26a282ea30ef8ff6da to your computer and use it in GitHub Desktop.
Modification to Auth0Provider in react-auth0-spa.js
import React, { useState, useEffect, useContext } from 'react'
import createAuth0Client from '@auth0/auth0-spa-js'
const DEFAULT_REDIRECT_CALLBACK = () =>
window.history.replaceState({}, document.title, window.location.pathname)
export const Auth0Context = React.createContext()
export const useAuth0 = () => useContext(Auth0Context)
let _initOptions
const getAuth0Client = () => {
return new Promise(async (resolve, reject) => {
let client
if (!client) {
try {
client = await createAuth0Client(_initOptions)
resolve(client)
} catch (e) {
reject(new Error('getAuth0Client Error', e))
}
}
})
}
export const getTokenSilently = async (...p) => {
const client = await getAuth0Client()
return await client.getTokenSilently(...p)
}
export const Auth0Provider = ({
children,
onRedirectCallback = DEFAULT_REDIRECT_CALLBACK,
...initOptions
}) => {
const [isAuthenticated, setIsAuthenticated] = useState()
const [user, setUser] = useState()
const [auth0Client, setAuth0] = useState()
const [loading, setLoading] = useState(true)
const [popupOpen, setPopupOpen] = useState(false)
useEffect(() => {
const initAuth0 = async () => {
_initOptions = initOptions
const client = await getAuth0Client(initOptions)
setAuth0(client)
if (window.location.search.includes('code=')) {
const {
appState
} = await client.handleRedirectCallback()
onRedirectCallback(appState)
}
const isAuthenticated = await client.isAuthenticated()
setIsAuthenticated(isAuthenticated)
if (isAuthenticated) {
const user = await client.getUser()
setUser(user)
}
setLoading(false)
}
initAuth0()
// eslint-disable-next-line
}, [])
const loginWithPopup = async (params = {}) => {
setPopupOpen(true)
try {
await auth0Client.loginWithPopup(params)
} catch (error) {
console.error(error)
} finally {
setPopupOpen(false)
}
const user = await auth0Client.getUser()
setUser(user)
setIsAuthenticated(true)
}
const handleRedirectCallback = async () => {
setLoading(true)
await auth0Client.handleRedirectCallback()
const user = await auth0Client.getUser()
setLoading(false)
setIsAuthenticated(true)
setUser(user)
}
return (
<Auth0Context.Provider
value={{
isAuthenticated,
user,
loading,
popupOpen,
loginWithPopup,
handleRedirectCallback,
getIdTokenClaims: (...p) => auth0Client.getIdTokenClaims(...p),
loginWithRedirect: (...p) => auth0Client.loginWithRedirect(...p),
getTokenWithPopup: (...p) => auth0Client.getTokenWithPopup(...p),
logout: (...p) => auth0Client.logout(...p)
}}
>
{children}
</Auth0Context.Provider>
)
}
@klequis
Copy link
Author

klequis commented Jul 13, 2019

For my immediate need the only thing that needs to be outside of the hook is getTokenSilently. I haven't thought of a use case where any of the other methods would need to be.

On the other hand isAuthenticated and loading need to get into props so changes trigger render and doing that with a provider seems a good approach. Having the user info available from the provider is also convenient.

I don't really like having one part of of it available via one mechanism and another part via another mechanism but I don't see a better choice.

I do think having the Auth0Client methods wrapped and setting isAuthenticated & loaded the way it is being done is beneficial as if it were not, people would just wrap it themselves because that functionality is needed.

I played with it a bit today but didn't come to any final conclusion. Will do some more in the next few days.

Cheers

@thekamahele
Copy link

@klequis Things seem to work fine the first time around, but on refresh I keep getting a getAuth0Client error. Have you run into this at all?

@klequis
Copy link
Author

klequis commented Aug 28, 2019

@thkamahele

I did have a similar problem on an earlier iteration of this code where the client (line 44) would fall out of scope. To solve it I wrote the getAuth0Client() function and have not had a problem since.

Can you reply with the full error message you are getting?

@aparry3
Copy link

aparry3 commented Sep 6, 2019

What is the let client doing on line 14. Maybe this is JS ignorance issue. Why would client exist on the check on the next line?

@niallmc
Copy link

niallmc commented Sep 18, 2019

@klequis I have tried using this, but it seems to be asking for a new token on every call of getTokenSilently when I use it.

update: This is what I did to resolve my issue:

let _initOptions, _client

const getAuth0Client = () => {
  return new Promise(async (resolve, reject) => {
    let client
    if (!client)  {
      try {
        client = await createAuth0Client(_initOptions)
        resolve(client)
      } catch (e) {
        reject(new Error('getAuth0Client Error', e))
      }
    }
  })
}

export const getTokenSilently = async (...p) => {
  if(!_client) {
      _client = await getAuth0Client()
  }
  return await _client.getTokenSilently(...p)
}

@thekamahele
Copy link

thekamahele commented Sep 18, 2019

I'm having the same issue as @niallmc, and similar code but I'm still getting this error:

auth0-spa-js.production.js:1026 Uncaught TypeError: Cannot read property 'close' of undefined at o

I'm thinking it might be related to this issue

@iamchathu
Copy link

When initializing the _initOptions get undefined

@artem-alek
Copy link

@klequis I have a similar implementation here, my question is where did you place your <Auth0Context.Provider> with Redux? Did you completely avoided redux state for all auth0 client work and relied on getSilentToken() for all your api calls with Redux? I am having trouble connecting the dots on either trying to get autho0Client into redux state or wrap the <Auth0Context.Provider> around

@MStumpp
Copy link

MStumpp commented Apr 9, 2020

@artem-alek Did you find a solution. Facing a similar question.

@carlank
Copy link

carlank commented May 8, 2020

I've been having this same issue. I manually initialized _initoptions with the props that I was passing to Auth0Provider, and it seems to have resolved the issue.

@afrancht
Copy link

@stevehobbsdev @klequis is this resolved? I feel like being able to call the React-SDK from an action is basic when you have a MERN stack. Surprised this is not available through the SDK yet as I also face the Hooks error when trying.

@HansBouwmeester
Copy link

HansBouwmeester commented Dec 12, 2020

Same issue/question here. Wondering if there's a good solution to this?

Edit: here's the code based on the above discussions that (so far) seems to work. Would be nice to see a fully Auth0 supported version though.

// Note: this code extends '@auth0/auth0-react.js' which is built 
// on '@auth0/auth0-spa-js' which exports 'createAuth0Client'.
import createAuth0Client from '@auth0/auth0-spa-js'

let _initOptions = {
  domain: AUTH_DOMAIN,
  client_id: AUTH_WEB_APP_CLIENT_ID,
}
let _client

const getAuth0Client = () => {
  return new Promise(async (resolve, reject) => {
    let client
    if (!client) {
      try {
        client = await createAuth0Client(_initOptions)
        resolve(client)
      } catch (e) {
        reject(new Error('getAuth0Client Error', e))
      }
    }
  })
}

export const getApiToken = async (...p) => {
  if (!_client) {
    _client = await getAuth0Client()
  }
  return await _client.getTokenSilently(...p)
}

@iamchathu
Copy link

@Gra55h0pper Auth0 has Updated SDK now. https://github.com/auth0/auth0-react

@HansBouwmeester
Copy link

@iamchathu, yes, auth0-react is the SDK I'm using.
If you look at the auth0-react sources you can see it calls auth0-spa-js (which exports createAuth0Client) under the hood.

Most importantly though, auth0-react (still) doesn't support getTokenSilently outside of a component (i.e. without the need for using a React Hook), does it?

@fieldju
Copy link

fieldju commented Dec 15, 2020

@Gra55h0pper

Are you using your snippet to just create an extra client that getApiToken uses and you use this in addition to auth0-react?

@HansBouwmeester
Copy link

@fieldju, yes, at this point in time I'm wrapping the App in auth0-react's Auth0Provider for general user-login besides using the snippet for getting API-tokens. I'm assuming that indeed means two clients are being created. Though I haven't seen any issues with that, I think it would be nice if Auth0 would provide a clean solution.

@HansBouwmeester
Copy link

HansBouwmeester commented Dec 17, 2020

Update: I do not understand why, but I found my snippet above does not work for Safari where it works fine for Chrome (???).
Also, I learned Auth0 recommends against storing the access-token in local storage (Redux in my case). See: https://auth0.com/blog/complete-guide-to-react-user-authentication/#Calling-an-API. I guess this may explain why they don't support getting a token outside of a component?
Anyway, I'm changing the architecture of my App getting the getAccessTokenSilently function from the useAuth0 hook in every UI component that needs to call the API and then passing it explicitly to the redux-thunk action that's calling the API-endpoint. It seems much more verbose than necessary, but it works.

@daltonfury42
Copy link

@Gra55h0pper This is how I am solving this for my project.

A PR with usage examples: SimplQ/simplQ-frontend#483

@HansBouwmeester
Copy link

@daltonfury42 Thanks much. I'll take a look. It will unclutter my code.
SimplQ looks cool! I think there's definitely space for an App like that!

@nelsonfncosta
Copy link

nelsonfncosta commented Jul 16, 2021

For anyone reaching this gist looking for a solution for @auth0/auth0-react
I have a working approach here https://stackoverflow.com/a/68407340/6469059

@luksiv
Copy link

luksiv commented Jan 4, 2022

@nelsonfncosta Thank you so much, this is absolutely what I wanted and after so much time struggling and dropping my projects because of this, I can finally say this is what I wanted to begin with. +1 sir.

Would love any insight from others, if this solution is robust and can it have any pitfalls?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment