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.

Configure _app.tsx for SSR

Server-side rendering comes with 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:

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