useSession() returning status unauthenticated
Unanswered
Rahul posted this in #help-forum
RahulOP
i am using <SessionProvider > wrapper in my main layout.tsx file where passing state session from auth.js file in my root directory
while fetching session in protected write it is returning unauthenticated while refreshing the page it is showing sessin data for a moment and then showing as unauthenticated
I am attaching a video of my error
while fetching session in protected write it is returning unauthenticated while refreshing the page it is showing sessin data for a moment and then showing as unauthenticated
I am attaching a video of my error
// layout.tsx
import type { Metadata } from "next";
import { Inter } from "next/font/google";
import "./globals.css";
import { SessionProvider } from "next-auth/react";
import { auth } from "@/auth";
const inter = Inter({ subsets: ["latin"] });
export const metadata: Metadata = {
title: "Create Next App",
description: "Generated by create next app",
};
export const RootLayout = async ({
children,
}: {
children: React.ReactNode;
}) => {
const session = await auth();
return (
<SessionProvider session={session}>
<html lang="en">
<body className={inter.className}>{children}</body>
</html>
</SessionProvider>
);
};
export default RootLayout;6 Replies
RahulOP
// app/(protected)/settings/page.tsx
"use client";
import { logout } from "@/actions/logout";
import { useCurrentUser } from "@/hooks/use-current-user";
import { useSession } from "next-auth/react";
const SettingsPage = () => {
const session = useSession();
const user = useCurrentUser();
const onClick = () => {
logout();
};
return (
<div>
<p>{JSON.stringify(session)}</p>
<button onClick={onClick}>SignOut</button>
</div>
);
};
export default SettingsPage;// logout server action
"use server";
import { signOut } from "@/auth";
export const logout = async () => {
await signOut({
redirectTo: "/",
});
return;
};// session and jwt callbacks in auth.ts
async session({ session, token }) {
console.log("Session");
if (token.sub && session.user) {
session.user.id = token.sub;
}
if (token.role && session.user) {
// @ts-ignore
session.user.role = token.role as UserRole;
}
return session;
},
async jwt({ token }) {
console.log("JWT");
if (!token.sub) return token;
const existingUser = await getUserById(token.sub);
if (!existingUser) return token;
token.role = existingUser.role;
return token;
},RahulOP
i have also tried creating a provider component and wrapping in my main layout
facing issue since few days
pls help
// dependencies
"next": "14.2.3",
"next-auth": "^5.0.0-beta.17",
"react": "^18",
"react-dom": "^18",