SSG Helpers

createSSGHelpers providers you a set of helper functions that you can use to prefetch queries on the server.

  1. import { createSSGHelpers } from '@trpc/react/ssg';
  2. const {
  3. prefetchQuery,
  4. prefetchInfiniteQuery,
  5. fetchQuery,
  6. fetchInfiniteQuery,
  7. dehydrate,
  8. queryClient,
  9. } = await createSSGHelpers({
  10. router: appRouter,
  11. ctx: createContext,
  12. transformer: superjson, // optional - adds superjson serialization
  13. });

The returned functions are all wrappers around react-query functions. Please check out their docs to learn more about them.

Next.js Example

pages/posts/[id].tsx

  1. import { createSSGHelpers } from '@trpc/react/ssg';
  2. import { GetServerSidePropsContext, InferGetServerSidePropsType } from 'next';
  3. import { prisma } from 'server/context';
  4. import { appRouter } from 'server/routers/_app';
  5. import { trpc } from 'utils/trpc';
  6. import superjson from 'superjson';
  7. export async function getServerSideProps(
  8. context: GetServerSidePropsContext<{ id: string }>,
  9. ) {
  10. const ssg = await createSSGHelpers({
  11. router: appRouter,
  12. ctx: {},
  13. transformer: superjson,
  14. });
  15. const id = context.params?.id as string;
  16. // Prefetch `post.byId`
  17. await ssg.fetchQuery('post.byId', {
  18. id,
  19. });
  20. // Make sure to return { props: { trpcState: ssg.dehydrate() } }
  21. return {
  22. props: {
  23. trpcState: ssg.dehydrate(),
  24. id,
  25. },
  26. };
  27. }
  28. export default function PostViewPage(
  29. props: InferGetServerSidePropsType<typeof getServerSideProps>,
  30. ) {
  31. const { id } = props;
  32. // This query will be immediately available as it's prefetched.
  33. const postQuery = trpc.useQuery(['post.byId', { id }]);
  34. const { data } = postQuery;
  35. return (
  36. <>
  37. <h1>{data.title}</h1>
  38. <em>Created {data.createdAt.toLocaleDateString()}</em>
  39. <p>{data.text}</p>
  40. <h2>Raw data:</h2>
  41. <pre>{JSON.stringify(data, null, 4)}</pre>
  42. </>
  43. );
  44. }