Next.js: useSession() hook does not seem to refresh when session is changed from the server

Hey everyone, I am currently working on adding a login system to my Next.js website. So far everything is working as expected, but I ran into some trouble when trying to automatically redirect users from e.g. the login page to the dashboard after they've clicked the magic link for example. Here's some information: - Sign-in is called from a Server Component using the API. - Sign-out is also called from a Server Component. - The useSession() hook is within a Client Component - I have tried to disable "cookieCache" but I do not see any difference. - nextCookies plugin is included at the bottom of my plugins array. There's two situations I've attempted to test this with: 1. Open page "/login" on one screen, click the magic link and check if the "/login" screen gets a change of state to useSession(). 2. Open two pages on "/app" with a valid session, click the server-side "sign-out" button on one of the pages. Both of these test-cases failed, and even waiting for over 5+ minutes did not ever refresh the session on the client. I've included some screenshots of the code I'm currently working with and the configuration I have. Please let me know if anyone knows anything! Please note that the screenshot does not show it, but the SessionWatcher is in the main layout file (server component) and at the top of the SessionWatcher file is "use client";.
No description
No description
No description
No description
Solution:
Perhaps this is simply not the right usage for useSession, since it does work with a cookie and the server cannot reactively send new info to clients without a refresh. I just added a 5000ms polling effect and it does the trick
Jump to solution
2 Replies
Nullified
NullifiedOP4mo ago
Sidenote: it seems like after about 10 minutes the page does in fact change (even though the URL does not, that's a mistake on my part) I'm testing it again with the other testcase This does not seem to work ^ Also calling the signOut method from authClient does not make a difference! Calling refetch() from one page does also not automatically trigger the effect on another open page...
Solution
Nullified
Nullified4mo ago
Perhaps this is simply not the right usage for useSession, since it does work with a cookie and the server cannot reactively send new info to clients without a refresh. I just added a 5000ms polling effect and it does the trick

Did you find this page helpful?