Why identity doesn't have user via context.clientContext in other functions

I am using netlify identity and want to protect API routes for non-logged in users. Issue is that in context.clientContext in custom function is doesn’t return any user info.

Site URL https://transcendent-pegasus-7ff91f.netlify.app as you can see login and logout is working fine but if you go to https://transcendent-pegasus-7ff91f.netlify.app/.netlify/functions/data which is a function which will return data and user info but it’s not sending any user info.

const handler = async function (event, context) {
  const { identity, user } = context.clientContext

  const data = { value: '###' }
  return {
    statusCode: 200,
    body: JSON.stringify({ identity, user, msg: data.value }),
  } catch (error) {
    return {
      statusCode: 500,
      // Could be a custom message or object i.e. JSON.stringify(err)
      body: JSON.stringify({ msg: error.message }),

module.exports = { handler }

Also console.log(user) outputs undefined.

What’s the possible reason?

Are you calling the function with authorization: Bearer <token> header?

I don’t know how to call this way. Where is the token?

Depends on how you’ve implemented Netlify Identity on the front-end. If you’re using the Identity Widget, you’d have to get the token using the methods explained here:

For example:

fetch('/.netlify/functions/data', {
  headers: {
    authorization: `Bearer ${netlifyIdentity.currentUser().token.access_token}`

Note: My memory is hazy about the token location. I know it’s in netlifyIdentity.currentUser(), just not sure if it’s in netlifyIdentity.currentUser().token.access_token. You could do a console.log(netlifyIdentity.currentUser()) to find out.

Thanks it worked. Access token is also available in page cookies.

That’s a http-only cookie - won’t be available through JavaScript.

1 Like