Next.js Discord

Discord Forum

Can't access the session inside a server action

Unanswered
Brewer's Blackbird posted this in #help-forum
Open in Discord
Brewer's BlackbirdOP
I'm using the "next-safe-action" library for server actions.

export const protectedAction = createSafeActionClient({
  async middleware() {
    const session = await getServerAuthSession();

    console.log(session);

    if (!session?.user) {
      throw new Error("Unauthorized!");
    }

    return { session };
  },
});


Even if I'm authenticated, I get this error and the console log result is null

1 Reply

@Brewer's Blackbird I'm using the "next-safe-action" library for server actions. ts export const protectedAction = createSafeActionClient({ async middleware() { const session = await getServerAuthSession(); console.log(session); if (!session?.user) { throw new Error("Unauthorized!"); } return { session }; }, }); Even if I'm authenticated, I get this error and the console log result is null
Jersey Wooly
import { authOptions } from '@/app/api/auth/[...nextauth]/route';
import { getServerSession } from 'next-auth';


export const protectedAction = createSafeActionClient({
  async middleware() {
   const session = await getServerSession(authOptions);

    if (!session?.user) {
      throw new Error('No session found');
    }

    return { session };
  },
});


I encountered the same issue as you and I resolved it by usingthe getServerSession function from NextAuth.

https://next-auth.js.org/configuration/nextjs