You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I'm working on a Next.js (v15, AppRouter) project with @tanstack/react-query (v5) and trying to optimize data fetching using server-side rendering. Specifically, I'm prefetching data in a Server Component with prefetchQuery and passing it to the client using HydrationBoundary.
Q. I have a question about whether it's appropriate to use a Next.js Server Action as the queryFn for this process.
Background
In Next.js, Server Actions are primarily designed for handling mutations (e.g., form submissions) and are executed as POST requests. However, I want to use a Server Action to fetch data (similar to a GET request) because it allows me to encapsulate server-side logic, such as authentication or data processing, securely. My concern is whether this approach aligns with best practices, considering the HTTP semantics of GET requests, caching behavior, and React Query's integration with Next.js.
Code Example
"use server";
export async function fetchPosts() {
// * Get data from a database
}
export default async function Page() {
const queryClient = new QueryClient();
await queryClient.prefetchQuery({
queryKey: ["posts"],
queryFn: fetchPosts, // Using Server Action
});
const dehydratedState = dehydrate(queryClient);
return (
<HydrationBoundary state={dehydratedState}>
<Home />
</HydrationBoundary>
);
}
"use client"
export default function Home() {
const { data, isLoading, isError, error } = useQuery({
queryKey: ["posts"],
queryFn: fetchPosts, // Same Server Action
});
...
}
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
I'm working on a Next.js (v15, AppRouter) project with @tanstack/react-query (v5) and trying to optimize data fetching using server-side rendering. Specifically, I'm prefetching data in a Server Component with prefetchQuery and passing it to the client using HydrationBoundary.
Q. I have a question about whether it's appropriate to use a Next.js Server Action as the queryFn for this process.
Background
In Next.js, Server Actions are primarily designed for handling mutations (e.g., form submissions) and are executed as POST requests. However, I want to use a Server Action to fetch data (similar to a GET request) because it allows me to encapsulate server-side logic, such as authentication or data processing, securely. My concern is whether this approach aligns with best practices, considering the HTTP semantics of GET requests, caching behavior, and React Query's integration with Next.js.
Code Example
Beta Was this translation helpful? Give feedback.
All reactions