번역 자료 / / 2025. 5. 28. 06:45

[react 번역] renderToPipeableStream API

원문: https://react.dev/reference/react-dom/server/renderToPipeableStream


renderToPipeableStream

renderToPipeableStream은 React 트리를 pipeable Node.js Stream으로 렌더링합니다.

const { pipe, abort } = renderToPipeableStream(reactNode, options?)
  • 레퍼런스
    • renderToPipeableStream(reactNode, options?)
  • 사용법
    • React 트리를 Node.js Stream으로 HTML 렌더링하기
    • 로딩되는 대로 추가 콘텐츠 스트리밍하기
    • shell에 포함할 내용 지정하기
    • 서버에서 크래시 로깅하기
    • shell 내부/외부 에러 복구하기
    • 상태 코드 설정하기
    • 다양한 에러를 다르게 처리하기
    • 크롤러/정적 생성 시 모든 콘텐츠가 로드될 때까지 대기하기
    • 서버 렌더링 중단하기

이 API는 Node.js 전용입니다. Web Streams 환경(Deno, Edge 등)에서는 renderToReadableStream을 사용하세요.


레퍼런스

renderToPipeableStream(reactNode, options?)

React 트리를 HTML로 Node.js Stream에 렌더링하려면 renderToPipeableStream을 호출하세요.

import { renderToPipeableStream } from 'react-dom/server';

const { pipe } = renderToPipeableStream(<App />, {
  bootstrapScripts: ['/main.js'],
  onShellReady() {
    response.setHeader('content-type', 'text/html');
    pipe(response);
  }
});

클라이언트에서는 hydrateRoot를 호출해 서버에서 생성된 HTML을 인터랙티브하게 만듭니다.

파라미터

  • reactNode: HTML로 렌더링할 React 노드(JSX 등). 전체 문서를 나타내야 하므로, App 컴포넌트는 <html> 태그를 렌더링해야 합니다.
  • options(선택): 스트리밍 옵션 객체
    • bootstrapScriptContent: 인라인 <script> 태그에 들어갈 문자열
    • bootstrapScripts: <script> 태그로 삽입할 스크립트 URL 배열. hydrateRoot를 호출하는 스크립트를 포함해야 함
    • bootstrapModules: <script type="module">로 삽입할 모듈 스크립트 URL 배열
    • identifierPrefix: useId로 생성되는 ID의 접두사(서버/클라이언트 동일해야 함)
    • namespaceURI: 루트 네임스페이스 URI. 기본값은 HTML, SVG/MathML 등은 별도 지정
    • nonce: CSP를 위한 스크립트 허용 난수값
    • onAllReady: shell과 모든 추가 콘텐츠 렌더링이 끝났을 때 호출되는 콜백(크롤러/정적 생성용)
    • onError: 서버 에러 발생 시 호출되는 콜백(기본값: console.error)
    • onShellReady: shell 렌더링 직후 호출되는 콜백. 이때 pipe를 호출해 스트리밍 시작
    • onShellError: shell 렌더링에 실패했을 때 호출되는 콜백. fallback HTML을 출력할 수 있음
    • progressiveChunkSize: 청크 크기(기본값: 내부 휴리스틱)

반환값

  • pipe: Writable Node.js Stream에 HTML을 출력하는 함수. onShellReady/onAllReady에서 호출
  • abort: 서버 렌더링을 중단하고 나머지는 클라이언트에서 렌더링하도록 함

사용법

React 트리를 Node.js Stream으로 HTML 렌더링하기

import { renderToPipeableStream } from 'react-dom/server';

app.use('/', (request, response) => {
  const { pipe } = renderToPipeableStream(<App />, {
    bootstrapScripts: ['/main.js'],
    onShellReady() {
      response.setHeader('content-type', 'text/html');
      pipe(response);
    }
  });
});

App 컴포넌트는 전체 문서(<html> 태그 포함)를 반환해야 하며, bootstrap 스크립트 경로도 지정해야 합니다.

shell에 포함할 내용 지정하기

export default function App() {
  return (
    <html>
      <head>
        <meta charSet="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <link rel="stylesheet" href="/styles.css"></link>
        <title>My app</title>
      </head>
      <body>
        <Router />
      </body>
    </html>
  );
}

React는 doctype과 bootstrap <script> 태그를 HTML 스트림에 자동으로 삽입합니다.


에러 처리 및 고급 사용법

  • shell 내부/외부에서 발생하는 에러에 따라 onShellError, onError, Suspense fallback 등으로 복구할 수 있습니다.
  • 상태 코드 설정, 크롤러/정적 생성 시 onAllReady 사용, 서버 렌더링 중단(abort) 등 다양한 고급 옵션을 지원합니다.

출처: https://react.dev/reference/react-dom/server/renderToPipeableStream

반응형
  • 네이버 블로그 공유
  • 네이버 밴드 공유
  • 페이스북 공유
  • 카카오스토리 공유