Next.js Discord

Discord Forum

How to set and access jwt in cookies?

Unanswered
Transvaal lion posted this in #help-forum
Open in Discord
Transvaal lionOP
Hi I am trying to udnerstand if I set a jwt token on server side would I automatically also get access to the same cookie in the client side?

I am trying to build a component on the frontend whether the user is logged in using the cookie

2 Replies

in general, the main purpose to have server side cookies, httpOnly, is to block malicious client js scripts from accessing them, so it does not make sense to allow client codes to access it. in case of Auth.js design, client side codes use 'useSession()' hook, which invokes server apis in order to delegate authentication processing.
here is a sample code.

function ClientHome() {
    const {data: session} = useSession(); // invoke server apis to get a session.
    const user = session?.user

    useEffect(() => {
            console.log("session.user", session?.user)
        }
        , [session])

    return (
        <main
            style={{...}}
        >
            <div>
                <div>{`${JSON.stringify(user)}`}</div>
                {user ? <div>Logged in</div> : <div>Not logged in</div>}
                {user ? <LogoutButton/> : <LoginButton/>}
            </div>
        </main>
    );
}