getInitialProps로 header정보 넘기기

2023. 10. 26. 13:15·React

next에서 getInitialProp는 권고하지 않고, getStaticProps, getServerSideProps를 사용하라고 권고

이번 프로젝트에서 페이지 앱인경우 공통으로 header값을 가져와야하는 케이스

모든페이지에 getServerSideProps를 사용할수없으니

_app.tsx에서 공통으로 처리하려고 함 

 

그래서 getInitialProps를 사용해서 처리

getInitialProps는 getServersideProps보다 먼저 실행됨 

둘다 서버에서 실행되는것으로 서버에서 header정보를 가져올 수있음 

 

최신 next에서는 서버컴포넌트에서는 아래처럼 사용함
https://nextjs.org/docs/app/api-reference/functions/headers

 

이번 프로젝트는 서버 컴포넌트를 사용하지 않아서 getinitialProps를 사용해서 처리했다.

import type { AppProps as NextAppProps, AppContext } from 'next/app';
import { NextPage } from 'next';
import { useEffect } from 'react';

type NextPageWithLayout = NextPage & {
  getLayout?: (page: React.ReactElement) => React.ReactNode;
  isAuthPage?: boolean;
};

type AppProps = {
  Component: NextPageWithLayout;
} & NextAppProps;

const App = ({ Component, pageProps }: AppProps) => {
  useEffect(() => {
    if (pageProps.deviceuuid) {
      authStore.setDeviceUuid(pageProps.deviceuuid);
    }
  }, [router.isReady]);
}

App.getInitialProps = async ({ Component, ctx }: AppContext) => {
  let pageProps = {};

  if (Component.getInitialProps) {
    pageProps = await Component.getInitialProps(ctx);
  }

  const header = ctx.req?.headers;
  const deviceUuid = header && header['device-uuid'] ? header['device-uuid'] : '';

  pageProps = { ...pageProps, deviceuuid: deviceUuid };

  return { pageProps };
};

'React' 카테고리의 다른 글

react-query resetQueries, removeQueries  (0) 2023.12.05
react tailwind setting, config  (0) 2023.10.29
React Query Promise.all, useQueries  (0) 2023.09.15
react 프로젝트에서 import순서 정렬  (0) 2023.09.08
react-hook-form validate with zod  (0) 2023.08.17
'React' 카테고리의 다른 글
  • react-query resetQueries, removeQueries
  • react tailwind setting, config
  • React Query Promise.all, useQueries
  • react 프로젝트에서 import순서 정렬
ssund
ssund
  • ssund
    ssund의 기술블로그
    ssund
  • 전체
    오늘
    어제
    • TECH (82)
      • Next.js (8)
      • React (25)
      • Vite (1)
      • javascript (17)
      • CSS (6)
      • CS (10)
      • AWS (0)
      • Jest (1)
      • CI|CD (0)
      • 알고리즘 (8)
      • Tools (1)
      • Tips (5)
  • 블로그 메뉴

    • 링크

    • 공지사항

    • 인기 글

    • 태그

      서버컴포넌트
      nextjs
      theme-provider
      git배포
      Array.sort()
      app-router
      react state management
      배열요소순서
      웹브라우저구성
      함수와 메서드차이
      call signatures
      TypeScript
      reat-head
      JavaScript
      styled-components
      커머스프로젝트
      타입스크립트
      React
      global-style
      redux
    • 최근 댓글

    • 최근 글

    • hELLO· Designed By정상우.v4.10.0
    ssund
    getInitialProps로 header정보 넘기기
    상단으로

    티스토리툴바