I wanted to know if this method is optimal or not. Because I did not find any documentation about it.
example
a server action to get the current user information
actions/whoami.ts
"use server";
import { auth, prisma } from "@/lib/auth"; // next-auth config file
export default async function whoami(): Promis<User | null> {
const session = await auth();
if (!session?.user || !session.user.email) {
return null;
}
const user = await prisma.user.findUnique({
where: {
email: session.user.email,
},
});
return user;
}
use in client components:
export default function ClientPage() {
const { data: user } = useSWR("whoami", whoami);
console.log({ user }); // user is fully typed
return "...";
}
use in server components:
export default async function ServerPage() {
const user = await whoami();
console.log({ user }); // user is fully typed
return "...";
}
The is a very good method, why this is not documented in nextjs or swr docs ? (I did not found it)
2
Answers
I have the same issue, and I use this approach in most parts of the project.
Do you have any new insights now?
While using server actions directly as SWR fetchers in Next.js isn’t the most common approach, there are valid use cases and alternative strategies to consider:
Reasons Why SWR Might Not Be Ideal for Server Actions:
Code Duplication: Using server actions within SWR fetchers can lead to redundant code, as you’d essentially be fetching data twice (once in the server action and again in the SWR fetcher).
Unnecessary Client-Side Fetching: If the data doesn’t need to be dynamically updated on the client, fetching it on the server side during the initial render (SSR) or static site generation (SSG) can be more efficient.
This is how you can fetch data :
User data:
CTX:
Actions:
Main competent:
TableWrapper
Action:
This is how you post data to server :
Action:
NOTE: keep in mind that I haven’t any specific auth check in the server action because for this I’m totally relying on Nest js backend for your case you must check for auth first in server action