[GH-ISSUE #308] useSession() not working properly on client side #8213

Closed
opened 2026-04-13 03:18:51 -05:00 by GiteaMirror · 5 comments
Owner

Originally created by @0xPratikPatil on GitHub (Oct 23, 2024).
Original GitHub issue: https://github.com/better-auth/better-auth/issues/308

Describe the bug
I was using useSession() from my auth-client to secure some pages, but it is not consistently detecting the session. It requires multiple requests to get the session, and it doesn't detect it on the first request. I was using the following code:

To Reproduce

	const router = useRouter();
	const {
		data: session,
		isPending,
		error
	} = useSession()
	console.log("Session:", session)
	if(!session){
		router.push("/login")
	}

Expected behavior
It must detect the logged-in session in one go for other functionality to work properly.

Screenshots
As you can see, it made the 8 requests but was unable to get a logged-in session initially. My user was redirected to the login page even after logging in.
Screenshot from 2024-10-23 19-01-44

Desktop (please complete the following information):

  • OS: Kali
  • Browser: Brave

Additional context

  • better-auth: 0.4.13
Originally created by @0xPratikPatil on GitHub (Oct 23, 2024). Original GitHub issue: https://github.com/better-auth/better-auth/issues/308 **Describe the bug** I was using `useSession()` from my auth-client to secure some pages, but it is not consistently detecting the session. It requires multiple requests to get the session, and it doesn't detect it on the first request. I was using the following code: **To Reproduce** ``` const router = useRouter(); const { data: session, isPending, error } = useSession() console.log("Session:", session) if(!session){ router.push("/login") } ``` **Expected behavior** It must detect the logged-in session in one go for other functionality to work properly. **Screenshots** As you can see, it made the 8 requests but was unable to get a logged-in session initially. My user was redirected to the login page even after logging in. ![Screenshot from 2024-10-23 19-01-44](https://github.com/user-attachments/assets/6112b2ef-95c5-4d12-b214-a25fd52d9a78) **Desktop (please complete the following information):** - OS: Kali - Browser: Brave **Additional context** - better-auth: 0.4.13
GiteaMirror added the locked label 2026-04-13 03:18:51 -05:00
Author
Owner

@Bekacru commented on GitHub (Oct 23, 2024):

First, get rid of the if block, since the session will be empty on the initial render it'll always be redirecting. You can check if isLoading is false before redirecting. Also, keep in mind that if there’s a re-render or another subscription that triggers the useSession, that might be why you’re seeing it sent twice.

<!-- gh-comment-id:2432314520 --> @Bekacru commented on GitHub (Oct 23, 2024): First, get rid of the `if` block, since the session will be empty on the initial render it'll always be redirecting. You can check if `isLoading` is false before redirecting. Also, keep in mind that if there’s a re-render or another subscription that triggers the `useSession`, that might be why you’re seeing it sent twice.
Author
Owner

@firzanarmani commented on GitHub (Oct 24, 2024):

First, get rid of the if block, since the session will be empty on the initial render it'll always be redirecting. You can check if isLoading is false before redirecting. Also, keep in mind that if there’s a re-render or another subscription that triggers the useSession, that might be why you’re seeing it sent twice.

On initial render, isPending and isRefetching is also false, which would cause the immediate redirect. I'm also trying out the same thing, where this redirect happens in an authenticated-only layout/nested routes, to the login page (as seen in Tanstack Router's Authenticated Routes)

How about something like isInitialLoading so that we can track this initial render fetch/loading?

<!-- gh-comment-id:2434244705 --> @firzanarmani commented on GitHub (Oct 24, 2024): > First, get rid of the `if` block, since the session will be empty on the initial render it'll always be redirecting. You can check if `isLoading` is false before redirecting. Also, keep in mind that if there’s a re-render or another subscription that triggers the `useSession`, that might be why you’re seeing it sent twice. On initial render, `isPending` and `isRefetching` is also `false`, which would cause the immediate redirect. I'm also trying out the same thing, where this redirect happens in an authenticated-only layout/nested routes, to the login page (as seen in Tanstack Router's Authenticated Routes) How about something like `isInitialLoading` so that we can track this initial render fetch/loading?
Author
Owner

@Bekacru commented on GitHub (Oct 24, 2024):

You're right, isPending is false on the initial render. Starting from the next release, it will be true. For now, you can also check if both error and data are null by using !data && !error.

<!-- gh-comment-id:2434257284 --> @Bekacru commented on GitHub (Oct 24, 2024): You're right, `isPending` is `false` on the initial render. Starting from the next release, it will be `true`. For now, you can also check if both `error` and `data` are `null` by using `!data && !error`.
Author
Owner

@0xPratikPatil commented on GitHub (Oct 24, 2024):

I used this code, and it worked, but it gave errors in the backend. Could you provide sample code on how to implement this without using an if statement, as mentioned earlier?

  const router = useRouter();
  const { data: session, isPending, error, isRefetching } = client.useSession();
  console.log("Session:", session);
  if (!session && !error) {
    router.push("/login");
  }
Screenshot 2024-10-24 at 6 49 20 PM
 ⨯ next/dist/src/client/components/app-router.tsx (146:23) @ __NEXT_APP_NAV_FAIL_HANDLING
 ⨯ uncaughtException: ReferenceError: location is not defined

      const url = new URL(addBasePath(href), location.href)
  145 |
> 146 |       if (process.env.__NEXT_APP_NAV_FAIL_HANDLING) {
      |                       ^
  147 |         window.next.__pendingUrl = url
  148 |       }

Version : ^0.5.4-beta.4

<!-- gh-comment-id:2435288767 --> @0xPratikPatil commented on GitHub (Oct 24, 2024): I used this code, and it worked, but it gave errors in the backend. Could you provide sample code on how to implement this without using an if statement, as mentioned earlier? ``` const router = useRouter(); const { data: session, isPending, error, isRefetching } = client.useSession(); console.log("Session:", session); if (!session && !error) { router.push("/login"); } ``` <img width="1131" alt="Screenshot 2024-10-24 at 6 49 20 PM" src="https://github.com/user-attachments/assets/d5ae6037-fa34-4940-99f7-4897f13b371d"> ``` ⨯ next/dist/src/client/components/app-router.tsx (146:23) @ __NEXT_APP_NAV_FAIL_HANDLING ⨯ uncaughtException: ReferenceError: location is not defined ``` ``` const url = new URL(addBasePath(href), location.href) 145 | > 146 | if (process.env.__NEXT_APP_NAV_FAIL_HANDLING) { | ^ 147 | window.next.__pendingUrl = url 148 | } ``` **Version : ^0.5.4-beta.4**
Author
Owner

@Bekacru commented on GitHub (Nov 3, 2024):

This is most likely due to using it in a server environment. Feel free to reopen if you believe this is still a valid issue with Better Auth

<!-- gh-comment-id:2453320609 --> @Bekacru commented on GitHub (Nov 3, 2024): This is most likely due to using it in a server environment. Feel free to reopen if you believe this is still a valid issue with Better Auth
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github-starred/better-auth#8213