Skip to content

Instantly share code, notes, and snippets.

@mmikhan
Created April 27, 2025 11:01
Show Gist options
  • Save mmikhan/b60e50b018f4b8a6ced5705e2c812caf to your computer and use it in GitHub Desktop.
Save mmikhan/b60e50b018f4b8a6ced5705e2c812caf to your computer and use it in GitHub Desktop.
Manual dehydration through T3 `queryClient.fetchQuery` in a RSC
import { auth } from "@/server/auth";
import { createQueryClient } from "@/trpc/query-client";
import { HydrationBoundary, dehydrate } from "@tanstack/react-query"; // Import HydrationBoundary
import { headers } from "next/headers";
import Link from "next/link";
import { cache } from "react";
// Cache the QueryClient per request in RSC
const getQueryClient = cache(() => createQueryClient());
export default async function DashboardPage() {
const queryClient = getQueryClient();
const reqHeaders = await headers(); // Get headers for the API call
// Fetch data using fetchQuery on the server
// This fetches, caches, and returns the data for SSR
const state = await queryClient.fetchQuery({
queryKey: ["polarCustomerState"], // Use a consistent query key
queryFn: () => auth.api.polarCustomerState({ headers: reqHeaders }), // Use the auth helper within queryFn
});
// Dehydrate the query client state for hydration
const dehydratedState = dehydrate(queryClient);
return (
// Use HydrationBoundary instead of HydrateClient
<HydrationBoundary state={dehydratedState}>
<div className="relative flex min-h-[100dvh] flex-col items-center justify-center gap-4 bg-gradient-to-b from-[#2e026d] to-[#15162c] text-white">
<h1 className="font-bold text-4xl">Dashboard</h1>
{/* Link to the Polar Customer Portal */}
<Link
href="/api/auth/portal" // Directly targets the API endpoint
className="text-blue-400 underline hover:text-blue-300"
target="_blank" // Optional: open in a new tab
rel="noopener noreferrer" // Security measure for target="_blank"
>
Manage Subscription
</Link>
{/* Display the data fetched on the server */}
<pre className="mt-4 max-w-lg overflow-auto rounded bg-gray-800 p-4">
{JSON.stringify(state, null, 2)}
</pre>
<Link
href="/"
className="absolute top-4 left-4 text-gray-300 text-sm hover:text-gray-100"
>
Back to Home
</Link>
</div>
</HydrationBoundary>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment