Next.js Discord

Discord Forum

Is it ok to call a server action directly in a client component?

Unanswered
Bluethroat posted this in #help-forum
Open in Discord
BluethroatOP
Hi, I'm new to Next.js. Using V14.1. I have a server action like this:
export const destroyUserSession = async () => {
    const userSession = await getIronSession(cookies(), sessionOptions);
    userSession.destroy();
}

And I import it and use it like this in a client component:
'use client'

import { destroyUserSession } from "@/actions/session";
import { useRouter } from "next/navigation";

export default function LogoutButton() {
    const router = useRouter();
    const handleLogout = async (e) => {
       
      destroyUserSession();

      router.push('/login');
    }
    return (
      <>
         <button onClick={handleLogout}>Logout</button>
      </>
   )
}

Is it OK to do that? It works... but it seems odd I must say.

6 Replies

Yes that is entirely the reason for server components
Instead of you hitting api's you just call a server action
Recently I've been using the approach of wrapping every server action of mine a custom function like publicAction or privateAction
this ensure that my actions are protected whenever I need
I can share some examples if anyone is interested