Search code examples
sessionjwtprismanext.js13next-auth

How do I use next auth getServerSession in next js 13 beta server component in app directory


I'm using next auth v4 with next js 13 beta with server component, and everything works fine. But I have a situation where I will need to know the logged user id, since I'm using next auth, I have access to the session, I can use useSession() but then I will need to make the component a client component, So I want to use it on the server, I can use getServerSession in API since I have access to req & res object, but in next js beta with new app dir, I can't do it. Please let me know if you know how to fix the issue. Thank you

import { getServerSession } from "next-auth";
import { authOptions } from "@/pages/api/auth/[...nextauth]";

const Test = async () => {
    const user_id = 1; // How do I get user id from session, user_id is available in session

    // I don't have access req & res object in server component.
    const data = await getServerSession(request, response, authOptions);

    console.log(data);

});
    return (
        <></>
    );
};

export default Test;

Didn't find enough information


Solution

  • I found an answer, in next js 13, you wont need to use request & response object, just use the authOptions, it will work

    import { getServerSession } from "next-auth";
    import { authOptions } from "@/pages/api/auth/[...nextauth]";
    
    const Test = async () => {
    
        const data = await getServerSession(authOptions);
    
        console.log(data);
    
    });
        return (
            <></>
        );
    };
    
    export default Test;