dejoma
dejoma

Reputation: 504

getServerSessoin returns session while useSession does not - NextJS13 with /app dir and next-auth

Some notes:

This is the session callback in authOptions:

async session({ session, token, user }) {
    session.user = user;
    return session;
}

The middleware.ts is very simple with temporarily just this:

export { default } from 'next-auth/middleware';

export const config = {
  matcher: ['/profile'] // Only /profile needs authentication
};

I have tried switching to a JWT strategy too, setting an initial session in the sessionprovider based on SO but without succes...

Upvotes: 0

Views: 727

Answers (2)

Aklil Solomon
Aklil Solomon

Reputation: 1

Create session provider component first

auth-provider.ts file

'use client';

    import { SessionProvider } from 'next-auth/react';
    
    type Props = {
        children: React.ReactNode;
    };
    
    export default function AuthProvider({ children }: Props) {
        return <SessionProvider>{children}</SessionProvider>;
    }

and wrap it in layout.ts file in main app directory like this

layout.ts file

import "./globals.css";
import type { Metadata } from "next";
import { getServerSession } from "next-auth";

import AuthProvider from "./auth-provider";

export default function RootLayout({
    children,
}: {
    children: React.ReactNode;
}) {
 const session = await getServerSession();
    return (
        <AuthProvider session={session}>
            <html lang="en">
                <body className={font.className}>
                        attribute="class"
                        defaultTheme="system"
                        enableSystem
                    >
                        <main>{children}</main>
                </body>
            </html>
        </AuthProvider>
    );
}

Upvotes: 0

Ahmed Sbai
Ahmed Sbai

Reputation: 16219

the user object may be undefined in the session callback, if you are using JWT strategy, you have to update the token first then update the session from it.
to do so, you have to add the JWT callback:

async jwt({ user, token }) {
  if (user) {
    token.user = user;
  }
  return token
}
async session({ session, token}) {
    session.user = token.user;
    return session;
}

Upvotes: 0

Related Questions