Auth0 Home Blog Docs

TypeError: Cannot read property 'idTokenPayload' of undefined

Hey there, I’m getting an error on my Gatsby js app when trying to log in. Here is the error:

TypeError: Cannot read property 'idTokenPayload' of undefined
(anonymous function)
src/utils/auth.js:1
> 1 | import auth0 from "auth0-js"
  2 | import { navigate } from "gatsby"
  3 | 
  4 | const isBrowser = typeof window !== "undefined"

When I log in to my app it works the first time and I can see that authResult is console logging proper values, but the moment I click on any routes or refresh the page, it returns this error. I was working fine until this morning, I didn’t change anything other than some CSS styles.

Here is my auth.js file:

import auth0 from "auth0-js"
import { navigate } from "gatsby"

const isBrowser = typeof window !== "undefined"

const auth = isBrowser
  ? new auth0.WebAuth({
      domain: process.env.AUTH0_DOMAIN,
      clientID: process.env.AUTH0_CLIENTID,
      redirectUri: process.env.AUTH0_CALLBACK,
      responseType: "token id_token",
      scope: "openid profile email",
    })
  : {}

const tokens = {
  accessToken: false,
  idToken: false,
  expiresAt: false,
}

let user = {}

export const isAuthenticated = () => {
  if (!isBrowser) {
    return
  }

  return localStorage.getItem("isLoggedIn") === "true"
}

export const login = () => {
  if (!isBrowser) {
    return
  }

  auth.authorize()
}

const setSession = (cb = () => {}) => (err, authResult) => {

  console.log(authResult);

  localStorage.setItem("userAuthID", authResult.idTokenPayload.sub)
  localStorage.setItem("userIdToken", 'Bearer '+authResult.idToken)
  if (err) {
    navigate("/")
    cb()
    return
  }

  if (authResult && authResult.accessToken && authResult.idToken) {
    let expiresAt = authResult.expiresIn * 1000 + new Date().getTime()
    tokens.accessToken = authResult.accessToken
    tokens.idToken = authResult.idToken
    tokens.expiresAt = expiresAt
    user = authResult.idTokenPayload
    localStorage.setItem("isLoggedIn", true)
    navigate("/account")
    cb()
  }

}

export const silentAuth = callback => {
  if (!isAuthenticated()) return callback()
  auth.checkSession({}, setSession(callback))
}

export const handleAuthentication = () => {
  if (!isBrowser) {
    return
  }

  auth.parseHash(setSession())
}

export const getProfile = () => {
  return user
}

export const logout = () => {
  localStorage.setItem("isLoggedIn", false)
  localStorage.removeItem("userIdToken");
  auth.logout()
}

And here is my callback.js file:

import React, { Component } from 'react'
import { handleAuthentication } from "../utils/auth"
import { navigate } from 'gatsby';

export default class callback extends Component {

  componentDidMount() {
    handleAuthentication();
    setTimeout(() => {
      navigate('/account')
    }, 1500);
  }

  render() {
    return (
      <div>
        <div className="hero is-white is-fullheight">
          <div className="hero-body">
            <div className="container">
              <h1 className="title is-1 is-spaced has-text-centered logo-text">Fottom</h1>
            </div>
          </div>
        </div>
      </div>
    )
  }
}

Can some please help me find what is missing here? Thanks :slight_smile: