Next.js Discord

Discord Forum

unable to proceed with server action that import "server-only"

Answered
Polish posted this in #help-forum
Open in Discord
PolishOP
So i have this this is the data access dal.ts layer that check the user auth
import 'server-only'
import { cookies } from 'next/headers'
import { decrypt } from '@/app/lib/session'
import { cache } from 'react'

export const verifySession = cache(async () => {
  const cookie = cookies().get('session')?.value
  const session = await decrypt(cookie)
  if (!session?.user) {
    return { isAuth: false, user: undefined }
  }
  return { isAuth: true, user: session?.user as User }
})

this is one of the server action
import { verifySession2 } from "@/app/lib/dal";
import { getNotes } from "@/db/controller/notecontroller";

export async function getAllNotesAction(): Promise<PartialNote[] | { error: string }> {
  try {
    const { isAuth, user } = await verifySession();
    if (!isAuth || !user) {
      return ({ error: "Authorization failed." });
    }
    const notes = await getNotes(user.user_id);
    return notes;
  } catch (error) {
    return ({ error: "Failed to fetch the user or shared notes." });
  }
}

due to that server-only function required for next/head i am unable to do this in client component

//client component
useEffect(() => {
    async function fetchData() {
      const res = await getAllNotes();
      if ('error' in res) {
        updateError(res)
     }
      else {
        updateNoteList(res)
      }
    }
    fetchData()
  }, [])

is there any way i can make this work , somebody please give me hint,solution,... anything that helps.
Answered by joulev
add "use server" to the top of the file exporting the server action
View full answer

3 Replies

Answer
PolishOP
&1159364112724262982 thanks , i am so stupid , you are god, one more question, isn't that if the nothing was declared at top, it would be 'use server' by default?
@Polish <@&1159364112724262982> thanks , i am so stupid , you are god, one more question, isn't that if the nothing was declared at top, it would be 'use server' by default?
nope, if nothing is declared at the top, nothing happens. page, layout and similar files are server component by default, server component != "use server"