Replies: 4 comments 1 reply
-
If storing sessions in a database, use the session token (next-auth.session-token) on the client side to authenticate the user on the server. This should persist beyond reload so will be there on visit. These cookies are HTTP Only, meaning you cannot read nor write them on the client-side. Fetch allows you to pass the On server-side, you can access session token via |
Beta Was this translation helpful? Give feedback.
-
And here's the middleware on the server side to validate session:
|
Beta Was this translation helpful? Give feedback.
-
You can use import { getServerSession } from "next-auth/next";
const session = await getServerSession(context.req, context.res, authOptions);
if (session) {
if (session.user?.name === null) {
... |
Beta Was this translation helpful? Give feedback.
-
Please note this has changed in v5: https://authjs.dev/getting-started/migrating-to-v5#authenticating-server-side |
Beta Was this translation helpful? Give feedback.
-
Question 💬
Hi,
I have a question about the right way(s) to handle the authentication state of a user with next-auth. I'm working on platform that authenticates with keycloak and I am trying to let next-auth do the job. After several hours of implementing it I've finally found a working solution. But to be honest, I'm sure there must be a better one.
The thing I wonder most about is the way to properly check if a user is logged in or not on server-side. The function providing the current session is
unstable_getServerSession()
but it's officially not recommended. Our application is completely password-protected and does API calls on every page. So to get the access key the session needs to be evaluated on every page request which makes the function basically a core component of the app. I have serious doubts about that and wonder how others help themselves.My working solution also handles the unauthenticated state on server-side in a hacky way. The thing is that I need to render the page somehow to let the client-side "take over" and trigger a redirect in case of an unauthenticated state (I use
useSession()
in a SessionProvider context – which works very well). I accomplished this by simply returning{props: {}}
or{ notFound: true }
. Returning an error is actually right at this place but a 401 would've been nicer than a 404 (but unavailable in next's API). Also I thought about temporarily redirecting the user to keycloak's login page but this ended in a redirect loop between keycloak's and next's page.The same issues I had when I tried middleware to achieve this.
So what would conceptionally be the right way to go in this case? And I don't think the case I'm describing is very uncommon as usually next projects include server-side and client-side rendering...
How to reproduce ☕️
pages/_app.tsx
AuthGuard.tsx
pages/index.tsx
utils.ts
Contributing 🙌🏽
No, I am afraid I cannot help regarding this
Beta Was this translation helpful? Give feedback.
All reactions