Skip to content

How to access user's session in root layout? #175

Answered by sergiodxa
kwiat1990 asked this question in Q&A
Discussion options

You must be logged in to vote

As you said, get the authenticated user data on root.tsx or any other layout or pathless layout route, then pass that using props or a custom context.

If you read the authenticated user data on root.tsx, you could also use the useMatches hook to read the data anywhere. For example:

// app/root
export let loader: LoaderFunction = async ({ request }) => {
  let user = await authenticator.isAuthenticated(request)
  // probably more code here
  return json({ user })
}
// app/hooks/use-user
export function useUser(): User | null {
  let [rootMatch] = useMatches()
  return rootMatch.data.user
}

// you can also create a hook to throw an error if user is null
// for routes where you know the use…

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@kwiat1990
Comment options

@sergiodxa
Comment options

Answer selected by kwiat1990
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants