Need some clarity on getting user and saving it
Unanswered
Rex posted this in #help-forum
RexOP
Ok I am working first time with authentication and need some guidance.
I am using next app directory, next-auth and mongodb
When a user logs in session token is returned and stored in the brower. I have the middleware setup and in that i redirect user to either home or login based on the presence of session token.
Using the
Should I get the
If this is the approach then where should I code the decoding part because my layout.js and page.js are server components.
once I have the logged in user I will be able to fetch other data (eg profile) based on the id
I am using next app directory, next-auth and mongodb
When a user logs in session token is returned and stored in the brower. I have the middleware setup and in that i redirect user to either home or login based on the presence of session token.
Using the
getCurrentUser() function I get the logged in user data in the server components but how can I get the logged in user in the client components? Should I get the
next-auth.session-token and then somehow decode it then store in zustand store persist it so that accessible across all the client compoent by making request to the store?If this is the approach then where should I code the decoding part because my layout.js and page.js are server components.
once I have the logged in user I will be able to fetch other data (eg profile) based on the id
import { getServerSession } from "next-auth";
export async function getSession() {
return await getServerSession(authOptions);
}
export async function getCurrentUser() {
try {
const session = await getSession();
if (!session?.user.email) {
return null;
}
const currentUser = await prisma.user.findUnique({
where: {
email: session.user.email,
},
});
if (!currentUser) {
return null;
}
return currentUser;
} catch (error) {
return null;
}
}2 Replies
RexOP
bump
Japanese flying squid
.