kevin8426
kevin8426
TTCTheo's Typesafe Cult
Created by rykuno on 5/7/2023 in #questions
Next-Auth Session in Server Function
Hey Guys, I found this thread through search and thought I'd chime in: There is currently no official fix for this but there is a workaround for the time being: Wrap your client component in a server component. Import the server function in a server component and pass it as a prop to the client component and call it there. That works but is more boilerplate than I would like. Like this:
// action.ts
'use server';
export async function serverFn(){...};

// ClientComponent.tsx
'use client'
import { serverFn } from './action'; // We use this only for the typing
type Props = {func: typeof serverFn};
export function ClientComponent({func}: Props){
const [count, setCount] = React.useState(0)
// Use function here however you like
return <button onClick={func}>Call Server Action {count}</button>
}

// Wrapper.tsx
import { serverFn } from './action';
import { ClientComponent } from './ClientComponent'
export default Wrapper(){
return <ClientComponent func={serverFn} />
}
// action.ts
'use server';
export async function serverFn(){...};

// ClientComponent.tsx
'use client'
import { serverFn } from './action'; // We use this only for the typing
type Props = {func: typeof serverFn};
export function ClientComponent({func}: Props){
const [count, setCount] = React.useState(0)
// Use function here however you like
return <button onClick={func}>Call Server Action {count}</button>
}

// Wrapper.tsx
import { serverFn } from './action';
import { ClientComponent } from './ClientComponent'
export default Wrapper(){
return <ClientComponent func={serverFn} />
}
Now using cookies or headers from next/headers works fine.
29 replies