clientContext.user is missing in from context.clientContex regular netlify function

netlify app: objective-golick-ba8922.netlify.app/

When I make a request to the account function the user is missing from context.clientContext. This doesn’t happen all the time. Upon a new deploy, I can log in no problem and see the user object in my function’s log. Then, if I wait about 20 or so minutes and hit refresh or open the app in a new tab, I will run into an error (as expected by the code in the function), but the error shouldn’t be happening because the user is logged in and that is checked BEFORE the request is made. I’m not sure what is going on…

in my functions/account.js file:

exports.handler = async function (event, context) {
  // check if logged in, return 401 if not
  if (!context.clientContext.user) {
    console.log("User not logged in?")
    console.log(context.clientContext)
    return {
      statusCode: 401,
      body: JSON.stringify({ msg: 'must be logged in' })
    }
  }
  console.log("User logged in?")
  console.log(context.clientContext)

In pages/index.js:

import Head from 'next/head'
import Link from 'next/link'
import { useContext, useEffect, useState } from 'react'
import AuthContext from '../stores/authContext'


export default function Home() {
  const { user, authReady, login, logout } = useContext(AuthContext)

  // create two states, one for the user's plan, and the other for errors
  const [account, setAccount] = useState(null)
  const [error, setError] = useState(null)


  // TODO figure out https://answers.netlify.com/t/could-not-access-user-from-context-inside-netlify-function/41801

  // https://reactjs.org/docs/hooks-effect.html for more information on useEffect
  useEffect(() => {
    if (authReady && user) {
      fetch('/.netlify/functions/account', user && {
        // only attach headers if user is logged in, but still make the request regardless
        headers: {
          'Authorization': `Bearer ${user.token.access_token}`
        }
      })
        .then(res => {
          if (!res.ok) {
            login()
            throw Error('Must be logged in to view plan')
          }
          return res.json()
        })
        .then(data => {
          // success, set states
          setError(null)
          setAccount(data)
          console.log(data)
        })
        .catch((err) => {
          // request failed, catch error and set states
          setError(err.message)
          setAccount(null)
        })
    }
  }, [user, authReady])
...

ex:

FWIW I’m following a flavor of GitHub - iamshaunjp/next-netlify-identity at lesson-10

Thanks!

Hey @zricethezav,

That is strange. This doesn’t normally happen. Would it be possible for you to generate an Identity account for the Support Team to check this behaviour?

Hi @hrishikesh,

I would be happy to if you could give me some instructions on how to do that. Thanks!

Zach

Hey @zricethezav,

You could setup any random user in your Identity instance and share its credentials with me privately.

Depending on how your confirmation settings are set in your instance, you might have to confirm the email address of that new user.

is this still open, because same functions worked for me and now the context.user.sub is missing again. I had it once before and it disappeared sort of magically. hard to put into production if something like this happens.

We have never confirmed the previously reported issue to exist. It still works fine in our tests. Maybe the Identity user token that you’re trying to use is expired after its 1 hour time limit?

Hey @hrishikesh -

Was this every resolved? I am having the same issues for my site. Locally, I can log context.clientContext.user and get an object but when I deploy, context.clientContext.user is undefined. It’s making my verification kinda moot right now and would love any help!

My handler:

import { Handler, HandlerEvent, HandlerContext } from "@netlify/functions"

export const handler: Handler = async (
	event: HandlerEvent,
	context: HandlerContext
) => {
	console.log(context)

	if (context.clientContext?.user) {
		*** code to verify user never being hit in production but logs successfully locally***
		try {
			return {
				statusCode: 200,	
			}
		} catch (err) {
			return {
				statusCode: 500,
				body: JSON.stringify({ message: err.message }),
			}
		}
	}

	return {
		statusCode: 401,
		body: JSON.stringify({
			message: "Unauthorized: No user ID found",
		}),
	}
}

Can you confirm what I asked before:

If that’s not the case, please share site name and steps to reproduce the issue.