Static Site Generation

tip

Reference project: https://github.com/trpc/examples-next-prisma-todomvc

Static site generation requires executing tRPC queries inside getStaticProps on each page.

Fetch data in getStaticProps

pages/posts/[id].tsx

  1. import { createSSGHelpers } from '@trpc/react/ssg';
  2. import {
  3. GetStaticPaths,
  4. GetStaticPropsContext,
  5. InferGetStaticPropsType,
  6. } from 'next';
  7. import { prisma } from 'server/context';
  8. import { appRouter } from 'server/routers/_app';
  9. import superjson from 'superjson';
  10. import { trpc } from 'utils/trpc';
  11. export async function getStaticProps(
  12. context: GetStaticPropsContext<{ id: string }>,
  13. ) {
  14. const ssg = await createSSGHelpers({
  15. router: appRouter,
  16. ctx: {},
  17. transformer: superjson, // optional - adds superjson serialization
  18. });
  19. const id = context.params?.id as string;
  20. // prefetch `post.byId`
  21. await ssg.fetchQuery('post.byId', {
  22. id,
  23. });
  24. return {
  25. props: {
  26. trpcState: ssg.dehydrate(),
  27. id,
  28. },
  29. revalidate: 1,
  30. };
  31. }
  32. export const getStaticPaths: GetStaticPaths = async () => {
  33. const posts = await prisma.post.findMany({
  34. select: {
  35. id: true,
  36. },
  37. });
  38. return {
  39. paths: posts.map((post) => ({
  40. params: {
  41. id: post.id,
  42. },
  43. })),
  44. // https://nextjs.org/docs/basic-features/data-fetching#fallback-blocking
  45. fallback: 'blocking',
  46. };
  47. };
  48. export default function PostViewPage(
  49. props: InferGetStaticPropsType<typeof getStaticProps>,
  50. ) {
  51. const { id } = props;
  52. const postQuery = trpc.useQuery(['post.byId', { id }]);
  53. if (postQuery.status !== 'success') {
  54. // won't happen since we're using `fallback: "blocking"`
  55. return <>Loading...</>;
  56. }
  57. const { data } = postQuery;
  58. return (
  59. <>
  60. <h1>{data.title}</h1>
  61. <em>Created {data.createdAt.toLocaleDateString('en-us')}</em>
  62. <p>{data.text}</p>
  63. <h2>Raw data:</h2>
  64. <pre>{JSON.stringify(data, null, 4)}</pre>
  65. </>
  66. );
  67. }

Check out here to learn more about createSSGHelpers.