Renderizado del lado del servidor
Esta página fue traducida por PageTurner AI (beta). No está respaldada oficialmente por el proyecto. ¿Encontraste un error? Reportar problema →
Lo único que necesitas hacer para implementar SSR en tu aplicación es establecer ssr: true en tu _app.tsx, pero esto conlleva algunas consideraciones adicionales.
Para ejecutar las consultas correctamente durante la fase de renderizado del lado del servidor y personalizar el comportamiento de caché, podríamos añadir lógica adicional dentro de nuestro _app.tsx:
pages/_app.tsxtsximport { withTRPC } from '@trpc/next';import { AppType } from 'next/dist/shared/lib/utils';import React from 'react';import superjson from 'superjson';import type { AppRouter } from './api/trpc/[trpc]';const MyApp: AppType = ({ Component, pageProps }) => {return <Component {...pageProps} />;};export default withTRPC<AppRouter>({config(config) {if (typeof window !== 'undefined') {// during client requestsreturn {transformer: superjson, // optional - adds superjson serializationurl: '/api/trpc',};}// during SSR below// optional: use SSG-caching for each rendered page (see caching section for more details)const ONE_DAY_SECONDS = 60 * 60 * 24;ctx?.res?.setHeader('Cache-Control',`s-maxage=1, stale-while-revalidate=${ONE_DAY_SECONDS}`,);// The server needs to know your app's full url// On render.com you can use `http://${process.env.RENDER_INTERNAL_HOSTNAME}:${process.env.PORT}/api/trpc`const url = process.env.VERCEL_URL? `https://${process.env.VERCEL_URL}/api/trpc`: 'http://localhost:3000/api/trpc';return {transformer: superjson, // optional - adds superjson serializationurl,/*** Set custom request headers on every request from tRPC* @see http://localhost:3000/docs/v9/header* @see http://localhost:3000/docs/v9/ssr*/headers() {if (ctx?.req) {// To use SSR properly, you need to forward the client's headers to the server// This is so you can pass through things like cookies when we're server-side rendering// If you're using Node 18, omit the "connection" headerconst {// eslint-disable-next-line @typescript-eslint/no-unused-varsconnection: _connection,...headers} = ctx.req.headers;return {...headers,// Optional: inform server that it's an SSR request'x-ssr': '1',};}return {};},};},ssr: true,})(MyApp);
pages/_app.tsxtsximport { withTRPC } from '@trpc/next';import { AppType } from 'next/dist/shared/lib/utils';import React from 'react';import superjson from 'superjson';import type { AppRouter } from './api/trpc/[trpc]';const MyApp: AppType = ({ Component, pageProps }) => {return <Component {...pageProps} />;};export default withTRPC<AppRouter>({config(config) {if (typeof window !== 'undefined') {// during client requestsreturn {transformer: superjson, // optional - adds superjson serializationurl: '/api/trpc',};}// during SSR below// optional: use SSG-caching for each rendered page (see caching section for more details)const ONE_DAY_SECONDS = 60 * 60 * 24;ctx?.res?.setHeader('Cache-Control',`s-maxage=1, stale-while-revalidate=${ONE_DAY_SECONDS}`,);// The server needs to know your app's full url// On render.com you can use `http://${process.env.RENDER_INTERNAL_HOSTNAME}:${process.env.PORT}/api/trpc`const url = process.env.VERCEL_URL? `https://${process.env.VERCEL_URL}/api/trpc`: 'http://localhost:3000/api/trpc';return {transformer: superjson, // optional - adds superjson serializationurl,/*** Set custom request headers on every request from tRPC* @see http://localhost:3000/docs/v9/header* @see http://localhost:3000/docs/v9/ssr*/headers() {if (ctx?.req) {// To use SSR properly, you need to forward the client's headers to the server// This is so you can pass through things like cookies when we're server-side rendering// If you're using Node 18, omit the "connection" headerconst {// eslint-disable-next-line @typescript-eslint/no-unused-varsconnection: _connection,...headers} = ctx.req.headers;return {...headers,// Optional: inform server that it's an SSR request'x-ssr': '1',};}return {};},};},ssr: true,})(MyApp);
Preguntas frecuentes
P: ¿Por qué debo reenviar manualmente los headers del cliente al servidor? ¿Por qué tRPC no lo hace automáticamente?
Aunque es raro que no quieras reenviar los headers del cliente al servidor al usar SSR, podrías necesitar agregar elementos dinámicamente en los headers. Por lo tanto, tRPC no quiere asumir la responsabilidad por posibles colisiones de claves en headers, etc.
P: ¿Por qué necesito eliminar el header connection al usar SSR en Node 18?
Si no eliminas el header connection, la obtención de datos fallará con TRPCClientError: fetch failed porque connection es un nombre de header prohibido.
P: ¿Puedo usar getServerSideProps y/o getStaticProps mientras utilizo SSR?
Cuando habilitas SSR, tRPC usará getInitialProps para precargar todas las consultas en el servidor. Esto causa problemas como este cuando usas getServerSideProps en una página, y solucionarlo escapa de nuestro control. Sin embargo, puedes usar SSG Helpers para precargar consultas en getStaticProps o getServerSideProps.