Next.js Discord

Discord Forum

Set Next Auth cookie with server actions after registration

Unanswered
Giant panda posted this in #help-forum
Open in Discord
Giant pandaOP
Is there a way to do this? I usually just do signIn on frontend but this would be better

8 Replies

Of course there is!
Server actions
'use server';

import { cookies } from "next/headers";
import { redirect } from "next/navigation";


export async function Login() {
    try {
        
        cookies().set('Auth-Cookie', 'abc123')
        return true;
    }
    catch (err) {
        console.log(err)
        return false
    }
}

export async function Logout() {
    try {
        cookies().delete('Auth-Cookie');
    }
    catch (err) {
        console.log(err)
        return false;
    }
    redirect('/home');
}


Page.js
'use client';

import { Button } from "@/components/ui/button";
import { Login, Logout } from "./action";

export default function Page() {
    const login = async () => {
        return await Login();
    }

    const logout = async () => {
        return await Logout();
    }
    return (
        <>
            <Button onClick={() => login()}>Login</Button>
            <Button onClick={() => logout()}>Logout</Button>
        </>
    );
}
A client component has to call a server action for it to be able to set a cookie, thats why the page is 'use client'
@Jboncz Of course there is!
Giant pandaOP
i am asking how to get the next auth session cookie
i am aware you can do that
You want to get it client side? Im not sure what your asking
Giant pandaOP
what im asking is not possible anyway, nextauth is a very closed off library. i am asking to generate nextauth session cookie
Okie dokie. If you say so.