Server-Side Rendering

The only thing you need to do to get SSR on your application is to set ssr: true in your _app.tsx, but it comes with some additional considerations.

In order to execute queries properly during the server-side render step and customize caching behavior, we might want to add some extra logic inside our _app.tsx:

pages/_app.tsx

  1. import React from 'react';
  2. import { withTRPC } from '@trpc/next';
  3. import { AppType } from 'next/dist/shared/lib/utils';
  4. import superjson from 'superjson';
  5. import type { AppRouter } from './api/trpc/[trpc]';
  6. const MyApp: AppType = ({ Component, pageProps }) => {
  7. return <Component {...pageProps} />;
  8. };
  9. export default withTRPC<AppRouter>({
  10. config({ ctx }) {
  11. if (typeof window !== 'undefined') {
  12. // during client requests
  13. return {
  14. transformer: superjson, // optional - adds superjson serialization
  15. url: '/api/trpc',
  16. };
  17. }
  18. // during SSR below
  19. // optional: use SSG-caching for each rendered page (see caching section for more details)
  20. const ONE_DAY_SECONDS = 60 * 60 * 24;
  21. ctx?.res?.setHeader(
  22. 'Cache-Control',
  23. `s-maxage=1, stale-while-revalidate=${ONE_DAY_SECONDS}`,
  24. );
  25. // The server needs to know your app's full url
  26. // On render.com you can use `http://${process.env.RENDER_INTERNAL_HOSTNAME}:${process.env.PORT}/api/trpc`
  27. const url = process.env.VERCEL_URL
  28. ? `https://${process.env.VERCEL_URL}/api/trpc`
  29. : 'http://localhost:3000/api/trpc';
  30. return {
  31. transformer: superjson, // optional - adds superjson serialization
  32. url,
  33. headers: {
  34. // optional - inform server that it's an ssr request
  35. 'x-ssr': '1',
  36. },
  37. };
  38. },
  39. ssr: true,
  40. })(MyApp);

Caveats

When you enable SSR, tRPC will use getInitialProps to prefetch all queries on the server. That causes problems like this when you use getServerSideProps in a page and solving it is out of our hands. Though, you can use SSG Helpers to prefetch queries in getStaticSiteProps or getServerSideProps.