Auth0 failing after F5 in React

I have this code:

import { useState, useEffect } from 'react'
import { useAuth0 } from '@auth0/auth0-react'
import Profile from './components/Profile'
import Login from './components/Login'
import Quotes from './components/Quotes'
import './App.css'

interface Quote {
  quote: string;
  author: string;
  tags: string[];
}

function App() {
  const [quotes, setQuotes] = useState<Quote[]>([])
  const { isAuthenticated, isLoading, getAccessTokenSilently } = useAuth0()

  useEffect(() => {
    if (isAuthenticated) {
      (async () => {
        const token = await getAccessTokenSilently()
      
        const response = await fetch('https://quotesapi.fly.dev/api/quotes/random', {
          headers: {
            Authorization: `Bearer ${token}`
          }
        })
        
        const data = await response.json()
        setQuotes(data)
      })()
    }
  }, [isAuthenticated, getAccessTokenSilently])

  if (isLoading) {
    return <div className="loading">Loading...</div>
  }

  return (
    <div className="app-container">
      <h1>Quotes API</h1>
      
      {isAuthenticated ? (
        <div>
          <Profile />
          {quotes.length > 0 && <Quotes quotes={quotes} />}
        </div>
      ) : (
        <div className="login-container">
          <p>Please log in to see quotes</p>
          <Login />
        </div>
      )}
    </div>
  )
}

export default App

Everything is good while I don’t hit the F5, I can login, send token to my BE. The Auth0 session is stored in local memory. On hitting F5 the session is still there however calling /authorize fails with 400 Bad request.

I found one of the solutions: if I add cacheLocation as localStorage like this:

import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import { Auth0Provider } from '@auth0/auth0-react'
import './index.css'
import App from './App.tsx'

createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <Auth0Provider
      domain="dev-wzfkg4o26oz6ndmt.us.auth0.com"
      clientId="v0YzxpAoJP6tLyW29TnZEuqStYkUF5fY"
      authorizationParams={{
        redirect_uri: window.location.origin,
        audience: "quotes.programmersdiary.com"
      }}
      **cacheLocation="localstorage"**
    >
      <App />
    </Auth0Provider>
  </StrictMode>,
)

However if my knowledge is correct using localStorage is discouraged due to XSS attacks.
Any better way to solve this refresh page problem?

Hi @EvalVis

Welcome to the Auth0 Community!

Thank you for posting your question. I’ve found the knowledge solution that should probably solve your issue with 400 Bad Request after the user hits F5. Can you try to implement onRedirectCallback function in your code → Auth0ProviderOptions | @auth0/auth0-react. You can read more about that here → State and Code Parameters Stuck in URL react-auth0 - User Getting Logged Out on Page Refresh

Thanks
Dawid

1 Like