• 카테고리

    질문 & 답변
  • 세부 분야

    풀스택

  • 해결 여부

    해결됨

질문드립니다 getServerSideProps or getInitialProps

21.11.04 20:54 작성 조회수 364

0

만약 모든 페이지에서 사용자 정보가 SSR되어야한다면
getServerSideProps보다 getInitalProps로 _app에다가 설정하는게 나을꺼 같은데
혹시 이 방법 말고 더 좋은 방법이 있을까 여쭤봅니다.
getInitalProps는 레거시 코드니까 사용하지 않는 게 좋다는데 이거 말고 대안을 못 찾겠네요.ㅠㅠ
 
1. _app -> getInitalProps
MyApp.getInitialProps = wrapper.getInitialAppProps(
  (store) =>
    async ({ Component, ctx }) => {
      store.dispatch(
        setCredentials({
          user: await axios
            .get("http://localhost:4000/users/me", {
              withCredentials: true,
              headers: {
                cookie: ctx.req?.headers.cookie || "",
              },
            })
            .then((response) => response.data)
            .catch(() => null),
        })
      );

      return {
        pageProps: {
          ...(Component.getInitialProps
            ? await Component.getInitialProps({ ...ctx, store })
            : {}),
          pathname: ctx.pathname,
        },
      };
    }
);
 
2. pages -> getServerSideProps
wrapper.getServerSideProps((store) => async (context) => {
    store.dispatch(
      setCredentials({
        user: await axios
          .get("http://localhost:4000/users/me", {
            withCredentials: true,
            headers: {
              cookie: context.req.headers.cookie || "",
            },
          })
          .then((response) => response.data)
          .catch(() => null),
      })
    );

    return {props: {}};
  });
 

답변 1

답변을 작성해보세요.

2

getInitialProps를 사용하는 게 중복이 없어지고 좋긴 한데 getServerSideProps만 쓰려면 모든 페이지에 다 넣는 수밖에 없습니다. next.js에서 페이지는 다 개별적으로 동작하는 것이라 그렇습니다.

묘단님의 프로필

묘단

질문자

2021.11.05

답글 감사합니다, 항상 ssr 인증부분에서 더 좋은방법이없을까하면서 구현했었는데 이것밖에없다고하니 뭐랄까 오히려 속이시원하네요! 

next-auth 라이브러리도 있는데 이것도 한 번 봐보세요.