<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sangmin Tsx on Medium]]></title>
        <description><![CDATA[Stories by Sangmin Tsx on Medium]]></description>
        <link>https://medium.com/@sangmin.tsx?source=rss-2ace129286a9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*EqU2VV1Wz5PYbtqY</url>
            <title>Stories by Sangmin Tsx on Medium</title>
            <link>https://medium.com/@sangmin.tsx?source=rss-2ace129286a9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 03:26:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sangmin.tsx/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Next.js에서 SuspenseQuery와 서버 액션을 함께 사용할 때의 문제와 해결 과정]]></title>
            <link>https://medium.com/wraffle-tech/%EC%9D%B4%EC%A0%84-%ED%8F%AC%EC%8A%A4%ED%8A%B8%EC%97%90%EC%84%9C-%EC%95%8C%EB%A6%BC-%EB%AA%A9%EB%A1%9D-%ED%8E%98%EC%9D%B4%EC%A7%80-%EA%B5%AC%ED%98%84-%EA%B3%BC%EC%A0%95%EC%97%90%EC%84%9C-%EB%B0%9C%EC%83%9D%ED%95%9C-suspense-query%EC%99%80-%EC%84%9C%EB%B2%84-%EC%95%A1%EC%85%98-%EB%AC%B8%EC%A0%9C%EA%B0%80-%EC%B9%B4%EB%93%9C-%EB%AA%A9%EB%A1%9D-%ED%8E%98%EC%9D%B4%EC%A7%80%EC%97%90%EC%84%9C%EB%8F%84-%EB%8F%99%EC%9D%BC%ED%95%98%EA%B2%8C-%EB%B0%9C%EC%83%9D%ED%96%88%EB%8B%A4-d9089227fba7?source=rss-2ace129286a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9089227fba7</guid>
            <category><![CDATA[suspense]]></category>
            <category><![CDATA[react-query]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[streaming]]></category>
            <category><![CDATA[tanstack-query]]></category>
            <dc:creator><![CDATA[Sangmin Tsx]]></dc:creator>
            <pubDate>Sun, 02 Mar 2025 16:44:23 GMT</pubDate>
            <atom:updated>2025-03-03T14:18:34.421Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://medium.com/wraffle-tech/server-component%EC%97%90%EC%84%9C-suspense-query%EB%A5%BC-%EC%82%AC%EC%9A%A9%ED%95%98%EC%97%AC-next-js-streaming-%EC%84%9C%EB%B2%84-%EB%A0%8C%EB%8D%94%EB%A7%81-%EC%A0%81%EC%9A%A9%ED%95%98%EA%B8%B0-3a5bfd1efb55">Server Component에서 Suspense Query를 사용하여 Next.js Streaming 서버 렌더링 적용하기</a></p><p>이전 포스트에서 <strong>알림 목록 페이지</strong> 구현 과정에서 발생한 <strong>Suspense Query와 서버 액션을 함께 사용했을 때 발생했던 문제</strong>가 <strong>카드 목록 페이지</strong>에서도 동일하게 발생했다.</p><p>해결 방안을 찾아 적용했지만, 구체적인 원인은 명확히 파악하지 못했었다. 이번에는 <strong>Suspense Query와 서버 액션을 함께 사용할 때 발생하는 에러의 원인을 정확히 분석</strong>하고, 최적의 해결 방법을 찾고자 한다.</p><h3>문제 상황</h3><p>이전에 내린 결론은 <strong>클라이언트 컴포넌트에서 </strong><strong>useSuspenseQuery를 사용하여 서버 액션을 호출할 때 에러가 발생한다</strong>는 것이었다.</p><p>서비스 내부적으로 구현한 Fetch Client에서 서버 액션을 통해 session 정보를 가져오고 있는데, 이 서버 액션 함수를 useSuspenseQuery의 queryFn에서 사용하고, 상위 서버 컴포넌트에서 Suspense Boundary로 감쌌을 때 에러가 발생했다.</p><blockquote>🚨 <strong>Unhandled Runtime Error</strong></blockquote><blockquote>Error: Server Functions cannot be called during initial render. This would create a fetch waterfall. Try to use a Server Component to pass data to Client Components instead.</blockquote><p>초기 렌더링 시 서버 액션 함수가 호출되면 Fetch Waterfall이 일어날 수 있기 때문에 Next.js에서 정책상으로 제한하였다고 한다.</p><h3>에러 원인</h3><p>결국 <strong>서버 액션을 </strong><strong>useSuspenseQuery+ </strong><strong>Suspense Boundary와 함께 사용</strong>하면서 발생하는 문제이다.</p><p><a href="https://github.com/TanStack/query/issues/6591?source=post_page-----3a5bfd1efb55---------------------------------------">Nextjs Streaming+Server Action Error: Server Functions cannot be called during initial render. · Issue #6591 · TanStack/query</a></p><p>Tanstack Query Github에서 관련된 Issue를 찾아볼 수 있다.</p><p>useSuspenseQuery가 호출되면 Promise를 throw하고, 이때 Suspense Boundary가 트리거된다.</p><p>데이터가 준비되지 않은 상태라면 컴포넌트가 <strong>suspend</strong>되며, Suspense는 <strong>컴포넌트 렌더링 이전에 데이터를 기다리도록 강제</strong>하여 fallback UI를 표시한다.</p><pre>&lt;Suspense fallback={&lt;Loading /&gt;}&gt;<br>  &lt;Component /&gt; // useSuspenseQuery 실행 (서버 액션)<br>&lt;/Suspense&gt;</pre><p>현재 구조는 Suspense 내부의 컴포넌트에서 useSuspenseQuery를 호출하고, queryFn에서 서버 액션을 호출하고 있다.<br> useSuspenseQuery 에서 초기 데이터가 없다면 데이터 페칭을 위해 Promise를 throw하여 Suspense Boundary가 Component를 suspend상태로 만들고 fallback UI를 표시한다.<br>Component가 suspend상태가 되어 초기 렌더링이 진행되는 동안 queryFn(서버액션)이 실행되고 있다.</p><p>즉, <strong>초기 렌더링 과정에서</strong> <strong>queryFn이 실행되면서 서버 액션이 호출되고, 이로 인해 Next.js에서 에러를 발생시키는 것</strong>으로 보인다.</p><h3>해결 방안 모색</h3><h3>🙅‍♂️) 1. 서버 액션 사용하지 않기</h3><p>가장 단순한 해결책은 <strong>서버 액션을 사용하지 않는 것</strong>이다.</p><p>서버 액션을 사용하는 apiClient대신 기본 fetch를 사용하면 에러가 발생하지 않는다.</p><pre>const response = await fetch(<br>  &#39;URL&#39;,<br>  {<br>    method: &#39;GET&#39;,<br>    headers: {<br>      &#39;Content-Type&#39;: &#39;application/json&#39;,<br>      Authorization: `Bearer ${TOKEN}`,<br>    },<br>  },<br>);<br><br>return response.json().then(data =&gt; data.data);</pre><p>하지만 <strong>인증이 필요한 API</strong>의 경우, header에 토큰 정보를 포함해야 하고, 이를 위해 Auth.js의 getSession()을 호출해야 한다. 그런데 getSession()이 서버 액션으로 정의되어 있다.</p><p>또한, 기본 fetch는 응답과 반환 데이터에 대한 <strong>타입 매핑이 불가능</strong>하므로, 이 방법은 최후의 수단으로 두고 다른 해결책을 찾아보았다.</p><h3>🙅‍♂️) 2. Suspense 사용하지 않기</h3><p>상위 컴포넌트에서 Suspense Boundary를 사용하지 않으면 에러가 발생하지 않는다.</p><p>이유를 살펴보기 전에 useQuery와 useSuspenseQuery의 동작 방식 차이를 먼저 알아보자.</p><h4><strong>useQuery vs </strong><strong>useSuspenseQuery</strong></h4><p><strong>1. </strong><strong>useQuery</strong></p><ul><li>명령형으로 데이터를 가져오며, 로딩 및 에러 상태를 명시적으로 처리할 수 있다.</li><li>isFetching과 같은 상태를 활용해 로딩 여부를 확인할 수 있다.</li><li>데이터가 준비되지 않아도 loading 상태를 표시하며, <strong>서버 액션 호출과 관련된 문제가 발생하지 않는다.</strong></li><li>클라이언트에서 데이터 페칭이 이루어지며, 서버 액션이 호출되더라도 이는 클라이언트에서의 비동기 요청으로 처리된다.</li></ul><p><strong>2. </strong><strong>useSuspenseQuery</strong></p><ul><li>React의 Suspense를 활용하여 데이터를 가져온다.</li><li>데이터가 준비되지 않으면 Promise를 던져 Suspense를 트리거한다.</li><li>이 과정에서 Suspense는 컴포넌트를 suspend 시키고, 가장 가까운 Suspense 컴포넌트의 fallback을 표시한다.</li><li>이 과정에서 <strong>서버 액션이 실행되면, Next.js에서 제한하는 에러가 발생할 수 있다.</strong></li></ul><p><strong>왜 </strong><strong>useQuery에서는 에러가 발생하지 않는가?</strong></p><ul><li><strong>명령형 vs 선언형<br>- </strong><strong>useQuery</strong>는 명령형으로 로딩 상태를 관리하므로, 데이터가 준비되지 않았을 때도 컴포넌트는 로딩 상태를 표시하며, 서버 액션 호출과 관련된 문제가 발생하지 않는다.<br>- <strong>useSuspenseQuery</strong>는 선언형으로 데이터를 가져오며, 데이터가 준비되지 않으면 컴포넌트를 suspend 시킨다. 이 과정에서 서버 액션 호출이 문제가 될 수 있다.</li><li><strong>클라이언트에서의 비동기 처리<br>- </strong>useQuery는 클라이언트에서 비동기적으로 데이터를 가져오며, 서버 액션이 호출되더라도 이는 클라이언트에서의 비동기 요청으로 처리된다.<br>- useSuspenseQuery는 Suspense를 통해 데이터를 가져오면서, 클라이언트에서 서버 액션을 호출하려고 시도할 수 있으며, 이는 Next.js의 초기 렌더링 중에 허용되지 않는다.</li></ul><p>하지만 로딩과 에러 처리를 명시적으로 처리하기 보다 선언적으로 관리하고 싶었고, <strong>Next.js의 </strong><strong>Streaming SSR 기능을 활용하려면</strong> Suspense Boundary<strong>가 필요</strong>하기 때문에, Suspense를 제거하는 것은 좋은 해결책이 아니었다.</p><h3>🙅‍♂️) 3. useSuspenseQuery에 InitialData 넣어주기</h3><p>initialData를 설정하면 useSuspenseQuery가 실행될 때 기존 데이터를 먼저 반환하고, 이후에 서버 액션을 호출하게 된다.</p><pre>export const useGETCardListQuery = () =&gt; {<br>  return useSuspenseQuery({<br>    ...getCardListQueryOptions(),<br>    select: data =&gt; data.items,<br>    initialData: {items: []},<br>    staleTime: 0,<br>  });<br>};</pre><p>useSuspenseQuery에서 initialData가 있다면, suspenseQuery는 Promise를 throw하지 않는다.</p><p>즉, Component를 suspend 상태로 만들지 않아 fallback UI를 표시하지 않는다.</p><p><a href="https://github.com/TanStack/query/discussions/6143">should useSuspenseQuery support initialData · TanStack query · Discussion #6143</a></p><p>초기 렌더링은 initialData를 사용하여 진행하기 때문에 queryFn(서버액션)은 실행되지 않는다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*cqFcMsNTIha24EfFT63v1A.gif" /></figure><p>초기 데이터가 비어있기 때문에 staleTime을 0으로 지정해주어 즉시 캐시를 새로 불러 데이터를 업데이트해 화면을 렌더링한다.</p><p>이렇게 하면 해결은 됐지만 페이지에 초기 접근 시 데이터가 fetching되는 동안 initialData인 빈 데이터를 보여주기 때문에 Suspense를 통한 fallback UI를 보여주는 이점이 없어진다.</p><h3>✅) 4. 서버 컴포넌트에서 Prefetch를 통해 초기 데이터 넘겨주기 (with Hydration Boundary)</h3><p>사실 초기 데이터를 꼭 initialData에 선언할 필요는 없다.</p><p>만약 페칭할 데이터를 사전에 받아놓고 캐싱해둔다면 useSuspenseQuery가 호출될 때 initialData는 캐시된 데이터를 사용할 것이고 추가적인 네트워크 요청을 하지 않게 된다.</p><p>queryFn에서 서버 액션을 호출하고 있고, Next.js에서 서버 액션은 초기 렌더링 시 호출이 되면 에러를 던져주고 있다.</p><p>이를 위해서 서버 컴포넌트에서 서버 액션을 호출해야 하고, Suspense Boundary를 사용하는 상위 서버 컴포넌트에서 useSuspenseQuery에서 사용할 데이터를 prefetch하여 넘겨준다면, 이 문제를 해결할 수 있다.</p><p><a href="https://tanstack.com/query/latest/docs/framework/react/guides/advanced-ssr">Advanced Server Rendering | TanStack Query React Docs</a></p><p>Tanstack Query 공식 문서에서도 Advanced Server Rendering 이라는 이름으로 소개하고 있는 내용이다.</p><p>서버 컴포넌트에서 query client를 통해 데이터를 prefetch하고, Hydration Boundary를 사용하여 query client를 직렬화(dehydrate)하여 서버 → 클라이언트로 query client 객체를 내려준다.</p><p>클라이언트 컴포넌트에서 useSuspenseQuery를 호출할 때 이미 prefetch를 통해 데이터가 캐싱되어 있으므로 추가적인 네트워크 요청을 하지 않고 (서버 액션 함수를 호출하지 않음) 렌더링할 수 있다.</p><pre>&lt;Suspense fallback={&lt;Loading /&gt;}&gt;<br> &lt;PrefetchBoundary ...&gt; // prefetchQuery 실행<br>   &lt;Component /&gt; // useSuspenseQuery 실행 (서버 액션)<br> &lt;/PrefetchBoundary&gt;<br>&lt;/Suspense&gt;</pre><p>위 구조로 다시 이해해보자.</p><p>useSuspenseQuery가 실행되기 전에 (Component가 렌더링 과정을 시작하기 전에) prefetchQuery가 실행된다. PrefetchBoundary의 prefetchQuery에서 useSuspenseQuery에서 호출할 queryFn을 호출하여 실행 결과를 query client 객체가 가지고 있다.</p><p>query client 객체를 Hydration Boundary를 통해 Component로 전달하고, Component에서 useSuspenseQuery를 호출한다.</p><p>이 과정에서<strong> query client에 이미 호출된 (또는 호출 중인) 캐시가 있기 때문에 queryFn(서버 액션)이 실행되지 않는다.</strong></p><p>데이터를 호출 중이라면 Suspense의 fallback UI를 표시한다.</p><p>따라서,<strong> 클라이언트에서 초기 렌더링이 진행되기 전에 서버 액션을 실행했기 때문에 에러가 발생하지 않는 것</strong>이다.</p><pre>const CardPage = async () =&gt; {<br>  return (<br>    &lt;&gt;<br>     ...<br>        &lt;Suspense fallback={&lt;SkeletonCardList /&gt;}&gt;<br>          &lt;PrefetchCardList&gt;<br>            &lt;CardList /&gt;<br>          &lt;/PrefetchCardList&gt;<br>        &lt;/Suspense&gt;<br>    &lt;/&gt;<br>  );<br>};<br><br>export default CardPage;</pre><pre>import {GET_CARD_LIST_KEY, getCardListAPI} from &#39;@/features/card/api&#39;;<br>import {dehydrate, HydrationBoundary, QueryClient} from &#39;@tanstack/react-query&#39;;<br><br>const PrefetchCardList = async ({children}: {children: React.ReactNode}) =&gt; {<br>  const queryClient = new QueryClient();<br><br>  await queryClient.prefetchQuery({<br>    queryKey: GET_CARD_LIST_KEY(),<br>    queryFn: () =&gt; getCardListAPI(),<br>  });<br>  return (<br>    &lt;HydrationBoundary state={dehydrate(queryClient)}&gt;<br>      {children}<br>    &lt;/HydrationBoundary&gt;<br>  );<br>};<br><br>export default PrefetchCardList;</pre><p>Suspense가 prefetch의 Promise를 catch할 수 있게 Suspense Boundary 내부에 prefetch 로직을 넣어준다.</p><p>서버 컴포넌트인 PrefetchCardList에서 useSuspenseQuery에서 호출할 데이터를 사전에 받아 캐싱해두고, 캐싱되어 있는 query client 객체를 Hydration Boundary를 통해 자식 컴포넌트인 CardList로 전달한다.</p><p>CardList에서는 useSuspenseQuery가 호출되지만, 캐싱 되어 있는(혹은 pending 중인) 데이터가 있기 때문에 추가적인 네트워크 요청을 하지 않는다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*KbHpRFwrekQtjRfiTcqG4w.gif" /></figure><p>Suspense Boundary로 감쌌기 때문에 Next.js에서 Streaming SSR을 통해 로딩중인 카드 목록은 fallback UI로 대체하여 빠르게 화면을 렌더링하고 있다.</p><h4>PrefetchBoundary 컴포넌트 추상화</h4><p>prefetchQuery를 호출하기 위해 PrefetchCardList가 생성되었는데, 이로 인해서 CardList 컴포넌트가 한 레이어 더 깜싸지며 page.tsx 내의 컴포넌트 추상화 레벨이 일관되지 않는다는 문제점이 발생했다.</p><p>그리고 서비스 내에서 이러한 패턴으로 렌더링 페이지가 여러개 있는 경우 매번 Prefetch를 위한 별도의 컴포넌트를 생성하는 것이 불편하게 느껴졌다.</p><p><strong>이를 해결하기 위해 </strong><strong>prefetchQuery를 호출해주는 추상화된 컴포넌트를 하나 생성한다.</strong></p><pre>// shared/context/query/PrefetchBoundary.tsx<br><br>import {<br>  type PrefetchOptions,<br>  type PrefetchInfiniteOptions,<br>  isPrefetchOptions,<br>  isPrefetchInfiniteOptions,<br>} from &#39;./type&#39;;<br>import {HydrationBoundary, QueryClient, dehydrate} from &#39;@tanstack/react-query&#39;;<br><br>type Props = {<br>  prefetchOptions:<br>    | PrefetchOptions[]<br>    | PrefetchInfiniteOptions[]<br>    | PrefetchOptions<br>    | PrefetchInfiniteOptions;<br>  children: React.ReactNode;<br>};<br><br>export async function PrefetchBoundary({prefetchOptions, children}: Props) {<br>  const queryClient = new QueryClient();<br><br>  if (Array.isArray(prefetchOptions)) {<br>    await Promise.all(<br>      prefetchOptions.map(option =&gt; {<br>        if (isPrefetchOptions(option)) {<br>          return queryClient.prefetchQuery(option);<br>        }<br>        if (isPrefetchInfiniteOptions(option)) {<br>          return queryClient.prefetchInfiniteQuery(option);<br>        }<br>      }),<br>    );<br>  } else {<br>    if (isPrefetchOptions(prefetchOptions)) {<br>      await queryClient.prefetchQuery(prefetchOptions);<br>    }<br>    if (isPrefetchInfiniteOptions(prefetchOptions)) {<br>      await queryClient.prefetchInfiniteQuery(prefetchOptions);<br>    }<br>  }<br><br>  return (<br>    &lt;HydrationBoundary state={dehydrate(queryClient)}&gt;<br>      {children}<br>    &lt;/HydrationBoundary&gt;<br>  );<br>}</pre><p>query client를 생성하여 prefetchQuery 또는 prefetchInifniteQuery를 호출해주며, HydrationBoundary를 감싸주는 추상체인 PrefetchBoundary를 생성했다.</p><p>prop으로 prefetch를 위한 쿼리 옵션인 prefetchOptions 또는 prefetchInfiniteOptions 를 받으며, 여러 개의 쿼리를 prefetch 해야하는 경우에는 배열로 받고 Promise.all() 메소드를 활용하여 병렬적으로 prefetch를 진행하도록 구현했다.</p><p>참고로 prefetch를 위한 query 타입과 타입가드를 정의한 파일은 아래와 같다.</p><pre>// shared/context/query/type.ts<br><br>import type {<br>  FetchInfiniteQueryOptions,<br>  FetchQueryOptions,<br>  UseInfiniteQueryOptions,<br>  UseQueryOptions,<br>  UseSuspenseInfiniteQueryOptions,<br>  UseSuspenseQueryOptions,<br>} from &#39;@tanstack/react-query&#39;;<br><br>export type PrefetchOptions = Pick&lt;FetchQueryOptions, &#39;queryKey&#39; | &#39;queryFn&#39;&gt;;<br>export type PrefetchInfiniteOptions = Pick&lt;<br>  FetchInfiniteQueryOptions,<br>  &#39;queryKey&#39; | &#39;queryFn&#39; | &#39;initialPageParam&#39;<br>&gt;;<br><br>export const isPrefetchOptions = (<br>  option: PrefetchOptions | PrefetchInfiniteOptions,<br>): option is FetchQueryOptions =&gt; {<br>  return (<br>    &#39;queryKey&#39; in option &amp;&amp;<br>    &#39;queryFn&#39; in option &amp;&amp;<br>    !(&#39;initialPageParam&#39; in option)<br>  );<br>};<br><br>export const isPrefetchInfiniteOptions = (<br>  option: PrefetchOptions | PrefetchInfiniteOptions,<br>): option is FetchInfiniteQueryOptions =&gt; {<br>  return (<br>    &#39;queryKey&#39; in option &amp;&amp; &#39;queryFn&#39; in option &amp;&amp; &#39;initialPageParam&#39; in option<br>  );<br>};<br><br>export type BasicSuspenseQueryOptions&lt;T&gt; = Pick&lt;<br>  UseSuspenseQueryOptions&lt;T&gt;,<br>  &#39;queryKey&#39; | &#39;queryFn&#39;<br>&gt;;<br>export type BasicQueryOptions&lt;T&gt; = Pick&lt;<br>  UseQueryOptions&lt;T&gt;,<br>  &#39;queryKey&#39; | &#39;queryFn&#39;<br>&gt;;<br>export type BasicInfiniteQueryOptions&lt;T&gt; = Pick&lt;<br>  UseInfiniteQueryOptions&lt;T&gt;,<br>  &#39;queryKey&#39; | &#39;queryFn&#39; | &#39;initialPageParam&#39;<br>&gt;;<br>export type BasicSuspenseInifniteQueryOptions&lt;T&gt; = Pick&lt;<br>  UseSuspenseInfiniteQueryOptions&lt;T&gt;,<br>  &#39;queryKey&#39; | &#39;queryFn&#39; | &#39;initialPageParam&#39;<br>&gt;;</pre><p>추상화한 PrefetchBoundary를 적용시키면 보일러 플레이트 코드 없이 필요한 곳에서 간편하게 호출하여 사용할 수 있다.</p><pre>import {PrefetchBoundary} from &#39;@/shared/context/query/PrefetchBoundary&#39;;<br><br>const CardPage = () =&gt; {<br>  return (<br>    &lt;&gt;<br>     ...<br>        &lt;Suspense fallback={&lt;SkeletonCardList /&gt;}&gt;<br>          &lt;PrefetchBoundary prefetchOptions={getCardListQueryOptions()}&gt;<br>            &lt;CardList /&gt;<br>          &lt;/PrefetchBoundary&gt;<br>        &lt;/Suspense&gt;<br>    &lt;/&gt;<br>  );<br>};<br><br>export default CardPage;</pre><h3>이런 구조가 어떤 이점이 있을까?</h3><h4>구조</h4><p><strong>a) 서버 컴포넌트에서의 프리페칭</strong></p><ul><li>page.tsx는 서버 컴포넌트이며, 여기서 <strong>PrefetchBoundary</strong>를 통해 서버 사이드에서 데이터를 미리 가져온다.<strong>.</strong></li></ul><p><strong>b) 클라이언트 컴포넌트에서의 데이터 활용</strong></p><ul><li>useSuspenseQuery로 데이터를 가져온다.</li><li>프리페칭된 데이터는 HydrationBoundary를 통해 클라이언트에 전달된다.</li></ul><p>이러한 구조로 인해 성능 최적화 장점을 얻을 수 있다.</p><ul><li>서버 사이드에서 데이터를 미리 가져와 초기 페이지 로드 시 성능이 향상된다.</li><li>dehydrate된 데이터는 클라이언트에서 재사용되어 추가 네트워크 요청을 방지한다.</li></ul><h4>왜 성능이 향상될까?</h4><p><strong>1. 일반적인 클라이언트 사이드 페칭의 경우</strong></p><pre>1. HTML/JS 다운로드<br>2. JS 실행 (React 하이드레이션)<br>3. 컴포넌트 마운트<br>4. 데이터 페칭 시작<br>5. 데이터 받아옴<br>6. 리렌더링</pre><p><strong>2. 서버 사이드 프리페칭의 경우 (현재 구조)</strong></p><pre>1. 서버에서 데이터 페칭 (PrefetchBoundary)<br>2. 데이터와 함께 HTML/JS 전송 (dehydrate된 상태)<br>3. JS 실행 (React 하이드레이션)<br>4. 컴포넌트 마운트 (이미 데이터가 있는 상태)</pre><p>실제 예시로 네트워크 타임라인을 비교해보면</p><ul><li><strong>클라이언트 사이드 페칭</strong></li></ul><pre>|----- HTML/JS 다운로드 (100ms) -----|<br>                                    |----- JS 실행 (50ms) -----|<br>                                                             |----- 데이터 요청 (200ms) -----|<br>                                                                                           |----- 렌더링 (50ms) ----|<br>총 시간: ~400ms</pre><ul><li><strong>서버 사이드 프리페칭</strong></li></ul><pre>|----- 서버 데이터 페칭 (200ms) -----|<br>                                   |----- HTML/JS+데이터 다운로드 (100ms) -----|<br>                                                                            |----- 렌더링 (50ms) ----|<br>총 시간: ~350ms</pre><p>따라서 서버 사이드 프리페칭은 아래와 같은 이점을 제공한다.</p><p><strong>1. 전체적인 로딩 시간 단축<br> </strong>→ 사용자는 더 빠르게 페이지를 볼 수 있음.<br><strong>2. 사용자가 체감하는 성능 향상<br> </strong>→ 데이터를 기다리는 시간이 줄어듦.<br><strong>3. 네트워크 요청 수 감소<br> </strong>→ 클라이언트에서 중복 API 요청을 하지 않아도 됨.<br><strong>4. 초기 렌더링 최적화<br> </strong>→ 화면이 깜빡이거나, 빈 상태로 렌더링되는 문제가 줄어듦.</p><h3>결론</h3><p><strong>PrefetchBoundary</strong>와 <strong>HydrationBoundary</strong>를 활용하면 서버 사이드에서 데이터를 미리 가져와, 클라이언트에서는 <strong>즉시 렌더링</strong>이 가능하다. 이를 통해 <strong>초기 로딩 속도를 개선하고, 불필요한 네트워크 요청을 줄이는 효과</strong>를 얻을 수 있다.</p><p>Next.js에서 Suspense Boundary에 서버 액션 함수가 호출되는 경우가 많지 않아서 그런지, 관련된 레퍼런스를 찾기가 힘들었다.</p><p>Wraffle의 경우 Fetch Client인 apiClient에서 서버 액션을 사용하므로 Suspense와 Prefetch Boundary 패턴을 자주 사용할 것 같다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9089227fba7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/wraffle-tech/%EC%9D%B4%EC%A0%84-%ED%8F%AC%EC%8A%A4%ED%8A%B8%EC%97%90%EC%84%9C-%EC%95%8C%EB%A6%BC-%EB%AA%A9%EB%A1%9D-%ED%8E%98%EC%9D%B4%EC%A7%80-%EA%B5%AC%ED%98%84-%EA%B3%BC%EC%A0%95%EC%97%90%EC%84%9C-%EB%B0%9C%EC%83%9D%ED%95%9C-suspense-query%EC%99%80-%EC%84%9C%EB%B2%84-%EC%95%A1%EC%85%98-%EB%AC%B8%EC%A0%9C%EA%B0%80-%EC%B9%B4%EB%93%9C-%EB%AA%A9%EB%A1%9D-%ED%8E%98%EC%9D%B4%EC%A7%80%EC%97%90%EC%84%9C%EB%8F%84-%EB%8F%99%EC%9D%BC%ED%95%98%EA%B2%8C-%EB%B0%9C%EC%83%9D%ED%96%88%EB%8B%A4-d9089227fba7">Next.js에서 SuspenseQuery와 서버 액션을 함께 사용할 때의 문제와 해결 과정</a> was originally published in <a href="https://medium.com/wraffle-tech">Wraffle-Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Next.js에서 Auth.js 토큰 재발급이 무한 호출되는 이유와 해결 과정]]></title>
            <link>https://medium.com/wraffle-tech/next-js%EC%97%90%EC%84%9C-auth-js-%ED%86%A0%ED%81%B0-%EC%9E%AC%EB%B0%9C%EA%B8%89%EC%9D%B4-%EB%AC%B4%ED%95%9C-%ED%98%B8%EC%B6%9C%EB%90%98%EB%8A%94-%EC%9D%B4%EC%9C%A0%EC%99%80-%ED%95%B4%EA%B2%B0-%EA%B3%BC%EC%A0%95-d97819aa3c31?source=rss-2ace129286a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/d97819aa3c31</guid>
            <category><![CDATA[auth]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[nextauth]]></category>
            <dc:creator><![CDATA[Sangmin Tsx]]></dc:creator>
            <pubDate>Sun, 02 Mar 2025 11:47:06 GMT</pubDate>
            <atom:updated>2025-03-02T11:59:26.475Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://medium.com/wraffle-tech/fetch-api-client%EC%99%80-auth-js-nextauth-js-%EB%A5%BC-%EC%82%AC%EC%9A%A9%ED%95%9C-%EC%9D%B8%EC%A6%9D-%EA%B5%AC%ED%98%84%ED%95%98%EA%B8%B0-6fe9b1062bc2">Next.js에서 확장성을 고려한 Fetch API Client와 Auth.js를 사용한 인증 구현하기</a></p><p>지난 포스트에서 에서 공통 Fetch Client와 Auth.js를 통한 인증 설정에 대해 다뤘었다.</p><p>하지만 당시에는 <strong>토큰 재발급 관련 테스트를 진행하지 않았다</strong>. 만료 기간이 며칠씩 걸리기 때문에, 코드만 읽고 문제가 없다고 판단해 넘어갔었다. 그러나 이로 인해 예상치 못한 문제가 발생했다.</p><p>결론적으로 큰 수정사항은 없지만, <strong>문제를 해결해 나가는 과정과 사고 과정</strong>을 정리하고자 한다.</p><h3>문제 상황</h3><p>프론트엔드 서버를 실행한 후 브라우저에서 서비스를 확인하려 하면 간헐적으로 localhost가 <strong>무한 로딩되는 이슈</strong>가 발생했다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/234/1*jvwmR_4JkgwTfaVISCGtsw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*205bUI11UpYD70yHdD3YBg.png" /></figure><p>서버 로그를 확인해 보니, middleware에서 실행이 멈춘 것을 확인할 수 있었다.</p><pre>export async function middleware(req: NextRequest) {<br>  console.log(&#39;middleware 실행&#39;);<br>  const {nextUrl} = req;<br>  const session = await getSession();<br><br>  console.log(&#39;session: &#39;, session);<br>   ...</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*gff27XzfRCuAIUKoYhPr6Q.png" /></figure><p>middleware는 실행되었지만 session 정보가 출력되지 않았다.</p><p>즉, getSession을 통해 세션 정보를 받아오는 과정이 <strong>끝나지 않고</strong> 있어 middleware에서 태스크가 <strong>blocking</strong>된 것이다.</p><h3>왜 getSession()에서 함수가 끝나지 않는걸까?</h3><p>이상하게도 평소에는 middleware가 정상적으로 동작하다가 <strong>어느 순간 특정한 조건에서만 문제가 발생</strong>했다.</p><p>이슈를 해결하기 위해 <strong>브라우저 쿠키를 삭제</strong>하고 다시 실행했을 때 정상적으로 동작했다. 처음에는 일시적인 에러라고 생각했지만, 며칠 뒤 다시 같은 현상이 발생했다.</p><p>팀원들에게 공유해 보니, <strong>다른 FE 팀원들도 같은 문제를 겪고 있었다</strong>. 따라서 제대로 원인을 파악하고 해결해야겠다고 판단했다.</p><p>middleware의 getSession() 함수에서 항상 실행이 안되는 것이 아니라 <strong>특정 조건일 때만 실행이 되지 않는 것으로 판단했다.</strong></p><h4>getSession() 동작 과정</h4><p>getSession은 Auth.js에서 auth 정보를 서버 액션을 통해 반환하는 함수다. 그렇다면, 인증 정보를 받아오는 과정은 어떻게 진행될까?</p><pre>callbacks: {<br>  async jwt({ token, user }) {<br>    if (user) {<br>      token.accessToken = user.accessToken;<br>      token.refreshToken = user.refreshToken;<br>      token.accessTokenExpires = Date.now() + ACCESS_TOKEN_EXPIRES_IN * 1000;<br>    }<br><br>    if (Date.now() &lt; token.accessTokenExpires) {<br>      return token;<br>    }<br><br>    return await reissueToken(token);<br>  },<br><br>  async session({ session, token }) {<br>    session.accessToken = token.accessToken;<br>    session.refreshToken = token.refreshToken;<br>    return session;<br>  },<br>},</pre><p>jwt에서 <strong>토큰이 만료되었을 경우</strong>, reissueToken 함수를 호출하여 <strong>access token을 재발급</strong>받는다.</p><p>즉, middleware의 이슈가 간헐적으로 발생하고 있으며, getSession 내부적으로 <strong>토큰이 만료되었을 때 재발급 로직이 동작하는 것이 원인</strong>일 가능성이 높다.</p><h4>로그 출력</h4><p>각 단계에서 로그를 추가하여 확인해 보았다.</p><p>로그는 총 네 군데에서 출력했다.</p><pre>callbacks: {<br>    async jwt({token, user}) {<br>      if (user) {<br>        token.accessToken = user.accessToken;<br>        token.refreshToken = user.refreshToken;<br>        token.accessTokenExpires = Date.now() + ACCESS_TOKEN_EXPIRES_IN * 1000;<br>      }<br><br>      if (Date.now() &lt; token.accessTokenExpires) {<br>       console.log(&#39;토큰 만료 전&#39;); // 💡 토큰 만료되기 전 로그<br>        return token;<br>      }<br><br>      return await reissueToken(token);<br>    },<br><br>...<br><br>const reissueToken = async (token: JWT) =&gt; {<br>  try {<br>    console.log(&#39;토큰 만료, 발급 전&#39;); // 💡 토큰 재발급 함수 실행<br>    const response = await apiClient.post&lt;<br>      {accessToken: string},<br>      {refreshToken: string}<br>    &gt;(&#39;/auth/refresh&#39;, {<br>      body: {refreshToken: token.refreshToken},<br>      withAuth: true,<br>    });<br>    <br>    console.log(&#39;토큰 만료, 발급 후: &#39;, response.data.accessToken); // 💡 토큰 재발급 함수 성공<br><br>    return {<br>      ...token,<br>      accessToken: response.data.accessToken,<br>      accessTokenExpires: Date.now() + 10 * 1000,<br>    };<br>  } catch (error) {<br>    console.log(&#39;토큰 만료, 발급 실패&#39;); // 💡 토큰 재발급 함수 실패<br>    await signOut();<br>    return {...token, error: &#39;RefreshAccessTokenError&#39;};<br>  }<br>};</pre><ol><li>JWT 과정에서 토큰을 검증할 때 (만료 전)</li><li>토큰이 만료되어서 토큰 재발급 함수가 실행될 때 (토큰 만료, 발급 전)</li><li>토큰 재발급 함수가 성공했을 때 (토큰 만료, 발급 후)</li><li>토큰 재발급 함수가 실패했을 때 (토큰 만료, 발급 실패)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*ZxrAXPh7hjkb4iGrmnCgfg.png" /></figure><p>로그인 후 토큰이 발급되고, 해당 토큰은 아직 만료 전이므로 재발급 함수를 실행하지 않는다.</p><p>토큰 만료 시간이 지난 후 특정 동작을 했을 때 아래와 같은 로그가 출력된다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/232/1*213XLx4OmzSZuN4z44hldA.png" /></figure><p>출력된 로그를 확인한 결과, reissueToken 함수가 <strong>무한 호출되고 있었다.</strong></p><p>이로 인해 middleware가 blocking되면서 페이지가 <strong>무한 로딩</strong>되는 것이었다.</p><h4>reissueToken()이 무한 호출되는 이유</h4><p>reissueToken 함수 내부를 살펴보자.</p><pre>const reissueToken = async (token: JWT) =&gt; {<br>  try {<br>    const response = await apiClient.post&lt;<br>      {accessToken: string},<br>      {refreshToken: string}<br>    &gt;(&#39;/auth/refresh&#39;, {<br>      body: {refreshToken: token.refreshToken},<br>      withAuth: true,<br>    });<br><br>    return {<br>      ...token,<br>      accessToken: response.data.accessToken,<br>      accessTokenExpires: Date.now() + 10 * 1000,<br>    };<br>  } catch (error) {<br>    await signOut();<br>    return {...token, error: &#39;RefreshAccessTokenError&#39;};<br>  }<br>};</pre><p>apiClient를 통해 요청할 때 withAuth: true <strong>옵션이 문제</strong>였다.</p><p>내부적으로 withAuth가 true일 경우, Fetch Client에서 getSession()을 호출하도록 되어 있다.</p><pre>const session = withAuth ? await getSession() : null;</pre><p>즉, <strong>토큰 재발급을 요청할 때</strong> getSession()<strong>을 호출 →</strong> jwt ****callback <strong>실행 → 토큰 만료 →</strong> reissueToken() <strong>호출 →</strong> getSession() <strong>실행</strong></p><p>이 과정이 <strong>무한 루프</strong>에 빠지고 있었던 것이다.</p><p>즉, middleware가 간헐적으로 태스크가 멈춰 서비스를 실행하지 않는 이유는 토큰이 만료되는 시점에서 토큰 재발급 함수가 무한으로 호출되고 있어 blocking되고 있던 것이다.</p><h3>해결 방안</h3><p>Fetch Client를 사용하지 않고, <strong>기본</strong> fetch <strong>API</strong>를 사용해 getSession() 호출을 방지한다.</p><h4>1. 기본 fetch를 사용해서 토큰 재발급하기</h4><pre>const reissueToken = async (token: JWT) =&gt; {<br>  try {<br>    console.log(&#39;토큰 만료, 발급 전&#39;); // 💡 토큰 재발급 함수 실행<br>    const response = await fetch(`${API_BASE_URL}/auth/refresh`, {<br>      method: &#39;POST&#39;,<br>      body: JSON.stringify({refreshToken: token.refreshToken}),<br>      headers: {<br>        &#39;Content-Type&#39;: &#39;application/json&#39;,<br>        Authorization: `Bearer ${token.accessToken}`,<br>        credentials: &#39;include&#39;,<br>      },<br>    });<br><br>    const data = await response.json();<br>    <br>    if (!response.ok) {<br>      throw data;<br>    }<br><br>    console.log(&#39;토큰 만료, 발급 후: &#39;, data.accessToken); // 💡 토큰 재발급 함수 성공<br><br>    return {<br>      ...token,<br>      accessToken: data.accessToken,<br>      accessTokenExpires: Date.now() + 10 * 1000,<br>    };<br>  } catch (error) {<br>    console.log(&#39;토큰 만료, 발급 실패&#39;); // 💡 토큰 재발급 함수 실패<br>    await signOut();<br>    return {...token, error};<br>  }<br>};</pre><p>apiClient 대신 기본 fetch 함수를 사용해서 토큰 재발급 API를 호출하도록 수정했다.</p><p>재발급 API가 성공하면 정상적으로 토큰이 업데이트 되는 것을 확인할 수 있다.</p><h4>2. 백엔드에서 재발급 API를 Public 처리</h4><p>해당 이슈를 제보하니 백엔드 서버 팀에서 재발급 API를 public 처리 해주셨다.</p><p>header에 만료된 access token을 넣지 않고 body에 refresh token만 넣어서 요청하면 정상적으로 처리된다.</p><p>그렇다면 Fetch Client의 withAuth 옵션을 사용할 필요가 없으니 문제는 발생하지 않을 것이다.</p><pre>export const reissueToken = async (token: JWT) =&gt; {<br>  try {<br>    const {data} = await apiClient.post&lt;<br>      {accessToken: string},<br>      {refreshToken: string}<br>    &gt;(&#39;/auth/refresh&#39;, {<br>      body: {refreshToken: token.refreshToken},<br>    });<br><br>    return {<br>      ...token,<br>      accessToken: data.accessToken,<br>      accessTokenExpires: Date.now() + ACCESS_TOKEN_EXPIRES_IN * 1000,<br>    };<br>  } catch (error) {<br>    await signOutWithCredentials();<br>    return {...token, error};<br>  }<br>};</pre><h4>재발급 실패 후 로그아웃 처리</h4><p>서비스에서 인증이 필요한 API를 호출할 때 <strong>refreshToken</strong>이 만료되면, 토큰 재발급 요청이 실패하고 로그아웃 처리가 필요하다. 그러나 이 과정에서 예상치 못한 <strong>쿠키 삭제 문제</strong>가 발생했다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*K6gRa-Iw_pzJ5_FdNPTScw.png" /></figure><p>토큰 재발급 API가 실패하면 아래와 같은 <strong>UnhandledRejection</strong> 에러가 발생한다.</p><blockquote><strong>unhandledRejection: ReadonlyRequestCookiesError:</strong></blockquote><blockquote>Cookies can only be modified in a Server Action or Route Handler. Read more: <a href="https://nextjs.org/docs/app/api-reference/functions/cookies#cookiessetname-value-options">https://nextjs.org/docs/app/api-reference/functions/cookies#cookiessetname-value-options</a></blockquote><p>서비스 화면에서는 정상적으로 로그아웃 처리가 되어 로그인 페이지로 리다이렉트되지만, <strong>쿠키에서 session 정보가 삭제되지 않고 그대로 남아있다</strong>.</p><p>로그아웃 후에도 쿠키가 남아있으면 다음과 같은 문제가 발생한다.</p><ol><li><strong>middleware에서 getSession을 호출하면 session이 남아있다고 판단</strong></li><li><strong>JWT callback이 실행되어 계속해서 reissueToken 요청을 보냄</strong></li><li><strong>다시 로그인하여 토큰을 갱신하기 전까지 무한 요청 발생</strong></li></ol><p><a href="https://github.com/nextauthjs/next-auth/pull/10907">fix(next-auth): signOut and middleware cookie error by jbpin · Pull Request #10907 · nextauthjs/next-auth</a></p><p>관련 PR을 보면, signOut()을 호출해도 쿠키가 자동으로 삭제되지 않기 때문에 발생하는 문제임을 확인할 수 있다.</p><h4>🤔 왜 Auth.js의 signOut을 호출하면 쿠키 에러가 발생할까?</h4><p>Next.js의 App Router는 React의 <strong>서버 사이드 렌더링(SSR)</strong> 및 <strong>서버 컴포넌트(RSC)</strong> 를 위해 <strong>스트리밍(Streaming)</strong> 을 사용한다.</p><p>스트리밍에서는 응답 <strong>본문(body)</strong> 이 서버에서 렌더링되는 즉시 클라이언트로 전송된다.</p><p>그런데 <strong>쿠키 수정은 반드시 응답이 전송되기 전에 헤더(Header)에서 처리해야 한다</strong>.</p><p>즉, <strong>이미 응답 일부가 클라이언트로 전송된 후에는 쿠키를 수정할 수 없기 때문에 Next.js 서버 컴포넌트에서 쿠키 수정이 제한된다</strong>.</p><p><a href="https://nextjs.org/docs/app/api-reference/functions/cookies#cookiessetname-value-options">Functions: cookies | Next.js</a></p><p>Next.js에서는 서버 액션이나 Route Handler, 또는 Middleware를 이용하여 쿠키를 조작할 수 있다.</p><h4>Middleware에서 헤더를 설정하여 쿠키 삭제하기</h4><p>signOut()을 호출하면 Auth.js에서 로그아웃 처리가 되므로 getSession() 호출 시 session은 null이 반환된다. 하지만 여전히 <strong>쿠키에는 세션 정보가 남아있어 재발급 요청이 계속 발생하는 문제</strong>가 있다.</p><p>따라서 <strong>Middleware에서 세션 정보가 비어있다면 auth.js 관련 쿠키를 직접 삭제하는 방식</strong>으로 해결할 수 있다.</p><pre>import type {NextRequest} from &#39;next/server&#39;;<br>import {NextResponse} from &#39;next/server&#39;;<br>import {getSession} from &#39;@/shared/util/auth/server&#39;;<br><br>const PUBLIC_ROUTES = [&#39;/login&#39;, &#39;/join&#39;];<br>const LOGIN = &#39;/login&#39;;<br>const MAIN = &#39;/&#39;;<br><br>export async function middleware(req: NextRequest) {<br>  const {nextUrl} = req;<br><br>  const session = await getSession();<br><br>  const isAuthenticated = !!session;<br><br>  const isPublicRoute = PUBLIC_ROUTES.find(route =&gt;<br>    nextUrl.pathname.startsWith(route),<br>  );<br><br>  if (isAuthenticated &amp;&amp; isPublicRoute) {<br>    return NextResponse.redirect(new URL(MAIN, req.url));<br>  }<br><br>  if (!isAuthenticated &amp;&amp; !isPublicRoute) {<br>    return NextResponse.redirect(new URL(LOGIN, nextUrl));<br>  }<br><br>  if (!isAuthenticated) {<br>    const response = NextResponse.next();<br>    if (req.cookies.has(&#39;authjs.callback-url&#39;)) {<br>      response.cookies.set(&#39;authjs.callback-url&#39;, &#39;&#39;, {maxAge: 0});<br>    }<br>    if (req.cookies.has(&#39;authjs.session-token&#39;)) {<br>      response.cookies.set(&#39;authjs.session-token&#39;, &#39;&#39;, {maxAge: 0});<br>    }<br>    return response;<br>  }<br><br>  return NextResponse.next();<br>}<br><br>export const config = {<br>  matcher: [&#39;/((?!api|_next/static|_next/image|.*\\.png$).*)&#39;],<br>};</pre><p>refreshToken이 만료되었을 때 reissueToken이 실패하면 <strong>middleware에서 auth.js 쿠키를 삭제하여 무한 요청 문제를 해결</strong>할 수 있다.</p><h3>결론</h3><p>이렇게 <strong>토큰 재발급 실패 후 쿠키 삭제가 되지 않아 발생하는 무한 요청 문제를 해결</strong>했다.</p><p>다만, <strong>signOut 호출 후에도 한 번은 “Cookies can only be modified in a Server Action or Route Handler” 에러가 발생하는 단점</strong>이 있다.</p><p>현재 토큰 재발급 요청을 JWT callback 내부에서 하고있는데, middleware에서 요청의 응답이 401 에러를 반환할 때 실행하고 실패 시 signOut 처리하도록 하면 개선될 수 있을 것 같다. (FE에서 토큰 만료 시간을 가지고 있지 않아도 된다.)</p><p>현재 래플 API 스펙 중 토큰 만료가 아님에도 401을 반환하는 API가 있기 때문에 추후에 서버 팀과 스펙 논의 후 개선해보아도 좋을 것 같다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d97819aa3c31" width="1" height="1" alt=""><hr><p><a href="https://medium.com/wraffle-tech/next-js%EC%97%90%EC%84%9C-auth-js-%ED%86%A0%ED%81%B0-%EC%9E%AC%EB%B0%9C%EA%B8%89%EC%9D%B4-%EB%AC%B4%ED%95%9C-%ED%98%B8%EC%B6%9C%EB%90%98%EB%8A%94-%EC%9D%B4%EC%9C%A0%EC%99%80-%ED%95%B4%EA%B2%B0-%EA%B3%BC%EC%A0%95-d97819aa3c31">Next.js에서 Auth.js 토큰 재발급이 무한 호출되는 이유와 해결 과정</a> was originally published in <a href="https://medium.com/wraffle-tech">Wraffle-Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Server Component에서 Suspense Query를 사용하여 Next.js Streaming 서버 렌더링 적용하기]]></title>
            <link>https://medium.com/wraffle-tech/server-component%EC%97%90%EC%84%9C-suspense-query%EB%A5%BC-%EC%82%AC%EC%9A%A9%ED%95%98%EC%97%AC-next-js-streaming-%EC%84%9C%EB%B2%84-%EB%A0%8C%EB%8D%94%EB%A7%81-%EC%A0%81%EC%9A%A9%ED%95%98%EA%B8%B0-3a5bfd1efb55?source=rss-2ace129286a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a5bfd1efb55</guid>
            <category><![CDATA[suspense]]></category>
            <category><![CDATA[server-action]]></category>
            <category><![CDATA[react-query]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Sangmin Tsx]]></dc:creator>
            <pubDate>Thu, 09 Jan 2025 16:43:06 GMT</pubDate>
            <atom:updated>2025-03-03T13:29:30.783Z</atom:updated>
            <content:encoded><![CDATA[<p>클라이언트 컴포넌트에서 알림 목록 API를 useSuspenseInfiniteQuery를 통해 받아오는 동안 서버 컴포넌트에서 Suspense fallback UI를 보여주면서 문제가 발생했다.</p><p>문제 발생과 해결 과정을 함께 살펴보자.</p><p>+ 2025.3.3) 해당 문제에 대해 자세하게 분석하고 해결한 과정을 따로 포스팅했다. 해당 포스트에서는 알림 목록 적용기에 대한 내용만 남겨둔다</p><p><a href="https://medium.com/wraffle-tech/%EC%9D%B4%EC%A0%84-%ED%8F%AC%EC%8A%A4%ED%8A%B8%EC%97%90%EC%84%9C-%EC%95%8C%EB%A6%BC-%EB%AA%A9%EB%A1%9D-%ED%8E%98%EC%9D%B4%EC%A7%80-%EA%B5%AC%ED%98%84-%EA%B3%BC%EC%A0%95%EC%97%90%EC%84%9C-%EB%B0%9C%EC%83%9D%ED%95%9C-suspense-query%EC%99%80-%EC%84%9C%EB%B2%84-%EC%95%A1%EC%85%98-%EB%AC%B8%EC%A0%9C%EA%B0%80-%EC%B9%B4%EB%93%9C-%EB%AA%A9%EB%A1%9D-%ED%8E%98%EC%9D%B4%EC%A7%80%EC%97%90%EC%84%9C%EB%8F%84-%EB%8F%99%EC%9D%BC%ED%95%98%EA%B2%8C-%EB%B0%9C%EC%83%9D%ED%96%88%EB%8B%A4-d9089227fba7">Next.js에서 SuspenseQuery와 서버 액션을 함께 사용할 때의 문제와 해결 과정</a></p><h3>Notification 페이지네이션 API 연동하기</h3><p>알림 목록 페이지는 <strong>커서 기반 페이지네이션</strong>으로 서버에서 데이터를 전해준다.</p><p>페이지네이션 데이터를 무한스크롤을 통해 보여주어야 되기 때문에 React Query의 useSuspenseInfiniteQuery를 사용하여 데이터 페칭을 구현하기로 했다.</p><p>SuspenseQuery를 사용하면 로딩 상태를 선언적으로 관리할 수 있다.</p><p>커서 페이지네이션 API 데이터인 notificationData를 받기 위한 useHandleNotifications는 아래와 같이 구현했다.</p><pre>// widgets/notification-list/hook/useHandleNotifications.ts<br><br>import {useRouter} from &#39;next/navigation&#39;;<br>import {useCallback, useMemo} from &#39;react&#39;;<br>import type {GetNotificationListParams} from &#39;@/features/get-notification/api&#39;;<br>import {<br>  useGETNotificationListQuery,<br>  usePATCHNotificationQuery,<br>} from &#39;@/features/get-notification/api&#39;;<br>import {useQueryClient} from &#39;@tanstack/react-query&#39;;<br><br>export const useHandleNotifications = ({params}: GetNotificationListParams) =&gt; {<br>  const router = useRouter();<br>  const queryClient = useQueryClient();<br><br>  const {<br>    data,<br>    fetchNextPage: fetchNextNotification,<br>    hasNextPage: hasNextNotification,<br>    isFetchingNextPage: isFetchingNextNotification,<br>  } = useGETNotificationListQuery({params});<br><br>  const {readNotificatoin} = usePATCHNotificationQuery();<br><br>  const notificationData = useMemo(<br>    () =&gt; data.pages.flatMap(page =&gt; page.items),<br>    [data],<br>  );<br><br>  const onReadNotification = useCallback(<br>    (id: number) =&gt; {<br>      readNotificatoin(id, {<br>        onSuccess: () =&gt; {<br>          queryClient.invalidateQueries({queryKey: [&#39;GET_NOTIFICATION_LIST&#39;]});<br>          router.push(`/notification/${id}`);<br>        },<br>      });<br>    },<br>    [queryClient, readNotificatoin, router],<br>  );<br><br>  const onFetchNextNotifications = useCallback(() =&gt; {<br>    if (hasNextNotification &amp;&amp; !isFetchingNextNotification) {<br>      fetchNextNotification();<br>    }<br>  }, [fetchNextNotification, hasNextNotification, isFetchingNextNotification]);<br><br>  return {<br>    notificationData,<br>    hasNextNotification,<br>    onReadNotification,<br>    onFetchNextNotifications,<br>  };<br>};</pre><p>알림 데이터를 사용하기 위한 함수와 데이터 가공을 해당 훅에서 정의한다.</p><p>실제 API Fetch 부분인 useGETNotificationListQuery와 usePATCHNotificationAPI는 아래와 같다.</p><pre>import {getNotificationInfiniteQueryOptions} from &#39;../config&#39;;<br>import type {Notification} from &#39;@/entities/notification&#39;;<br>import type {CursorPagination} from &#39;@/entities/pagination&#39;;<br>import apiClient from &#39;@/shared/api/apiClient&#39;;<br>import {useMutation, useSuspenseInfiniteQuery} from &#39;@tanstack/react-query&#39;;<br><br>export interface GetNotificationListRequest {<br>  itemsPerPage?: number;<br>  cursorId?: number;<br>}<br><br>export interface GetNotificationListResponse {<br>  items: Notification[];<br>  pagination: CursorPagination;<br>}<br><br>export interface GetNotificationListParams {<br>  params: GetNotificationListRequest;<br>}<br><br>export const getNotificationListAPI = async (<br>  params: GetNotificationListRequest,<br>) =&gt; {<br>  const response = await apiClient.get&lt;GetNotificationListResponse&gt;(<br>    `/push-notices/me`,<br>    {withAuth: true, params},<br>  );<br><br>  return response.data;<br>};<br><br>export const patchNotificationAPI = async (notificationId: number) =&gt; {<br>  await apiClient.patch(`/push-notices/${notificationId}`, {withAuth: true});<br>};<br><br>export const GET_NOTIFICATION_LIST_KEY = (<br>  params: GetNotificationListRequest,<br>) =&gt; [&#39;GET_NOTIFICATION_LIST&#39;, params.cursorId, params.itemsPerPage];<br><br>export const useGETNotificationListQuery = ({<br>  params,<br>}: GetNotificationListParams) =&gt; {<br>  return useSuspenseInfiniteQuery({<br>    ...getNotificationInfiniteQueryOptions({params}),<br>    getNextPageParam: (lastPage: GetNotificationListResponse) =&gt; {<br>      if (lastPage.pagination.hasNextData) {<br>        return lastPage.pagination.cursor;<br>      }<br>      return undefined;<br>    },<br>  });<br>};<br><br>export const usePATCHNotificationQuery = () =&gt; {<br>  const mutation = useMutation({<br>    mutationFn: patchNotificationAPI,<br>  });<br><br>  return {readNotificatoin: mutation.mutate};<br>};</pre><p>실제 Fetch 요청을 하는 getNotificationListAPI 함수는 API URL에 queryString으로 파라미터 정보가 포함되어 요청한다.</p><p>fetchClient에 커스텀으로 만들어 둔 params 옵션을 사용하여 파라미터를 넘겨준다.</p><p>Patch API는 useMutation을 사용하여 성공과 실패에 대한 fallback을 외부에서 주입할 수 있도록 구현한다.</p><pre>// widgets/notification-list/ui/list/NotificationList.tsx<br><br>&#39;use client&#39;;<br><br>import {useHandleNotifications} from &#39;../../hook&#39;;<br>import {NotificationItem} from &#39;../item/NotificationItem&#39;;<br><br>export const NotificationList = () =&gt; {<br>  const {<br>    notificationData,<br>    hasNextNotification,<br>    onReadNotification,<br>    onFetchNextNotifications,<br>  } = useHandleNotifications({<br>    params: {itemsPerPage: 10},<br>  });<br><br>  return (<br>    &lt;div className=&#39;flex flex-col divide-y divide-[#E0E0E0]&#39;&gt;<br>      &lt;InfiniteScroll<br>        onEnd={onFetchNextNotifications}<br>        disabled={!hasNextNotification}<br>      &gt;<br>        {notificationData.map(notification =&gt; (<br>          &lt;NotificationItem<br>            id={notification.id}<br>            key={notification.id}<br>            title={notification.title}<br>            description={notification.content}<br>            date={notification.createdAt}<br>            isRead={notification.isRead}<br>            handleReadNotification={onReadNotification}<br>          /&gt;<br>        ))}<br>      &lt;/InfiniteScroll&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><pre>// app/notification/page.tsx<br><br>import {Suspense} from &#39;react&#39;;<br>import {NotificationList} from &#39;@/widgets/notification-list/ui&#39;;<br>...<br><br>const NotificationPage = () =&gt; {<br>  return (<br>    &lt;&gt;<br>     ...<br>      &lt;Suspense fallback={&lt;div&gt;Loading...&lt;/div&gt;}&gt;<br>        &lt;NotificationList /&gt;<br>      &lt;/Suspense&gt;<br>    &lt;/&gt;<br>  );<br>};</pre><p>실행해보면 실제로 렌더링은 잘 되지만 아래와 같은 에러가 발생한다.</p><blockquote><strong><em>Unhandled Runtime Error <br>Error: Server Functions cannot be called during initial render. This would create a fetch waterfall. Try to use a Server Component to pass data to Client Components instead.</em></strong></blockquote><p><a href="https://github.com/TanStack/query/issues/6591">Nextjs Streaming+Server Action Error: Server Functions cannot be called during initial render. · Issue #6591 · TanStack/query</a></p><p>+ 2025.3.3) 해당 문제의 원인과 해결 과정을 기록한 포스트로 해결 과정 내용을 대체합니다.</p><pre>import {getNotificationInfiniteQueryOptions} from &#39;@/features/get-notification/config&#39;;<br>import {PrefetchBoundary} from &#39;@/shared/context/query/PrefetchBoundary&#39;;<br>import {NotificationList} from &#39;@/widgets/notification-list/ui&#39;;<br>...<br><br>const NotificationPage = async () =&gt; {<br>  return (<br>    &lt;&gt;<br>     ...<br>      &lt;PrefetchBoundary<br>        prefetchOptions={getNotificationInfiniteQueryOptions({<br>          params: {itemsPerPage: 10},<br>        })}<br>       &gt;<br>         &lt;NotificationList /&gt;<br>       &lt;/PrefetchBoundary&gt;<br>    &lt;/&gt;<br>  );<br>};<br><br>export default NotificationPage;</pre><p>PrefetchBoundary내부에서 queryClient를 생성해 데이터를 prefetch한다.</p><p>이 prefetch 결과가 담긴 queryClient를 dehydrate 함수를 사용하여 직렬화 상태의 QueryClient를 하위 컴포넌트인 NotificationList로 전달한다.</p><pre>&#39;use client&#39;;<br><br>import {useHandleNotifications} from &#39;../../hook&#39;;<br>import {NotificationItem} from &#39;../item/NotificationItem&#39;;<br>import {InfiniteScroll} from &#39;@/shared/ui&#39;;<br><br>export const NotificationList = () =&gt; {<br>  const {<br>    notificationData,<br>    hasNextNotification,<br>    onReadNotification,<br>    onFetchNextNotifications,<br>  } = useHandleNotifications({<br>    params: {itemsPerPage: 10},<br>  });<br>  return (<br>    &lt;div className=&#39;flex flex-col divide-y divide-[#E0E0E0]&#39;&gt;<br>      &lt;InfiniteScroll<br>        onEnd={onFetchNextNotifications}<br>        disabled={!hasNextNotification}<br>      &gt;<br>        {notificationData.map(notification =&gt; (<br>          &lt;NotificationItem<br>            id={notification.id}<br>            key={notification.id}<br>            title={notification.title}<br>            description={notification.content}<br>            date={notification.createdAt}<br>            isRead={notification.isRead}<br>            handleReadNotification={onReadNotification}<br>          /&gt;<br>        ))}<br>      &lt;/InfiniteScroll&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QRcoa2lmRCynz-b8NjGWug.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*0dJMkhE53QncMfk5ketogA.gif" /><figcaption>suspense 없이 Server에서 prefetch한 결과</figcaption></figure><p>실행 결과를 보면 잘 동작하지만 <strong>알림 페이지에 접근 시 서버에서 알림 데이터를 prefetching하는 동안 페이지 접근이 제한</strong>된다. <br>prefetching이 완료되고 나서 pre-render된 데이터를 클라이언트 컴포넌트에 넘겨주어야 하므로 그 만큼의 로딩 지연시간이 발생하는 듯 하다.</p><p>prefethcing을 진행하는 부분을 Suspense로 감싸 Streaming 서버 렌더링을 적용한다면 데이터 페칭이 되는 동안 fallback UI를 pre-rendering을 통해 사용자에게 우선 보여주고 데이터 페칭이 완료되면 해당 부분을 hydration할 수 있다.</p><h3>Streaming 적용하기</h3><p>위 방법을 토대로 Streaming을 적용하려면 prefetch를 호출하는 부분을 Suspense 바운더리로 감싸주면 된다.</p><pre>// app/notification/page.tsx<br><br>import {Suspense} from &#39;react&#39;;<br>import {getNotificationInfiniteQueryOptions} from &#39;@/features/get-notification/config&#39;;<br>import {PrefetchBoundary} from &#39;@/shared/context/query/PrefetchBoundary&#39;;<br>import {NotificationList} from &#39;@/widgets/notification-list/ui&#39;;<br>...<br><br>const NotificationPage = () =&gt; {<br>  return (<br>    &lt;&gt;<br>      ...<br>      &lt;Suspense fallback={&lt;NotificationSkeleton /&gt;}&gt;<br>        &lt;PrefetchBoundary<br>          prefetchOptions={getNotificationInfiniteQueryOptions({<br>            params: {itemsPerPage: 10},<br>          })}<br>        &gt;<br>          &lt;NotificationList /&gt;<br>        &lt;/PrefetchBoundary&gt;<br>      &lt;/Suspense&gt;<br>    &lt;/&gt;<br>  );<br>};<br><br>export default NotificationPage;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*E07nbbaELGV071qKPxLgww.gif" /></figure><p>알림 페이지에 접근 시 prefetching을 진행하는 부분을 fallback UI로 서버에서 pre-rendering하여 클라이언트 컴포넌트에 전달하고, 데이터 페칭이 완료되면 데이터를 hydration하여 클라이언트 컴포넌트에 보여주는 식으로 동작한다.</p><p>이전과 달리 서버에서 prefetch하는 동안 페이지 렌더링이 지연되는 것이 아니라 <strong>prefetch 되는 컴포넌트는 Suspense fallback UI로 대체되어 즉시 화면이 렌더링</strong> 되는 것을 확인할 수 있다.</p><p>알림 페이지에서 알림목록 외에도 다른 API를 prefetching을 진행한다면 streaming으로 hydration이 완료된 컴포넌트부터 보여줄 것이다.</p><h3>마무리..</h3><p>prefetch 과정 없이, streaming을 가능하게 해주는<a href="https://tanstack.com/query/v5/docs/framework/react/guides/advanced-ssr#experimental-streaming-without-prefetching-in-nextjs">ReactQueryStreamedHydration</a>라는 experimental 기능이 있다고 한다.</p><p>나중에 안정화되면 리팩토링 해봐도 좋을 것 같다.</p><h3>참고 자료</h3><ul><li><a href="https://tanstack.com/query/latest/docs/framework/react/guides/advanced-ssr">Advanced Server Rendering | TanStack Query React Docs</a></li><li><a href="https://velog.io/@stakbucks/React-Query%EC%99%80-streaming-%ED%95%98%EA%B8%B0">React Query 환경에서 Next.js와 streaming 이용하기</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a5bfd1efb55" width="1" height="1" alt=""><hr><p><a href="https://medium.com/wraffle-tech/server-component%EC%97%90%EC%84%9C-suspense-query%EB%A5%BC-%EC%82%AC%EC%9A%A9%ED%95%98%EC%97%AC-next-js-streaming-%EC%84%9C%EB%B2%84-%EB%A0%8C%EB%8D%94%EB%A7%81-%EC%A0%81%EC%9A%A9%ED%95%98%EA%B8%B0-3a5bfd1efb55">Server Component에서 Suspense Query를 사용하여 Next.js Streaming 서버 렌더링 적용하기</a> was originally published in <a href="https://medium.com/wraffle-tech">Wraffle-Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Next.js에서 zod, react-hook-form, @use-funnel을 사용하여 회원가입 스텝 구현하기]]></title>
            <link>https://medium.com/wraffle-tech/next-js%EC%97%90%EC%84%9C-zod-react-hook-form-use-funnel%EC%9D%84-%EC%82%AC%EC%9A%A9%ED%95%98%EC%97%AC-%ED%9A%8C%EC%9B%90%EA%B0%80%EC%9E%85-%EC%8A%A4%ED%85%9D-%EA%B5%AC%ED%98%84%ED%95%98%EA%B8%B0-7daa87bfa108?source=rss-2ace129286a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/7daa87bfa108</guid>
            <category><![CDATA[toss]]></category>
            <category><![CDATA[zod]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[react-hook-form]]></category>
            <category><![CDATA[funnel]]></category>
            <dc:creator><![CDATA[Sangmin Tsx]]></dc:creator>
            <pubDate>Fri, 27 Dec 2024 18:27:58 GMT</pubDate>
            <atom:updated>2025-02-17T17:28:03.039Z</atom:updated>
            <content:encoded><![CDATA[<p>Wraffle의 회원가입 플로우는 총 4단계의 스텝으로 진행된다.</p><ul><li>이메일, 비밀번호, 비밀번호 확인 → Info Step</li><li>이름, 닉네임 → Name Step</li><li>전화번호 인증 → Phone Step<br>- 전화번호 입력<br>- 인증번호 입력</li><li>약관 동의 → Extra</li></ul><p>여러 스텝으로 나눠져 있다 보니 toss의Funnel 패턴 을 도입하려고 한다.</p><h3>적용 방법에 대하여..</h3><p>Funnel을 도입하기 위해 wraffle 팀에서 3가지 방안을 생각해봤다.</p><ul><li>slash의 @toss/use-funnel 사용하기</li><li>@use-funnel 사용하기</li><li>직접 구현하기</li></ul><h4>@toss/use-funnel</h4><p>@toss/use-funnel은 Toss팀에서 구현한 오픈 소스 라이브러리인 slash의 패키지 중 하나이다.</p><p>funnel 기능을 사용하기 위해 slash 라이브러리를 설치해야 하며, 제대로 된 상태관리를 지원하지 않아 상태관리는 퍼널과 별개로 직접 해야 하는 문제가 있다.</p><blockquote><em>@toss/use-funnel</em>은 더 이상 지원되지 않습니다. 새로운 패키지 <em>@use-funnel</em>로 전환되었으며, 기능성과 성능 또한 한층 더 개선되었습니다.</blockquote><p>이러한 문제점을 인식해선지 새로운 패키지로 배포했다고 한다.</p><h4>@use-funnel</h4><p>Toss팀에서 기존 funnel을 개선한 새로운 라이브러리다.<br>공개된 지 얼마 되지 않아서 참고할만한 레퍼런스가 많이 없다.</p><ul><li><a href="https://toss.tech/article/use-funnel-1">@use-funnel 개발기 #1: 왜 기존 라이브러리를 두고 새로 만들었나?</a></li><li><a href="https://toss.tech/article/use-funnel-2">@use-funnel 개발기 #2: 기존 라이브러리를 어떻게 뜯어 고칠 것인가?</a></li></ul><p>도입 당시에는 공식 문서 외에는 문서가 거의 없었는데 2024.12.09 기준으로 사내 기술 블로그에 관련 포스팅이 올라오고 있다.</p><h4>직접 구현하기</h4><p>예전에 @toss/use-funnel의 라이브러리를 분석하여 필요한 기능만 직접 구현하여 사용해본 적이 있다.</p><p>서드 파티 라이브러리에 의존하지 않아도 된다는 장점이 있지만 이전에 구현해본 경험으로는 스텝에 따른 상태가 관리되지 않기 때문에 추가적인 상태 관리 방법이 필요했다.</p><p>새로운 @use-funnel도 오픈 소스 프로젝트기 때문에 원본 코드 기반으로 구현해보다가 문득 이럴 거면 설치해서 쓰는거랑 다를게 없지 않나 라는 생각이 들었다. 토스 팀에서 유지보수도 해주는데 안쓸 이유가 없었다.</p><h4>결론은…</h4><p>새로운 @@use-funnel라이브러리를 사용하는 방향으로 결정했다.<br>신생 라이브러리라 레퍼런스가 많이 없고 아직 안정적이지 않을 수 있지만 친절한 공식문서와 빠른 업데이트가 될거라 생각했다.</p><h3>회원가입 스텝 구현하기</h3><h4>설치</h4><p><a href="https://use-funnel.slash.page/ko">@use-funnel: 강력하고 안전한 단계별 상태 관리 라이브러리</a></p><pre>pnpm i @use-funnel/browser</pre><p>next의 app router는 browser history 방식을 사용하기 때문에 browser 버전으로 설치하여 사용했다.</p><h4>사용하기</h4><pre>import {useFunnel} from &#39;@use-funnel/browser&#39;;<br><br>const funnel = useFunnel&lt;JoinStep&gt;({<br>  id: &#39;join&#39;,<br>  initial: {<br>    step: &#39;Info&#39;,<br>    context: {},<br>  },<br>});</pre><pre>export type JoinStep = {<br>  Info: {<br>    email?: string;<br>    password?: string;<br>  };<br>  Name: {<br>    email: string;<br>    password: string;<br>    name?: string;<br>    nickname?: string;<br>  };<br>  Phone: {<br>    email: string;<br>    password: string;<br>    name: string;<br>    nickname: string;<br>    phoneNumber?: string;<br>  };<br>  Extra: {<br>    email: string;<br>    password: string;<br>    name: string;<br>    nickname: string;<br>    phoneNumber: string;<br>    isAgreed?: boolean;<br>    isPrivacyAgreed?: boolean;<br>    isThirdAgreed?: boolean;<br>    isMarketingAgreed?: boolean;<br>  };<br>};</pre><p>useFunnel의 제네릭 타입으로 들어가는 JoinStep타입은 각 스텝에서 가지고 있을 수 있는 상태의 값을 모두 선언해주어야 한다.</p><p>Info스텝에서는 email과 password를 받기 전이므로 optional이고, 다음 스텝인 Name에서는 email과 password를 받고 넘어왔기 때문에 필수값이어야 한다.</p><pre>&lt;funnel.Render<br>  Info={({history}) =&gt; (<br>    &lt;Info<br>      onNext={(email, password) =&gt; history.push(&#39;Name&#39;, {email, password})}<br>    /&gt;<br>  )}<br>  Name={({history}) =&gt; (<br>    &lt;Name<br>      onNext={(name, nickname) =&gt; history.push(&#39;Phone&#39;, {name, nickname})}<br>    /&gt;<br>  )}<br>  Phone={({history}) =&gt; (<br>    &lt;PhoneFunnel onNext={phoneNumber =&gt; history.push(&#39;Extra&#39;, {phoneNumber})} /&gt;<br>  )}<br>  Extra={() =&gt; &lt;Extra /&gt;}<br>/&gt;;</pre><p>funnel.Render 의 속성으로 명시한 Step을 선언한다.</p><p>각 step에서 history, context 등 funnel이 가지고 있는 상태를 가져다가 사용할 수 있다.<br>다음 스텝으로 넘어갈 때 현재 스텝에서 작성한 상태를 history.push를 통해 저장한다.</p><p>전화번호 인증에서도 2개의 스텝으로 분리되기 때문에 Sub Funnel을 생성하여 사용했다.</p><pre>import Code from &#39;./Code&#39;;<br>import PhoneNumber from &#39;./PhoneNumber&#39;;<br>import {useFunnel} from &#39;@use-funnel/browser&#39;;<br><br>interface PhoneProps {<br>  onNext(phoneNumber: string): void;<br>}<br><br>const PhoneFunnel = ({onNext}: PhoneProps) =&gt; {<br>  const funnel = useFunnel&lt;{<br>    PhoneNumber: {phoneNumber?: string; code?: string};<br>    Code: {phoneNumber: string; code?: string};<br>  }&gt;({<br>    id: &#39;phone&#39;,<br>    initial: {<br>      step: &#39;PhoneNumber&#39;,<br>      context: {},<br>    },<br>  });<br><br>  return (<br>    &lt;funnel.Render<br>      PhoneNumber={({history}) =&gt; (<br>        &lt;PhoneNumber<br>          onNext={phoneNumber =&gt; history.push(&#39;Code&#39;, {phoneNumber})}<br>        /&gt;<br>      )}<br>      Code={({context}) =&gt; &lt;Code onNext={() =&gt; onNext(context.phoneNumber)} /&gt;}<br>    /&gt;<br>  );<br>};<br><br>export {PhoneFunnel};</pre><h3>Zod와 React Hook Form을 사용한 회원가입 폼 Validation 처리</h3><h4>GenericForm</h4><p>회원가입 Funnel의 각 스텝에서 Validation을 위한 Input을 사용하므로 Funnel 컴포넌트를 react-hook-form의 FormProvider로 감싸주어야 한다.</p><pre>&#39;use client&#39;;<br><br>import type {z} from &#39;zod&#39;;<br>import {useRouter} from &#39;next/navigation&#39;;<br>import {startTransition} from &#39;react&#39;;<br>import {Header, ProgressBar, GenericForm} from &#39;@/shared/ui&#39;;<br>import {signUpUser} from &#39;@/widgets/join/api/server&#39;;<br>import type {JoinStep} from &#39;@/widgets/join/config&#39;;<br>import {joinDefaultValues, joinSchema} from &#39;@/widgets/join/config&#39;;<br>import {Info, Name, Extra, PhoneFunnel} from &#39;@/widgets/join/ui&#39;;<br>import {zodResolver} from &#39;@hookform/resolvers/zod&#39;;<br>import {useFunnel} from &#39;@use-funnel/browser&#39;;<br>import {useToast} from &#39;@wraffle/ui&#39;;<br><br>const Join = () =&gt; {<br>  const {toast} = useToast();<br>  const router = useRouter();<br><br>  const onSubmit = (data: z.infer&lt;typeof joinSchema&gt;) =&gt; {<br>  ...<br>  };<br><br>  const funnel = useFunnel&lt;JoinStep&gt;({<br>    id: &#39;join&#39;,<br>    initial: {<br>      step: &#39;Info&#39;,<br>      context: {},<br>    },<br>  });<br><br>  return (<br>    &lt;div&gt;<br>      &lt;section className=&#39;py-5&#39;&gt;<br>        &lt;Header&gt;<br>          &lt;Header.Left&gt;<br>            &lt;Header.BackButton onClick={() =&gt; funnel.history.back()} /&gt;<br>          &lt;/Header.Left&gt;<br>        &lt;/Header&gt;<br>        &lt;ProgressBar totalSteps={4} index={funnel.index} /&gt;<br>      &lt;/section&gt;<br><br>      &lt;section className=&#39;px-5&#39;&gt;<br>        &lt;GenericForm<br>          onSubmit={onSubmit}<br>          formOptions={{<br>            mode: &#39;onChange&#39;,<br>            resolver: zodResolver(joinSchema),<br>            defaultValues: joinDefaultValues,<br>          }}<br>        &gt;<br>          &lt;funnel.Render<br>            Info={({history}) =&gt; (<br>              &lt;Info<br>                onNext={(email, password) =&gt;<br>                  history.push(&#39;Name&#39;, {email, password})<br>                }<br>              /&gt;<br>            )}<br>            Name={({history}) =&gt; (<br>              &lt;Name<br>                onNext={(name, nickname) =&gt;<br>                  history.push(&#39;Phone&#39;, {name, nickname})<br>                }<br>              /&gt;<br>            )}<br>            Phone={({history}) =&gt; (<br>              &lt;PhoneFunnel<br>                onNext={phoneNumber =&gt; history.push(&#39;Extra&#39;, {phoneNumber})}<br>              /&gt;<br>            )}<br>            Extra={() =&gt; &lt;Extra /&gt;}<br>          /&gt;<br>        &lt;/GenericForm&gt;<br>      &lt;/section&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default Join;</pre><pre>import {Form} from &#39;./RHF/core/Form&#39;;<br>import type {SubmitHandler, UseFormProps, FieldValues} from &#39;react-hook-form&#39;;<br>import {useForm} from &#39;react-hook-form&#39;;<br><br>interface GenericFormInterface&lt;TFormData extends FieldValues&gt; {<br>  onSubmit: SubmitHandler&lt;TFormData&gt;;<br>  formOptions: UseFormProps&lt;TFormData&gt;;<br>  children: React.ReactNode;<br>}<br><br>const GenericForm = &lt;TFormData extends FieldValues&gt;({<br>  onSubmit,<br>  formOptions,<br>  children,<br>}: GenericFormInterface&lt;TFormData&gt;) =&gt; {<br>  const methods = useForm&lt;TFormData&gt;(formOptions);<br><br>  return (<br>    &lt;Form {...methods}&gt;<br>      &lt;form onSubmit={methods.handleSubmit(onSubmit)}&gt;{children}&lt;/form&gt;<br>    &lt;/Form&gt;<br>  );<br>};<br><br>export default GenericForm;</pre><p>GenericForm 내부에서 useForm을 선언하여 method를 FormProvider로 전달한다. (Form 컴포넌트)</p><p>formOption을 zod schema를 사용한 방식으로 전달받는다.</p><pre>&lt;GenericForm&lt;JoinPayload&gt;<br>	...<br>&lt;/GenricForm&gt;</pre><p>위 처럼 제네릭 컴포넌트 형식으로 사용 가능하지만.. GenricForm에 타입을 넘겨줘도 결국 사용하는 곳에서 useFormContext에 타입을 지정해주어야 자동완성이 된다.</p><h3>Zod Schema</h3><pre>import {z} from &#39;zod&#39;;<br>import {<br>  emailSchema,<br>  passwordRegex,<br>  passwordSchema,<br>} from &#39;@/entities/auth/schema&#39;;<br>import {getDefaults} from &#39;@/shared/util&#39;;<br><br>export const confirmPasswordSchema = z<br>  .string()<br>  .regex(<br>    passwordRegex,<br>    &#39;비밀번호는 영문, 숫자, 특수문자 조합으로 8자 이상 형식입니다.&#39;,<br>  )<br>  .default(&#39;&#39;);<br><br>export const nameSchema = z<br>  .string()<br>  .min(1, {message: &#39;이름을 입력해 주세요.&#39;})<br>  .default(&#39;&#39;);<br><br>export const nicknameSchema = z<br>  .string()<br>  .min(1, {message: &#39;닉네임을 입력해 주세요.&#39;})<br>  .default(&#39;&#39;);<br><br>export const phoneNumberSchema = z<br>  .string()<br>  .min(1, {message: &#39;전화번호를 입력해 주세요.&#39;})<br>  .default(&#39;&#39;);<br><br>export const isAgreedSchema = z<br>  .boolean()<br>  .default(false)<br>  .refine(val =&gt; val === true, {<br>    message: &#39;필수 선택입니다.&#39;,<br>  });<br>export const isPrivacyAgreedSchema = z<br>  .boolean()<br>  .default(false)<br>  .refine(val =&gt; val === true, {<br>    message: &#39;필수 선택입니다.&#39;,<br>  });<br>export const isThirdAgreedSchema = z<br>  .boolean()<br>  .default(false)<br>  .refine(val =&gt; val === true, {<br>    message: &#39;필수 선택입니다.&#39;,<br>  });<br>export const isMarketingAgreedSchema = z.boolean().optional().default(false);<br><br>export const joinSchema = z<br>  .object({<br>    email: emailSchema,<br>    password: passwordSchema,<br>    confirmPassword: confirmPasswordSchema,<br>    name: nameSchema,<br>    nickname: nicknameSchema,<br>    phoneNumber: phoneNumberSchema,<br>    isAgreed: isAgreedSchema,<br>    isPrivacyAgreed: isPrivacyAgreedSchema,<br>    isThirdAgreed: isThirdAgreedSchema,<br>    isMarketingAgreed: isMarketingAgreedSchema,<br>  })<br>  .refine(data =&gt; data.confirmPassword === data.password, {<br>    path: [&#39;confirmPassword&#39;],<br>    message: &#39;비밀번호가 일치하지 않습니다.&#39;,<br>  });<br><br>export type JoinPayload = z.infer&lt;typeof joinSchema&gt;;<br><br>export const joinDefaultValues = getDefaults(joinSchema.innerType());</pre><p>비밀번호 확인을 위한 confirmPassword는 refine메소드를 통해 검증하도록 구현했다.</p><p>refine 메소드로 인해 joinSchema의 타입이 ZodObject가 아닌 ZodEffects가 되었다.. 그래서 getDefaults함수의 인자로 넣었을 때 타입에러가 발생했다.</p><p>따라서innertype() 메소드를 통해 ZodObject를 전달하도록 구현했다.</p><h3>Info</h3><p>이메일, 비밀번호, 비밀번호 확인에 대한 validation을 진행하는 스텝</p><p>GenericForm으로 감싸진 Funnel의 스텝이므로 react-hook-form을 사용한 validation을 진행한다.</p><p>외부 컴포넌트에서 hook form을 사용하므로 Controller로 구현된 FormField를 사용해야 한다.</p><h4>RHFInput</h4><pre>&#39;use client&#39;;<br><br>import {<br>  FormControl,<br>  FormDescription,<br>  FormField,<br>  FormItem,<br>  FormLabel,<br>  FormMessage,<br>} from &#39;./core/Form&#39;;<br>import type {HTMLInputTypeAttribute} from &#39;react&#39;;<br>import {useFormContext} from &#39;react-hook-form&#39;;<br>import {Input} from &#39;@wraffle/ui&#39;;<br><br>export interface RHFInputProps {<br>  name: string;<br>  label: string;<br>  placeholder?: string;<br>  description?: string;<br>  type?: HTMLInputTypeAttribute;<br>}<br><br>const RHFInput = ({<br>  name,<br>  label,<br>  placeholder,<br>  description,<br>  type,<br>}: RHFInputProps) =&gt; {<br>  const {control} = useFormContext();<br><br>  return (<br>    &lt;FormField<br>      control={control}<br>      name={name}<br>      render={({field}) =&gt; (<br>        &lt;FormItem&gt;<br>          &lt;div className=&#39;mb-2&#39;&gt;<br>            &lt;FormLabel className=&#39;text-[#333D4B]&#39;&gt;{label}&lt;/FormLabel&gt;<br>          &lt;/div&gt;<br>          &lt;FormControl&gt;<br>            &lt;Input<br>              placeholder={placeholder}<br>              {...field}<br>              type={type}<br>              autoComplete=&#39;off&#39;<br>            /&gt;<br>          &lt;/FormControl&gt;<br>          {description &amp;&amp; &lt;FormDescription&gt;{description}&lt;/FormDescription&gt;}<br>          &lt;FormMessage className=&#39;mt-1 min-h-6&#39; /&gt;<br>        &lt;/FormItem&gt;<br>      )}<br>    /&gt;<br>  );<br>};<br><br>export {RHFInput};</pre><p>RHFInput은 React Hook Form의 Controller로 구현된 FormField 컴포넌트로 구현된 React Hook Form 전용 Input 컴포넌트다.</p><p>해당 컴포넌트를 사용하여 Info 컴포넌트를 구현한다.</p><pre>import type {JoinPayload} from &#39;../config&#39;;<br>import {useEffect} from &#39;react&#39;;<br>import {useFormContext} from &#39;react-hook-form&#39;;<br>import {ValidateEmailInput} from &#39;@/features/validate-duplication/ui&#39;;<br>import {RHFInput} from &#39;@/shared/ui&#39;;<br>import {Button, Typography} from &#39;@wraffle/ui&#39;;<br><br>interface InfoProps {<br>  onNext(email: string, password: string): void;<br>}<br><br>const Info = ({onNext}: InfoProps) =&gt; {<br>  const {<br>    formState: {errors, touchedFields},<br>    getValues,<br>    trigger,<br>  } = useFormContext&lt;JoinPayload&gt;();<br><br>  const email = getValues(&#39;email&#39;);<br>  const password = getValues(&#39;password&#39;);<br>  const confirmPassword = getValues(&#39;confirmPassword&#39;);<br><br>  const isDisabled = () =&gt; {<br>    return (<br>      !email ||<br>      !password ||<br>      !confirmPassword ||<br>      !!errors.email ||<br>      !!errors.password ||<br>      !!errors.confirmPassword<br>    );<br>  };<br><br>  useEffect(() =&gt; {<br>    if (touchedFields.password) {<br>      trigger(&#39;confirmPassword&#39;);<br>    }<br>  }, [password, touchedFields.password, trigger]);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;div className=&#39;mb-5&#39;&gt;<br>        &lt;Typography as=&#39;p&#39; size=&#39;h2&#39;&gt;<br>          회원 가입을 진행할게요!<br>        &lt;/Typography&gt;<br>        &lt;Typography as=&#39;p&#39; size=&#39;p3&#39; color=&#39;zinc400&#39;&gt;<br>          기본 정보를 입력해주세요.<br>        &lt;/Typography&gt;<br>      &lt;/div&gt;<br><br>      &lt;ValidateEmailInput /&gt;<br>      &lt;RHFInput<br>        type=&#39;password&#39;<br>        name=&#39;password&#39;<br>        label=&#39;비밀번호*&#39;<br>        placeholder=&#39;비밀번호를 입력해주세요.&#39;<br>      /&gt;<br>      &lt;RHFInput<br>        type=&#39;password&#39;<br>        name=&#39;confirmPassword&#39;<br>        label=&#39;비밀번호 확인*&#39;<br>        placeholder=&#39;비밀번호를 입력해주세요.&#39;<br>      /&gt;<br><br>      &lt;div className=&#39;fixed inset-x-0 bottom-0 bg-white p-5&#39;&gt;<br>        &lt;Button<br>          type=&#39;button&#39;<br>          onClick={() =&gt; onNext(email, password)}<br>          disabled={isDisabled()}<br>        &gt;<br>          다음<br>        &lt;/Button&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export {Info};</pre><pre>useEffect(() =&gt; {<br>  if (touchedFields.password) {<br>    trigger(&#39;confirmPassword&#39;);<br>  }<br>}, [password]);</pre><p>비밀번호와 비밀번호 확인 필드를 입력 후 다시 비밀번호를 변경했을 때 비밀번호 확인의 validation이 재적용되지 않는다.</p><p>formState의 touchedFields를 사용하여 password가 변경되었을 때 confirmPassword의 validation이 trigger 되도록 구현했다.</p><p>Button 컴포넌트의 기본 type 속성 값이 submit이어서 다음 스텝으로 넘어갈 때 자동으로 validationd이 되었다.<br>type을 button을 명시적으로 선언해준다.</p><h3>이메일 중복 검사 API 연동하기</h3><p>이메일/닉네임은 zod를 통해서 유효성 검사를 진행하고 있다. zod의 유효성검사가 통과되면 중복 검사 API를 통해 최종적으로 유효성 검증을 확인해야 한다.</p><p>Wraffle 회원가입 UI에는 중복 검사 버튼이 없어서 사용자가 Input 값을 입력하면 API를 통해 검증을 진행해야한다. debounce를 적용하여 무분별한 API 호출을 방지할 수 있다.</p><h4>요구사항</h4><ul><li>zod 유효성 검사가 통과되면 중복 검사 API를 통해 최종적으로 유효성을 검증한다.<br>- zod의 유효성 검사가 통과되더라도 중복 검사가 통과되지 않으면 다음 단계로 넘어갈 수 없어야 한다.</li><li>Input에 debounce를 적용하여 무분별한 API 호출을 방지한다.</li></ul><pre>import {useEffect, useState} from &#39;react&#39;;<br><br>const useDebounce = &lt;T&gt;(value: T, delay = 300) =&gt; {<br>  const [debouncedValue, setDebouncedValue] = useState(value);<br>  useEffect(() =&gt; {<br>    const timerId = setTimeout(() =&gt; {<br>      setDebouncedValue(value);<br>    }, delay);<br>    return () =&gt; {<br>      clearTimeout(timerId);<br>    };<br>  }, [value, delay]);<br>  return debouncedValue;<br>};<br>export {useDebounce};</pre><p>debounce를 적용할 수 있는 커스텀훅을 구현한다.</p><pre>// features/validate-duplication/api/validate.ts<br><br>import apiClient from &#39;@/shared/api/apiClient&#39;;<br>import {useMutation} from &#39;@tanstack/react-query&#39;;<br><br>type ValidateRequest =<br>  | {email: string; nickname?: string}<br>  | {email?: string; nickname: string};<br><br>export const useValidateDuplication = () =&gt; {<br>  const mutation = useMutation({<br>    mutationFn: async (query: ValidateRequest) =&gt; {<br>      await apiClient.post&lt;null, ValidateRequest&gt;(&#39;/auth/valid-duplicate&#39;, {<br>        body: query,<br>      });<br>    },<br>  });<br><br>  return {<br>    validateDuplication: mutation.mutate,<br>  };<br>};</pre><pre>// features/validate-duplication/ui/ValidateEmailInput.tsx<br><br>import {useValidateDuplication} from &#39;../api/validate&#39;;<br>import {useCallback, useEffect} from &#39;react&#39;;<br>import {useFormContext} from &#39;react-hook-form&#39;;<br>import {emailSchema} from &#39;@/entities/auth&#39;;<br>import {useDebounce} from &#39;@/shared/hook&#39;;<br>import {RHFInput} from &#39;@/shared/ui&#39;;<br>import type {JoinPayload} from &#39;@/widgets/join/config&#39;;<br><br>const ValidateEmailInput = () =&gt; {<br>  const {watch, setError, clearErrors, trigger} = useFormContext&lt;JoinPayload&gt;();<br><br>  const email = watch(&#39;email&#39;);<br>  const debouncedEmail = useDebounce(email);<br><br>  const {validateDuplication: validateEmailApi} = useValidateDuplication();<br><br>  const validateEmailSchema = useCallback(async () =&gt; {<br>    const isValid = await trigger(&#39;email&#39;);<br>    if (isValid) {<br>      setError(&#39;email&#39;, {<br>        type: &#39;validate&#39;,<br>        message: &#39;이메일 중복 검사가 진행 중입니다.&#39;,<br>      });<br>    }<br>  }, [setError, trigger]);<br><br>  const validateEmailDuplication = useCallback(async () =&gt; {<br>    const isValidSchema = await emailSchema.safeParseAsync(debouncedEmail);<br>    if (isValidSchema.success) {<br>      validateEmailApi(<br>        {email: debouncedEmail},<br>        {<br>          onSuccess: () =&gt; {<br>            clearErrors(&#39;email&#39;);<br>          },<br>          onError: (error: Error) =&gt; {<br>            setError(&#39;email&#39;, {message: error.message});<br>          },<br>        },<br>      );<br>    }<br>  }, [clearErrors, debouncedEmail, setError, validateEmailApi]);<br><br>  useEffect(() =&gt; {<br>    if (!email) return;<br>    validateEmailSchema();<br>  }, [email, validateEmailSchema]);<br><br>  useEffect(() =&gt; {<br>    validateEmailDuplication();<br>  }, [validateEmailDuplication]);<br><br>  return (<br>    &lt;RHFInput<br>      name=&#39;email&#39;<br>      label=&#39;이메일*&#39;<br>      placeholder=&#39;이메일을 입력해주세요.&#39;<br>    /&gt;<br>  );<br>};<br><br>export {ValidateEmailInput};</pre><ol><li>Email Input이 입력되면 validateEmailSchema 함수가 실행된다. validateEmailSchema에서는 trigger로 email의 유효성 검사를 실행하고, 유효성 검사가 통과되었다면 이메일 중복 검사 API를 실행해야 하기 때문에 setError를 사용해서 다시 에러 처리를 한다.</li><li>email값이 change될 때 마다 debouncedEmail 값도 업데이트된다. debouncedEmail이 업데이트되면 validateEmailDuplication 함수가 실행된다. validateEmailDuplication에서는 email zod 스키마의 유효성을 safeParseAsync 검사한다.<br>(trigger로 검사하지 않는 이유는 validateEmailSchema에서 setError로 validation을 통과시키지 않기 때문에 순수 schema의 유효성 검사를 통과하는지만 체크하기 위해서다.)</li></ol><h4>불필요한 useEffect의 사용? 리팩토링하기</h4><p>팀원으로부터 해당 방법이 email과 debouncedEmail이 useEffect에 의존하여 실행되고 있고, 두 사이드 이펙트가 서로 의존되고 있는 점에 대해서 리뷰해주셨다.</p><p>zod 스키마 검증, react-hook-form의 유효성 상태 관리, debounce 등 여러가지 요소가 엮이다 보니 로직이 덕지덕지 붙어있는 듯한 느낌이 드는 것 같다.</p><p>중복 검사 API는 POST 메소드기 때문에 현재 useMutation을 사용하고 있다.<br>몰랐었는데, POST 메소드도 useQuery를 사용할 수 있다고 한다. 👀</p><p>useMutation에는 enabed속성이 없기 때문에 현재 로직을 useQuery로 변경하여 개선할 수 있다.</p><h4>useQuery의 enabled 속성을 사용하여 개선하기</h4><ol><li>useQuery의 enabled조건을 Email Schema의 validation 여부로 지정</li><li>API Query에 debouncedEmail을 전달</li><li>다음 버튼 활성화 조건을 Email Schema의 validation &amp;&amp; API 중복 체크 통과 여부로 설정</li></ol><p>Tanstack Query v5부터는 useQuery에 onSuccess와 onError 콜백이 없다.</p><p>현재 로직을 뜯어내고 리팩토링을 진행해야 하는데 밀린 태스크가 많아서 우선 현재 작성한 코드로 적용하고 리팩토링은 백로그에 남겨두기로 했다.</p><p>닉네임 중복검사도 같은 방법이므로 아래에서 설명은 패스하겠다.</p><h3>Name</h3><p>이름과 닉네임에 대한 validation을 진행하는 스텝.<br>Info와 크게 다를건 없다.</p><pre>import type {JoinPayload} from &#39;../config&#39;;<br>import {useFormContext} from &#39;react-hook-form&#39;;<br>import {ValidateNicknameInput} from &#39;@/features/validate-duplication/ui&#39;;<br>import {RHFInput} from &#39;@/shared/ui&#39;;<br>import {Button, Typography} from &#39;@wraffle/ui&#39;;<br><br>interface NameProps {<br>  onNext(name: string, nickname: string): void;<br>}<br><br>const Name = ({onNext}: NameProps) =&gt; {<br>  const {<br>    getValues,<br>    formState: {errors},<br>  } = useFormContext&lt;JoinPayload&gt;();<br><br>  const name = getValues(&#39;name&#39;);<br>  const nickname = getValues(&#39;nickname&#39;);<br><br>  const isDisabled = () =&gt; {<br>    return !name || !nickname || !!errors.name || !!errors.nickname;<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;div className=&#39;mb-5&#39;&gt;<br>        &lt;Typography as=&#39;p&#39; size=&#39;h2&#39;&gt;<br>          쓰고 싶은 닉네임이 있나요?<br>        &lt;/Typography&gt;<br>        &lt;Typography as=&#39;p&#39; size=&#39;p3&#39; color=&#39;zinc400&#39;&gt;<br>          이름과 닉네임을 알려주세요!<br>        &lt;/Typography&gt;<br>      &lt;/div&gt;<br><br>      &lt;RHFInput name=&#39;name&#39; label=&#39;이름*&#39; placeholder=&#39;이름을 입력해주세요.&#39; /&gt;<br>      &lt;ValidateNicknameInput /&gt;<br><br>      &lt;div className=&#39;fixed inset-x-0 bottom-0 bg-white p-5&#39;&gt;<br>        &lt;Button<br>          type=&#39;button&#39;<br>          onClick={() =&gt; onNext(name, nickname)}<br>          disabled={isDisabled()}<br>        &gt;<br>          다음<br>        &lt;/Button&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export {Name};</pre><h3>Phone</h3><p>휴대폰 번호를 입력하고 해당 번호로 전송된 인증코드를 검증하는 스텝.<br>Phone 스텝에서도 휴대폰 번호 입력 스텝과 인증코드 입력 스텝으로 나뉜다.</p><p>따라서 회원가입 Funnel 안에서 전화번호 인증 스텝 Sub Funnel을 사용했다.</p><pre>import Code from &#39;./Code&#39;;<br>import PhoneNumber from &#39;./PhoneNumber&#39;;<br>import {useFunnel} from &#39;@use-funnel/browser&#39;;<br><br>interface PhoneProps {<br>  onNext(phoneNumber: string): void;<br>}<br><br>const PhoneFunnel = ({onNext}: PhoneProps) =&gt; {<br>  const funnel = useFunnel&lt;{<br>    PhoneNumber: {phoneNumber?: string; code?: string};<br>    Code: {phoneNumber: string; code?: string};<br>  }&gt;({<br>    id: &#39;phone&#39;,<br>    initial: {<br>      step: &#39;PhoneNumber&#39;,<br>      context: {},<br>    },<br>  });<br><br>  return (<br>    &lt;funnel.Render<br>      PhoneNumber={({history}) =&gt; (<br>        &lt;PhoneNumber<br>          onNext={phoneNumber =&gt; history.push(&#39;Code&#39;, {phoneNumber})}<br>        /&gt;<br>      )}<br>      Code={({context}) =&gt; &lt;Code onNext={() =&gt; onNext(context.phoneNumber)} /&gt;}<br>    /&gt;<br>  );<br>};<br><br>export {PhoneFunnel};</pre><h3>PhoneNumber</h3><p>3개의 Input으로 나뉘어져 휴대폰 번호를 입력받는다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*J7EPvzdX_F1LICfY7xP_Hg.png" /></figure><p>각 Input의 값을 first, middle, last라는 state로 선언하여 각 Input의 값이 모두 입력되었을 때 setValue를 통해 phoneNumber를 업데이트 하는 방향으로 구현했다.</p><p>또한 Input에서 maxLength만큼 입력되었을 때 자동으로 다음 Input으로 focus되는 기능도 구현 필요했다.</p><p>요구사항</p><ul><li>3개의 분리된 Input이 모두 입력되었을 때 phoneNumber로 setValue</li><li>Input의 MaxLength만큼 입력되었을 때 자동으로 다음 Input의 포커스로 넘어가는 AutoFocus 기능</li></ul><pre>// widgets/join/ui/Phone/PhoneNumber.tsx<br><br>import type {JoinPayload} from &#39;../../config&#39;;<br>import {useCallback, useState} from &#39;react&#39;;<br>import {useFormContext} from &#39;react-hook-form&#39;;<br>import {RequestCode} from &#39;@/features/validate-phone/ui/RequestCode&#39;;<br>import {Button, Typography} from &#39;@wraffle/ui&#39;;<br><br>interface PhoneNumberProps {<br>  onNext(phoneNumber: string): void;<br>}<br><br>const PhoneNumber = ({onNext}: PhoneNumberProps) =&gt; {<br>  const {<br>    formState: {errors},<br>    setValue,<br>    getValues,<br>  } = useFormContext&lt;JoinPayload&gt;();<br><br>  const [isVerified, handleIsVerified] = useState(false);<br><br>  const handlePhoneNumber = useCallback(<br>    (phone: string) =&gt; {<br>      setValue(&#39;phoneNumber&#39;, phone, {shouldValidate: true});<br>    },<br>    [setValue],<br>  );<br><br>  return (<br>    &lt;div&gt;<br>      &lt;div className=&#39;mb-12&#39;&gt;<br>        &lt;Typography as=&#39;p&#39; size=&#39;h2&#39;&gt;<br>          휴대폰 인증을 진행할게요!<br>        &lt;/Typography&gt;<br>        &lt;Typography as=&#39;p&#39; size=&#39;p3&#39; color=&#39;zinc400&#39;&gt;<br>          휴대폰 정보를 입력해주세요.<br>        &lt;/Typography&gt;<br>      &lt;/div&gt;<br><br>      &lt;RequestCode<br>        onChangePhoneNumber={handlePhoneNumber}<br>        onChangeIsVerified={handleIsVerified}<br>        error={errors.phoneNumber}<br>      /&gt;<br><br>      &lt;div className=&#39;fixed inset-x-0 bottom-0 bg-white p-5&#39;&gt;<br>        &lt;Button<br>          type=&#39;button&#39;<br>          onClick={() =&gt; onNext(getValues(&#39;phoneNumber&#39;))}<br>          disabled={!isVerified || !!errors.phoneNumber}<br>        &gt;<br>          다음<br>        &lt;/Button&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default PhoneNumber;</pre><pre>// features/validate-phone/ui/RequestCode.tsx<br><br>import {useRequestCode} from &#39;../api/request&#39;;<br>import type {RequestCodeRequest} from &#39;../config/type&#39;;<br>import type {Dispatch, SetStateAction} from &#39;react&#39;;<br>import {useCallback, useEffect, useState} from &#39;react&#39;;<br>import type {FieldError} from &#39;react-hook-form&#39;;<br>import {useAutoFocus, useInput} from &#39;@/shared/hook&#39;;<br>import {handleMaxLength} from &#39;@/shared/util&#39;;<br>import {InputField, Select} from &#39;@wraffle/ui&#39;;<br><br>const MAX_INPUT_LENGTH = 4;<br><br>interface RequestCodeProps {<br>  onChangePhoneNumber: (phone: string) =&gt; void;<br>  onChangeIsVerified: Dispatch&lt;SetStateAction&lt;boolean&gt;&gt;;<br>  error?: FieldError;<br>}<br><br>const RequestCode = ({<br>  onChangePhoneNumber,<br>  onChangeIsVerified,<br>  error,<br>}: RequestCodeProps) =&gt; {<br>  const [middleInputRef, handleMiddleKeyUp] = useAutoFocus(MAX_INPUT_LENGTH);<br>  const [lastInputRef, handleLastKeyUp] = useAutoFocus(MAX_INPUT_LENGTH);<br><br>  const [first, setFirst] = useState(&#39;&#39;);<br>  const [middle, handleMiddle] = useInput(&#39;&#39;);<br>  const [last, handleLast] = useInput(&#39;&#39;);<br>  const [errorMessage, setErrorMessage] = useState(&#39;&#39;);<br><br>  const {requestCode} = useRequestCode();<br><br>  const handleRequestCode = useCallback(<br>    ({phoneNumber}: RequestCodeRequest) =&gt; {<br>      requestCode(<br>        {phoneNumber},<br>        {<br>          onSuccess: () =&gt; {<br>            onChangeIsVerified(true);<br>          },<br>          onError: (error: Error) =&gt; {<br>            setErrorMessage(error.message);<br>            onChangeIsVerified(false);<br>          },<br>        },<br>      );<br>    },<br>    [onChangeIsVerified, requestCode],<br>  );<br><br>  const isValid =<br>    first &amp;&amp;<br>    (middle.length === MAX_INPUT_LENGTH ||<br>      middle.length === MAX_INPUT_LENGTH - 1) &amp;&amp;<br>    last.length === MAX_INPUT_LENGTH;<br><br>  useEffect(() =&gt; {<br>    onChangeIsVerified(false);<br>    setErrorMessage(&#39;&#39;);<br>    if (isValid) {<br>      const phoneNumber = first.concat(middle, last);<br>      onChangePhoneNumber(phoneNumber);<br>      handleRequestCode({phoneNumber});<br>    }<br>  }, [<br>    first,<br>    handleRequestCode,<br>    isValid,<br>    last,<br>    middle,<br>    onChangeIsVerified,<br>    onChangePhoneNumber,<br>  ]);<br><br>  return (<br>    &lt;InputField&gt;<br>      &lt;InputField.Label htmlFor=&#39;phone&#39;&gt;휴대폰 번호*&lt;/InputField.Label&gt;<br>      &lt;Select<br>        onValueChange={value =&gt; setFirst(value)}<br>        placeholder=&#39;선택&#39;<br>        items={[<br>          {value: &#39;010&#39;, name: &#39;010&#39;},<br>          {value: &#39;02&#39;, name: &#39;02&#39;},<br>          {value: &#39;031&#39;, name: &#39;031&#39;},<br>          {value: &#39;032&#39;, name: &#39;032&#39;},<br>        ]}<br>      /&gt;<br>      &lt;InputField.Input<br>        ref={middleInputRef}<br>        id=&#39;middle&#39;<br>        placeholder=&#39;&#39;<br>        type=&#39;number&#39;<br>        maxLength={MAX_INPUT_LENGTH}<br>        value={middle}<br>        onChange={handleMiddle}<br>        onInput={handleMaxLength}<br>        onKeyUp={e =&gt; handleMiddleKeyUp(e, lastInputRef)}<br>      /&gt;<br>      &lt;InputField.Input<br>        ref={lastInputRef}<br>        id=&#39;last&#39;<br>        placeholder=&#39;&#39;<br>        type=&#39;number&#39;<br>        maxLength={MAX_INPUT_LENGTH}<br>        value={last}<br>        onChange={handleLast}<br>        onInput={handleMaxLength}<br>        onKeyUp={e =&gt; handleLastKeyUp(e, null)}<br>      /&gt;<br>      &lt;InputField.ErrorMessage isError&gt;<br>        {error &amp;&amp; error.message}<br>        {!error &amp;&amp; errorMessage}<br>      &lt;/InputField.ErrorMessage&gt;<br>    &lt;/InputField&gt;<br>  );<br>};<br><br>export {RequestCode};</pre><p>각 Input은 React Hook Form을 사용하여 validation을 진행하지 않으므로 합성 컴포넌트 방식으로 구현된 InputField를 사용했다.</p><p>🚨 type이 number인 input에 대해서는 maxLength가 계산되지 않는다.<br>→ onInput 함수에 handleMaxLength 유틸 함수를 적용.</p><pre>export const handleMaxLength = (e: React.FormEvent&lt;HTMLInputElement&gt;) =&gt; {<br>  const inputElement = e.currentTarget;<br>  const {value, maxLength} = inputElement;<br>  if (value.length &gt; maxLength) {<br>    inputElement.value = value.slice(0, maxLength);<br>  }<br>};</pre><p>해당 Input의 MaxLength 만큼 값을 slice해서 value가 최대 길이를 넘지 않도록 구현했다.</p><pre>const {requestCode} = useRequestCode();<br><br>  const handleRequestCode = useCallback(<br>    ({phoneNumber}: RequestCodeRequest) =&gt; {<br>      requestCode(<br>        {phoneNumber},<br>        {<br>          onSuccess: () =&gt; {<br>            onChangeIsVerified(true);<br>          },<br>          onError: (error: Error) =&gt; {<br>            setErrorMessage(error.message);<br>            onChangeIsVerified(false);<br>          },<br>        },<br>      );<br>    },<br>    [onChangeIsVerified, requestCode],<br>  );<br> ...<br> <br>  useEffect(() =&gt; {<br>    onChangeIsVerified(false);<br>    setErrorMessage(&#39;&#39;);<br>    if (isValid) {<br>      const phoneNumber = first.concat(middle, last);<br>      onChangePhoneNumber(phoneNumber);<br>      handleRequestCode({phoneNumber});<br>    }<br>  }, [<br>    first,<br>    handleRequestCode,<br>    isValid,<br>    last,<br>    middle,<br>    onChangeIsVerified,<br>    onChangePhoneNumber,<br>  ]);</pre><p>first, middle, last 값이 조건을 충족했을 때 setValue를 통해 phoneNumber 값을 업데이트하고 인증번호 검증 API를 수행한다.<br>setValue에 {shouldValidate: true}옵션을 주었기 때문에 value가 업데이트 되면서 다시 Validation을 진행한다.</p><p>필드의 유효성 검증이 통과되면 handleRequestCode를 통해 인증코드 발송 API를 mutation한다. mutation API 결과에 따라 최종적으로 유효성 검사 여부를 판별한다.</p><pre>const [middleInputRef, handleMiddleKeyUp] = useAutoFocus(MAX_INPUT_LENGTH);<br>const [lastInputRef, handleLastKeyUp] = useAutoFocus(MAX_INPUT_LENGTH);</pre><p>Input의 MaxLength만큼 입력되었을 때 다음 Input으로 AutoFocus를 하는 커스텀훅을 구현했다.</p><pre>import {useRef} from &#39;react&#39;;<br><br>const useAutoFocus = (<br>  maxLength: number,<br>): [<br>  React.RefObject&lt;HTMLInputElement&gt;,<br>  (<br>    event: React.KeyboardEvent&lt;HTMLInputElement&gt;,<br>    nextRef: React.RefObject&lt;HTMLInputElement&gt; | null,<br>  ) =&gt; void,<br>] =&gt; {<br>  const ref = useRef&lt;HTMLInputElement&gt;(null);<br><br>  const handleKeyUp = (<br>    event: React.KeyboardEvent&lt;HTMLInputElement&gt;,<br>    nextRef: React.RefObject&lt;HTMLInputElement&gt; | null,<br>  ) =&gt; {<br>    if (event.currentTarget.value.length &gt;= maxLength) {<br>      nextRef?.current?.focus();<br>    }<br>  };<br><br>  return [ref, handleKeyUp];<br>};<br><br>export default useAutoFocus;</pre><pre>&lt;InputField.Input<br>  ref={middleInputRef}<br>  id=&#39;middle&#39;<br>  placeholder=&#39;&#39;<br>  type=&#39;number&#39;<br>  maxLength={MAX_INPUT_LENGTH}<br>  value={middle}<br>  onChange={handleMiddle}<br>  onInput={handleMaxLength}<br>  onKeyUp={e =&gt; handleMiddleKeyUp(e, lastInputRef)}<br>/&gt;<br>&lt;InputField.Input<br>  ref={lastInputRef}<br>  id=&#39;last&#39;<br>  placeholder=&#39;&#39;<br>  type=&#39;number&#39;<br>  maxLength={MAX_INPUT_LENGTH}<br>  value={last}<br>  onChange={handleLast}<br>  onInput={handleMaxLength}<br>  onKeyUp={e =&gt; handleLastKeyUp(e, null)}<br>/&gt;</pre><p>각 Input에 useAutoFocus의 ref와 onKeyUp 이벤트 핸들러를 적용했다.</p><h3>Code</h3><p>인증코드를 입력하는 필드.</p><p>다음 버튼이 없고 인증이 성공하면 다음 스텝으로 넘어가도록 구현한다.</p><p>현재는 API 연동을 하지 않았으므로 4자리를 입력받으면 다음 스텝으로 넘어가도록 구현했다.</p><pre>import type {JoinPayload} from &#39;../../config&#39;;<br>import {useFormContext} from &#39;react-hook-form&#39;;<br>import {VerifyCode} from &#39;@/features/validate-phone/ui/VerifyCode&#39;;<br>import {Timer} from &#39;@/shared/ui&#39;;<br>import {Typography} from &#39;@wraffle/ui&#39;;<br><br>interface CodeProps {<br>  onNext(code: string): void;<br>}<br><br>const Code = ({onNext}: CodeProps) =&gt; {<br>  const {getValues} = useFormContext&lt;JoinPayload&gt;();<br><br>  const handleVerify = () =&gt; {<br>    onNext(getValues(&#39;phoneNumber&#39;));<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;div className=&#39;mb-12&#39;&gt;<br>        &lt;Typography as=&#39;p&#39; size=&#39;h2&#39;&gt;<br>          휴대폰 인증을 진행할게요!<br>        &lt;/Typography&gt;<br>        &lt;Typography as=&#39;p&#39; size=&#39;p3&#39; color=&#39;zinc400&#39;&gt;<br>          인증번호를 입력해주세요.<br>        &lt;/Typography&gt;<br>      &lt;/div&gt;<br><br>      &lt;VerifyCode<br>        phoneNumber={getValues(&#39;phoneNumber&#39;)}<br>        onSuccess={handleVerify}<br>      /&gt;<br>      &lt;div className=&#39;flex justify-end pr-2 pt-1&#39;&gt;<br>        &lt;Timer timerSecond={180} /&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default Code;</pre><p>인증코드 유효기간을 3분으로 가정하여 Timer 컴포넌트를 추가했다.</p><p>인증코드 검증 API 연동은 PhoneNumber스텝과 동일하므로 설명은 패스.</p><h3>Extra</h3><p>약관을 처리하는 스텝.<br>모두 동의 필드가 있고 필수와 선택으로 validation을 진행해야 한다.</p><pre>import type {JoinPayload} from &#39;../config&#39;;<br>import {terms} from &#39;../config&#39;;<br>import {useFormContext} from &#39;react-hook-form&#39;;<br>import {FormControl, FormField, FormItem} from &#39;@/shared/ui&#39;;<br>import {Button, ErrorMessage, Icon, Typography, CheckBox} from &#39;@wraffle/ui&#39;;<br><br>const Extra = () =&gt; {<br>  const {control, setValue, watch, clearErrors} = useFormContext&lt;JoinPayload&gt;();<br>  const watchAllFields = watch();<br><br>  const allChecked = terms.every(term =&gt; watchAllFields[term.id]);<br><br>  const isAgreed = watch(&#39;isAgreed&#39;);<br>  const isPrivacyAgreed = watch(&#39;isPrivacyAgreed&#39;);<br>  const isThirdAgreed = watch(&#39;isThirdAgreed&#39;);<br><br>  const allAgreed = isAgreed &amp;&amp; isPrivacyAgreed &amp;&amp; isThirdAgreed;<br><br>  const handleAllCheckChange = (isChecked: boolean) =&gt; {<br>    terms.forEach(term =&gt; {<br>      setValue(term.id, isChecked, {shouldValidate: true});<br>      if (isChecked) {<br>        clearErrors(term.id);<br>      }<br>    });<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;div className=&#39;mb-5&#39;&gt;<br>        &lt;Typography as=&#39;p&#39; size=&#39;h2&#39;&gt;<br>          약관 동의<br>        &lt;/Typography&gt;<br>        &lt;Typography as=&#39;p&#39; size=&#39;p3&#39; color=&#39;zinc400&#39;&gt;<br>          약관 동의<br>        &lt;/Typography&gt;<br>      &lt;/div&gt;<br><br>      &lt;FormField<br>        name=&#39;isAllAgreed&#39;<br>        render={() =&gt; (<br>          &lt;FormItem className=&#39;flex flex-col gap-6&#39;&gt;<br>            &lt;CheckBox<br>              className=&#39;text-[15px] font-bold&#39;<br>              id=&#39;allAgreed&#39;<br>              label=&#39;전체 동의&#39;<br>              checked={allChecked}<br>              onCheckedChange={checked =&gt; handleAllCheckChange(checked)}<br>            /&gt;<br>            {terms.map(term =&gt; (<br>              &lt;FormField<br>                key={term.id}<br>                control={control}<br>                name={term.id}<br>                render={({field, fieldState}) =&gt; {<br>                  return (<br>                    &lt;FormItem<br>                      key={term.id}<br>                      className=&#39;flex h-6 flex-col items-start&#39;<br>                    &gt;<br>                      &lt;span className=&#39;flex w-full justify-between&#39;&gt;<br>                        &lt;FormControl&gt;<br>                          &lt;CheckBox<br>                            className=&#39;text-[15px] font-medium text-[#333D4B]&#39;<br>                            id={term.id}<br>                            label={term.label}<br>                            checked={field.value || false}<br>                            onCheckedChange={checked =&gt; {<br>                              field.onChange(checked);<br>                              if (checked) {<br>                                clearErrors(term.id);<br>                              }<br>                            }}<br>                          /&gt;<br>                        &lt;/FormControl&gt;<br>                        &lt;Icon name=&#39;arrow-right&#39; color=&#39;#ADB5BD&#39; /&gt;<br>                      &lt;/span&gt;<br>                      {fieldState.error &amp;&amp; (<br>                        &lt;ErrorMessage isError className=&#39;ml-6&#39;&gt;<br>                          {fieldState.error.message}<br>                        &lt;/ErrorMessage&gt;<br>                      )}<br>                    &lt;/FormItem&gt;<br>                  );<br>                }}<br>              /&gt;<br>            ))}<br>          &lt;/FormItem&gt;<br>        )}<br>      /&gt;<br><br>      &lt;div className=&#39;fixed inset-x-0 bottom-0 bg-white p-5&#39;&gt;<br>        &lt;Button disabled={!allAgreed}&gt;회원가입&lt;/Button&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export {Extra};</pre><p>CheckBox 컴포넌트는 RHFInput 같은 react-hook-form을 위한 컴포넌트가 없으므로 FormField를 직접 선언해서 구현해야 한다.</p><p>“전체 동의” 버튼을 누르면 모든 약관의 값이 true가 되거나 false가 되어야 한다. 이와 동시에 validation도 진행되어야 한다.</p><pre>const watchAllFields = watch();<br><br>const allChecked = terms.every(term =&gt; watchAllFields[term.id]);<br><br>const isAgreed = watch(&#39;isAgreed&#39;);<br>const isPrivacyAgreed = watch(&#39;isPrivacyAgreed&#39;);<br>const isThirdAgreed = watch(&#39;isThirdAgreed&#39;);<br><br>const allAgreed = isAgreed &amp;&amp; isPrivacyAgreed &amp;&amp; isThirdAgreed;</pre><p>watch를 통해 값을 실시간으로 받아온다.</p><pre>const handleAllCheckChange = (isChecked: boolean) =&gt; {<br>  terms.forEach(term =&gt; {<br>    setValue(term.id, isChecked, {shouldValidate: true});<br>    if (isChecked) {<br>      clearErrors(term.id);<br>    }<br>  });<br>};</pre><p>전체 동의 버튼을 누르면 실행할 함수.<br>조건이 만족되면 clearErrors를 통해 해당 약관의 에러를 제거한다.</p><pre>&lt;FormControl&gt;<br>  &lt;CheckBox<br>    className=&#39;text-[15px] font-medium text-[#333D4B]&#39;<br>    id={term.id}<br>    label={term.label}<br>    checked={field.value || false}<br>    onCheckedChange={checked =&gt; {<br>      field.onChange(checked);<br>      if (checked) {<br>        clearErrors(term.id);<br>      }<br>    }}<br>  /&gt;<br>&lt;/FormControl&gt;;</pre><p>checked나 onCheckedChange의 값들은 모두 field에서 받아온 값을 사용해야 react-hook-form의 validation이 진행된다.</p><h3>회원가입 서버액션으로 처리하기</h3><p>회원가입 API의 request body에는 사용자의 민감한 정보가 포함되어 있다.</p><p>이런 정보를 숨기고 검증 우회를 방지하기 위해 서버 액션으로 처리하는 것이 좋다.</p><pre>// widgets/join/api/server.ts<br><br>&#39;use server&#39;;<br>import type {JoinRequest} from &#39;../config/type&#39;;<br>import apiClient from &#39;@/shared/api/apiClient&#39;;<br>import type {Tokens} from &#39;@/shared/api/type&#39;;<br>export const signUpUser = async (data: JoinRequest) =&gt; {<br>  await apiClient.post&lt;Tokens, JoinRequest&gt;(&#39;/auth/signup&#39;, {<br>    body: data,<br>  });<br>};</pre><pre>// app/join/page.tsx<br><br>&#39;use client&#39;;<br>import {signUpUser} from &#39;@/widgets/join/api/server&#39;;<br>...<br>const Join = () =&gt; {<br>  const {toast} = useToast();<br>  const router = useRouter();<br>  const onSubmit = (data: z.infer&lt;typeof joinSchema&gt;) =&gt; {<br>    startTransition(async () =&gt; {<br>      try {<br>        const {confirmPassword, ...userJoinData} = data;<br>        void confirmPassword;<br>        await signUpUser(userJoinData);<br>        toast({<br>          title: &#39;회원가입에 성공했습니다.&#39;,<br>          duration: 2000,<br>          variant: &#39;success&#39;,<br>          icon: &#39;check&#39;,<br>        });<br>        router.push(&#39;/login&#39;);<br>      } catch (error) {<br>        toast({<br>          title: (error as Error).message,<br>          duration: 2000,<br>          variant: &#39;warning&#39;,<br>          icon: &#39;close&#39;,<br>        });<br>      }<br>    });<br>  };<br>  ...<br>  return (<br>  ...<br> &lt;GenericForm<br>  onSubmit={onSubmit}<br>  formOptions={{<br>   mode: &#39;onChange&#39;,<br>   resolver: zodResolver(joinSchema),<br>   defaultValues: joinDefaultValues,<br>  }}<br> &gt;<br>        ...<br>  );<br>};<br>export default Join;</pre><p>react-hook-form을 사용하기 때문에 onSubmit 이벤트에 서버액션 함수를 전달하기 위해서 startTransition으로 서버 액션 함수를 래핑하여 사용했다.</p><h3>마치며..</h3><p>Next.js에서 15버전으로 업데이트 하면서 Next 자체적으로 Form을 관리하는 Form컴포넌트가 나올 예정이라고 한다.<br>과연 react-hook-form같은 라이브러리를 대체할 수 있을지는 살펴봐야 할 것 같다.</p><p>새롭게 출시된 Toss의 @use-funnel라이브러리가 빨리 안정화되고 더 많은 레퍼런스가 나왔으면 좋겠다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7daa87bfa108" width="1" height="1" alt=""><hr><p><a href="https://medium.com/wraffle-tech/next-js%EC%97%90%EC%84%9C-zod-react-hook-form-use-funnel%EC%9D%84-%EC%82%AC%EC%9A%A9%ED%95%98%EC%97%AC-%ED%9A%8C%EC%9B%90%EA%B0%80%EC%9E%85-%EC%8A%A4%ED%85%9D-%EA%B5%AC%ED%98%84%ED%95%98%EA%B8%B0-7daa87bfa108">Next.js에서 zod, react-hook-form, @use-funnel을 사용하여 회원가입 스텝 구현하기</a> was originally published in <a href="https://medium.com/wraffle-tech">Wraffle-Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TurbRepo와 pnpm을 사용하여 모노레포 구축하기]]></title>
            <link>https://medium.com/wraffle-tech/turbrepo%EC%99%80-pnpm%EC%9D%84-%EC%82%AC%EC%9A%A9%ED%95%98%EC%97%AC-%EB%AA%A8%EB%85%B8%EB%A0%88%ED%8F%AC-%EA%B5%AC%EC%B6%95%ED%95%98%EA%B8%B0-3f7108557bb0?source=rss-2ace129286a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f7108557bb0</guid>
            <category><![CDATA[pnpm]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[turborepo]]></category>
            <dc:creator><![CDATA[Sangmin Tsx]]></dc:creator>
            <pubDate>Wed, 18 Dec 2024 14:05:07 GMT</pubDate>
            <atom:updated>2024-12-18T14:05:07.036Z</atom:updated>
            <content:encoded><![CDATA[<p>지난 포스트에서는 모노레포를 구축하기 위한 패키지 매니저의 workspace 기능에 대해서 알아보았다.</p><p><a href="https://medium.com/wraffle-tech/yarn-workspace%EC%99%80-pnpm-workspace-c118e8ba3260">Yarn Workspace와 Pnpm Workspace</a></p><p>패키지 매니저의 워크스페이스 기능만을 사용하면 복잡한 의존성 관리에 대한 어려움이 있기 때문에 모노레포 도구를 사용하기로 한다.</p><p>그 중에서도 TurboRepo에 대해서 알아보고 Wraffle 프로젝트도 세팅해보자.</p><blockquote>프로젝트 세팅할 때 당시 기준으로 작성한 내용입니다. 현재는 일부 구조가 수정되거나 삭제되었습니다.</blockquote><h3>Turborepo</h3><p>자바스크립트 및 타입스크립트 코드베이스를 위한 <strong>고성능 빌드 시스템</strong></p><h4>특징</h4><ul><li>Vercel에서 인수한 빌드 시스템 도구</li><li>모노레포에서만 사용하는 것은 아님<br>- 모노레포의 경우 npm, yarn classic, yarn berry, pnpm의 워크스페이스와 함께 사용이 가능하지만 <strong>pnpm을 권장한다.</strong></li><li>모노레포 환경에서도 쉽고 빠르게 개발할 수 있는 빌드 환경을 제공하는 것이 목표</li><li>turbo.json 파일을 이용해 <strong>캐싱</strong>과 <strong>태스크 오케스트레이션</strong>을 설정</li></ul><h4>장점</h4><ul><li>사용자가 빌드한 내용을 기억하고 <strong>이미 계산한 내용은 건너뛴다</strong></li><li>타임스탬프가 아닌 파일 내용을 보고 빌드해야 할 내용을 파악</li><li>모든 코어를 최대로 사용해서 병렬로 실행할 수 있음</li><li><strong>원격 빌드 캐시</strong>를 팀원 및 CI/CD와 공유하여 빌드 속도를 높일 수 있음</li><li>작업 간의 관계를 정의한 다음 Turborepo가 빌드할 항목과 시기를 최적화할 수 있음</li></ul><h4>Turborepo 기능</h4><ul><li>태스크 실행(test) 명령</li></ul><pre>turbo run test</pre><ul><li>특정 워크스페이스(shared) 실행 명령</li></ul><pre>turbo run test --filter=shared</pre><ul><li>의존성이 있을 때 의존 관계에 따라서 태스크 실행 + 병렬실행</li></ul><pre>turbo run lint test build</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TPIoOCxYUMT_imYlRXoxpg.png" /></figure><ul><li>Code Generation</li></ul><pre>turbo gen workspace --name @acme/icons</pre><p>빈 워크스페이스를 생성한다</p><ul><li>Remote Caching</li></ul><pre>turbo login turbo link</pre><p>Vercel에 원격으로 캐시가 저장된다 (CI/CD에서 활용할 수 있기 때문에 빌드 속도 향상 가능)</p><h4>Turborepo 사용하기</h4><pre>pnpm init<br>corepack use pnpm@9.4.0</pre><p>pnpm-workspace.yaml 파일에 워크스페이스를 설정한다</p><pre>packages:<br>  - &quot;packages/*&quot;<br>  - &quot;apps/*&quot;</pre><p>apps 폴더에 Next.js 프로젝트를 생성한다</p><pre>pnpx create-next-app@latest</pre><p>프로젝트 <strong>루트 경로(-w)</strong>에 <strong>DevDependency(-D)</strong>로 turbo를 설치한다</p><pre>pnpm -w add turbo -D</pre><p>code generation 기능을 사용해 빈 워크스페이스를 생성한다</p><pre>pnpm exec turbo gen workspace --name my-utils</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*h-rG3myaa7igQNPLnhhXwA.png" /></figure><p>어떤 타입의 워크스페이스인지 (app/package) 등등 옵션을 선택할 수 있다</p><p>패키지인 packages/my-utils에 있는 소스코드를 Next.js 앱인apps/my-app에서 사용하기</p><pre>pnpm --filter my-utils add typescript -D<br>pnpm --filter my-utils exec tsc --init</pre><p>함수를 하나 만들어준다</p><pre>// packages/my-utils/src/index.ts<br><br>export function plusOne(num: number): number {<br>  return num + 1;<br>}</pre><p>tsconfig 설정에서 해당 옵션을 설정해준다</p><pre>// packages/my-utils/tsconfig.json<br><br>{<br> &quot;complierOptions&quot;: {<br>  ...<br>  &quot;declaration&quot;: true,<br>  &quot;outDir&quot;: &quot;./dist&quot;,<br>  ...<br> },<br> &quot;include&quot;: [&quot;src/**/*&quot;]<br>}</pre><pre>// packages/my-utils/package.json<br><br>{<br>  &quot;name&quot;: &quot;my-utils&quot;,<br>  &quot;version&quot;: &quot;0.0.0&quot;,<br>  // &quot;private&quot;: true, 다른 패키지에서 사용할 것이기 때문에 삭제<br>  &quot;main&quot;: &quot;dist/index.js&quot;, // 실행될 파일<br>  &quot;types&quot;: &quot;dist/index.d.ts&quot; // 타입 파일<br>  &quot;scripts&quot;: {<br>    &quot;build&quot;: &quot;tsc&quot; // 타입스크립트를 사용할 것이기 때문에 tsc로 변경한다<br>  },<br>  &quot;devDependencies&quot;: {<br>    &quot;typescript&quot;: &quot;^5&quot;<br>  }<br>}</pre><pre>pnpm --filter my-utils build</pre><p>my-utils에 dist폴더에 결과물이 생성되었다.</p><p>my-app에서 my-utils에 있는 코드를 사용할 것이기 때문에 my-app의 package.json에서 의존성을 명시해야 한다.</p><pre>// apps/my-app/package.json<br><br>{<br>  &quot;name&quot;: &quot;my-app&quot;,<br>  &quot;version&quot;: &quot;0.1.0&quot;,<br>  &quot;private&quot;: true,<br>  &quot;scripts&quot;: {<br>    &quot;dev&quot;: &quot;next dev&quot;,<br>    &quot;build&quot;: &quot;next build&quot;,<br>    &quot;start&quot;: &quot;next start&quot;,<br>    &quot;lint&quot;: &quot;next lint&quot;<br>  },<br>  &quot;dependencies&quot;: {<br>    &quot;react&quot;: &quot;^18&quot;,<br>    &quot;react-dom&quot;: &quot;^18&quot;,<br>    &quot;next&quot;: &quot;14.2.4&quot;,<br>    **&quot;my-utils&quot;: &quot;workspace:*&quot; // 의존성을 추가한다**<br>  },<br>  &quot;devDependencies&quot;: {<br>    &quot;typescript&quot;: &quot;^5&quot;,<br>    &quot;@types/node&quot;: &quot;^20&quot;,<br>    &quot;@types/react&quot;: &quot;^18&quot;,<br>    &quot;@types/react-dom&quot;: &quot;^18&quot;,<br>    &quot;eslint&quot;: &quot;^8&quot;,<br>    &quot;eslint-config-next&quot;: &quot;14.2.4&quot;<br>  }<br>}</pre><p>my-app에서 my-utils의 plusOne함수를 사용해보자</p><pre>import Image from &quot;next/image&quot;;<br>import styles from &quot;./page.module.css&quot;;<br>**import { plusOne } from &quot;my-utils&quot;;**<br><br>export default function Home() {<br>  return (<br>    &lt;main className={styles.main}&gt;<br>     ...<br>      **&lt;h1&gt;{plusOne(5)}&lt;/h1&gt;**<br>      ...<br>    &lt;/main&gt;<br>  );<br>}</pre><pre>pnpm --filter my-app dev</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_kKFBsrWvkR0lOjBCiJXdA.png" /></figure><p>함수가 잘 실행되는 것을 확인할 수 있다.</p><h4>Turbo를 사용해서 실행해보자</h4><h4>단일 워크스페이스 실행하기</h4><pre>pnpm exec turbo build --filter=my-utils</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*dc7Z_wKoQEWYtKVdg_BNSQ.png" /></figure><p>turbo.json에 태스크를 정의해야 turbo 명령어를 사용할 수 있다.</p><p>프로젝트 루트에 turbo.json을 생성한다 (다른 설정 없이 turbo를 사용할 수 있도록 기본 세팅)</p><pre>{<br>  &quot;$schema&quot;: &quot;&lt;https://turbo.build/schema.json&gt;&quot;,<br>  &quot;tasks&quot;: {<br>    &quot;build&quot;: {}<br>  }<br>}</pre><ul><li>$schema: 해당 스키마의 형태로 turbo.json이 잘 작성되고 있는지 확인해줌</li><li>tasks: 파이프라인을 작성한다. (기존에는 pipeline이었는데 최근데 tasks로 변경된 듯 하다)</li></ul><p>이후 다시 turbo를 사용하여 my-utils를 build해보면 성공한다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*XIPCXiYtIzy5EIWKB92Q2Q.png" /></figure><p>다시 실행했을 때 <strong>캐시된 값을 사용</strong>하기 때문에 매우 빠르게 빌드되는 것을 확인할 수 있다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*imM88cFMMh_PxlMzPnYvKQ.png" /></figure><p>my-utils에 있는 코드를 수정하고 다시 빌드하면 캐시를 사용하지 않고 재빌드한다.<br>이후 빌드하면 다시 캐시된 값을 사용한다.</p><h4>모든 워크스페이스 실행하기</h4><pre>pnpm exec turbo build</pre><p>— filter없이 작성하면 모든 워크스페이스에 적용된다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*_v6re5ZPmGlvrcxw0RvpwQ.png" /></figure><p>my-app과 my-utils가 build되었다.<br>my-utils는 좀 전에 build했기 때문에 캐시된 값을 사용한 것을 확인할 수 있다.</p><p>다시 모든 워크스페이스에 build 명령어를 입력해봐도 1개만 캐시되는 것을 확인할 수 있는데, <strong>빌드의 결과물이 output으로 지정되지 않았기 때문</strong>이다.</p><pre>// turbo.json<br><br>{<br>  &quot;$schema&quot;: &quot;&lt;https://turbo.build/schema.json&gt;&quot;,<br>  &quot;tasks&quot;: {<br>    &quot;build&quot;: {<br>      &quot;outputs&quot;: [&quot;.next/**&quot;, &quot;!.next/cache/**&quot;, &quot;dist/**&quot;]<br>    }<br>  }<br>}</pre><p>outputs에 Next.js의 빌드 결과물인 <strong>.next</strong>와 패키지의 빌드 결과물인 <strong>dist</strong>를 output으로 지정한다.</p><p><strong>.next/cache</strong>는 제외해야 하므로 !키워드를 통해 제외시킨다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*RGm652qMs9nbhUDTy5xwHA.png" /><figcaption>처음 빌드했을 때</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/329/1*u1C8ll0rr9FTFb0yHBe8AQ.png" /><figcaption>두 번째 빌드했을 때</figcaption></figure><p>빌드를 할 때 의존하고 있는 워크스페이스도 빌드해주어야 하기 때문에 관계에 대한 설정도 필요하다</p><p>turbo.json에서 build에 dependsOn으로 설정 가능하다</p><pre>// turbo.json<br><br>{<br>  &quot;$schema&quot;: &quot;&lt;https://turbo.build/schema.json&gt;&quot;,<br>  &quot;tasks&quot;: {<br>    &quot;build&quot;: {<br>      **&quot;dependsOn&quot;: [&quot;^build&quot;],**<br>      &quot;outputs&quot;: [&quot;.next/**&quot;, &quot;!.next/cache/**&quot;, &quot;dist/**&quot;]<br>    }<br>  }<br>}</pre><p>^build는 <strong>의존하고 있는 모든 워크스페이스를 빌드</strong>한다는 의미이다. ⇒ 태스크 오케스트레이션</p><p>현재 my-app에서는 my-utils를 사용하고 있으니 my-utils가 변경된다면 my-utils가 build된 후 my-app도 다시 빌드가 될 것이다. (반대로 my-app만 수정된다면 my-app만 빌드된다)</p><p>my-app을 수정 후 my-app만 다시 빌드해보자.</p><pre>pnpm exec turbo build --filter=my-app</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*DaJ9QaNb7jaoEDkqocIQwQ.png" /></figure><p>캐시된 값을 사용하지 않고 my-app을 재빌드했다. (my-utils는 캐시된 값 사용)<br>다시 빌드했을 때 두 워크스페이스 전부 캐시된 것을 확인할 수 있다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*S5ZBFSCTU3CHa7Cc3hePDA.png" /></figure><p>이 상태에서 my-utils를 수정하고 다시 my-app을 빌드해본다면..</p><pre>pnpm exec turbo build --filter=my-app</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*S7BSvuLfNHtFnsiekj55IA.png" /></figure><p>my-app과 my-utils <strong>둘 다 캐시되지 않고 재빌드된것을 확인</strong>할 수 있다.</p><p>my-app을 빌드할 때 의존관계에 있는 my-utils를 먼저 빌드하는데 값이 변경되었기 때문에 다시 빌드되었고, 이에 따라 my-app도 다시 빌드된 것을 확인할 수 있다.</p><p>turbo.json에서 build의 outputs의 경우 my-app과 my-utils가 다르다.<br>(my-app은 Next.js기 때문에 <strong>.next</strong>, my-utils는 패키지이기 때문에 <strong>dist</strong>)</p><pre>{<br>  &quot;$schema&quot;: &quot;&lt;https://turbo.build/schema.json&gt;&quot;,<br>  &quot;tasks&quot;: {<br>    &quot;build&quot;: {<br>      &quot;dependsOn&quot;: [&quot;^build&quot;],<br>      &quot;outputs&quot;: [&quot;.next/**&quot;, &quot;!.next/cache/**&quot;, &quot;dist/**&quot;]<br>    }<br>  }<br>}</pre><p>build의 옵션이 워크스페이스마다 다를 수 있다.</p><p>이를 해결하기 위한 두 가지 방법이 있다.</p><ol><li><strong>build 앞에 #으로 워크스페이스 이름을 붙인다.</strong></li></ol><pre>// turbo.json<br><br>{<br>  &quot;$schema&quot;: &quot;https://turbo.build/schema.json&quot;,<br>  &quot;tasks&quot;: {<br>    &quot;my-app#build&quot;: {<br>      &quot;dependsOn&quot;: [&quot;^build&quot;],<br>      &quot;outputs&quot;: [&quot;.next/**&quot;, &quot;!.next/cache/**&quot;]<br>    },<br>    &quot;my-utils#build&quot;: {<br>      &quot;dependsOn&quot;: [&quot;^build&quot;],<br>      &quot;outputs&quot;: [&quot;dist/**&quot;]<br>    }<br>  }<br>}</pre><p><strong>2. build 부분을 각 워크스페이스의 turbo.json에서 작성한다.</strong></p><pre>// turbo.json<br><br>{<br>  &quot;$schema&quot;: &quot;https://turbo.build/schema.json&quot;,<br>  &quot;tasks&quot;: {}<br>}</pre><pre>// apps/my-app/turbo.json<br><br>{<br>  &quot;$schema&quot;: &quot;https://turbo.build/schema.json&quot;,<br>  &quot;extends&quot;: [&quot;//&quot;],<br>  &quot;tasks&quot;: {<br>    &quot;build&quot;: {<br>      &quot;dependsOn&quot;: [&quot;^build&quot;],<br>      &quot;outputs&quot;: [&quot;.next/**&quot;, &quot;!.next/cache/**&quot;]<br>    }<br>  }<br>}</pre><pre>// packages/my-utils/turbo.json<br><br>{<br>  &quot;$schema&quot;: &quot;https://turbo.build/schema.json&quot;,<br>  &quot;extends&quot;: [&quot;//&quot;],<br>  &quot;tasks&quot;: {<br>    &quot;build&quot;: {<br>      &quot;dependsOn&quot;: [&quot;^build&quot;],<br>      &quot;outputs&quot;: [&quot;dist/**&quot;]<br>    }<br>  }<br>}</pre><p>dev에 대한 설정도 할 수 있는데, Next.js 앱인 my-app은 dev모드를 실행할 경우 cache를 사용하지 않아야 한다.</p><pre>// apps/my-app/turbo.json<br><br>{<br>  &quot;$schema&quot;: &quot;https://turbo.build/schema.json&quot;,<br>  &quot;extends&quot;: [&quot;//&quot;],<br>  &quot;tasks&quot;: {<br>    &quot;build&quot;: {<br>      &quot;dependsOn&quot;: [&quot;^build&quot;],<br>      &quot;outputs&quot;: [&quot;.next/**&quot;, &quot;!.next/cache/**&quot;]<br>    },<br>    &quot;dev&quot;: {<br>      &quot;cache&quot;: false,<br>      &quot;persistent&quot;: true<br>    }<br>  }<br>}</pre><p>cache를 <strong>false</strong>로 설정한다.</p><p>계속 실행되는 설정에 대해서는 persistent를 <strong>true</strong>로 설정하도록 turborepo에서 권장한다고 한다.</p><h3>Wraffle 프로젝트에 터보레포 적용하기</h3><h4>모노레포 구조</h4><blockquote><em>pnpm + turborepo을 사용하여 frontend를 관리하는 모노레포를 구성한다.</em></blockquote><p><a href="https://github.com/Wraffle-Inc/wraffle">GitHub - Wraffle-Inc/wraffle: Wraffle 서비스</a></p><h4>프로젝트 세팅</h4><p>기본 터보레포 세팅 명령어</p><pre>pnpm dlx create-turbo@latest</pre><pre>pnpm install turbo --global<br>corepack enable pnpm<br><br>// 설치가 안된다면<br>pnpm setup<br>source ~/.zshrc</pre><p><strong>Apps and Packages</strong></p><ul><li>docs: a <a href="https://nextjs.org/">Next.js</a> app</li><li>web: another <a href="https://nextjs.org/">Next.js</a> app</li><li>@repo/ui: a stub React component library shared by both web and docs applications</li><li>@repo/eslint-config: eslint configurations (includes eslint-config-next and eslint-config-prettier)</li><li>@repo/typescript-config: tsconfig.jsons used throughout the monorepo</li></ul><p>Each package/app is 100% <a href="https://www.typescriptlang.org/">TypeScript</a>.</p><p><strong>Utilities<br></strong>This Turborepo has some additional tools already setup for you:</p><ul><li><a href="https://www.typescriptlang.org/">TypeScript</a> for static type checking</li><li><a href="https://eslint.org/">ESLint</a> for code linting</li><li><a href="https://prettier.io/">Prettier</a> for code formatting</li></ul><h4>Wraffle 프로젝트 레포 구조</h4><pre>- apps<br>    - front<br>        - wraffle-webview<br>        - wraffle-native<br>    - admin<br>- packages<br>    - shared<br>        - eslint-config<br>        - prettier-config<br>        - tailwind-config<br>        - typescript-config<br>    - ui</pre><p>(현재는 일부 구조가 삭제되거나 수정되었다. 이 글은 프로젝트 세팅 당시 기준으로 작성한다.)</p><p>여러 depth를 거쳐 워크스페이스가 존재하기 때문에 pnpm-workspace.yaml 을 수정한다.</p><p>패키지를 특정하는 것이 좋을지 apps와 packages 하위에 있는 모든 폴더를 패키지로 지정하는 것이 좋을지 고민이 되었다.</p><p><a href="https://turbo.build/repo/docs/crafting-your-repository/structuring-a-repository">Structuring a repository | Turborepo</a></p><blockquote><em>Turborepo does not support nested packages like </em><em>apps/** or </em><em>packages/**. Using a structure that would put a package at </em><em>apps/a and another at </em><em>apps/a/b will result in an error.</em></blockquote><blockquote><em>If you’d like to group packages by directory, you can do this using globs like </em><em>packages/* and </em><em>packages/group/* and </em><strong><em>not</em></strong><em> creating a </em><em>packages/group/package.json file.</em></blockquote><p>nested package를 지원하지 않는다고 한다. <br>디렉토리별로 패키지를 그룹화 하고 싶으면 packages/group/* 형식으로 생성하라고 나와있다.</p><pre>packages:<br> - &quot;apps/admin/*&quot;<br> - &quot;apps/front/*&quot;<br> - &quot;packages/*&quot;<br>  - &quot;packages/shared/*&quot;<br>  - &quot;packages/ui/*&quot;</pre><p>하지만 모든 패키지를 명시하는 것이 번거롭다고 느껴져 apps와 packages 하위 폴더를 모두 워크스페이스로 지정하는 방식으로 결정했다.</p><ul><li>pnpm-workspace.yaml</li></ul><pre>packages:<br>  - &quot;apps/**/*&quot;<br>  - &quot;packages/**/*&quot;</pre><p>packages에 있는 eslint-config와 typescript-config 패키지의 이름을 @wraffle/[reponame]으로 변경해주었다.</p><pre>// packages/shared/eslint-config/package.json<br><br>{<br>  &quot;name&quot;: &quot;@wraffle/eslint-config&quot;,<br>  &quot;version&quot;: &quot;0.0.0&quot;,<br>  &quot;private&quot;: true,<br>  &quot;files&quot;: [<br>    &quot;library.js&quot;,<br>    &quot;next.js&quot;,<br>    &quot;react-internal.js&quot;<br>  ],<br>  &quot;devDependencies&quot;: {<br>    &quot;@vercel/style-guide&quot;: &quot;^5.2.0&quot;,<br>    &quot;eslint-config-turbo&quot;: &quot;^2.0.0&quot;,<br>    &quot;eslint-config-prettier&quot;: &quot;^9.1.0&quot;,<br>    &quot;eslint-plugin-only-warn&quot;: &quot;^1.1.0&quot;,<br>    &quot;@typescript-eslint/parser&quot;: &quot;^7.1.0&quot;,<br>    &quot;@typescript-eslint/eslint-plugin&quot;: &quot;^7.1.0&quot;,<br>    &quot;typescript&quot;: &quot;^5.3.3&quot;<br>  }<br>}</pre><pre>// packages/shared/typescript-config/package.json<br><br>{<br>  &quot;name&quot;: &quot;@wraffle/typescript-config&quot;,<br>  &quot;version&quot;: &quot;0.0.0&quot;,<br>  &quot;private&quot;: true,<br>  &quot;license&quot;: &quot;MIT&quot;,<br>  &quot;publishConfig&quot;: {<br>    &quot;access&quot;: &quot;public&quot;<br>  }<br>}</pre><p>tailwind도 공통으로 사용할 것이기 때문에 tailwind-config도 패키지로 만들어 설정했다.</p><p><a href="https://github.com/vercel/turborepo/tree/main/examples">turborepo/examples at main · vercel/turborepo</a></p><p>Turbo-example을 참고하여 tailwind 패키지 생성을 참고했다.</p><pre>// packages/shared/tailwind-config/package.json<br><br>{<br>  **&quot;name&quot;: &quot;@wraffle/tailwind-config&quot;,**<br>  &quot;version&quot;: &quot;0.0.0&quot;,<br>  &quot;private&quot;: true,<br>  &quot;exports&quot;: {<br>    &quot;.&quot;: &quot;./tailwind.config.ts&quot; // tailwind config 설정 파일을 export<br>  },<br>  &quot;devDependencies&quot;: {<br>    &quot;@wraffle/typescript-config&quot;: &quot;workspace:*&quot;, // 패키지를 사용하여 typescript 설정<br>    &quot;tailwindcss&quot;: &quot;^3.4.1&quot;<br>  }<br>}</pre><pre>// packages/shared/tailwind-config/tsconfig.json<br><br>{<br>  &quot;extends&quot;: &quot;@wraffle/typescript-config/base.json&quot;, // typescript config를 상속<br>  &quot;include&quot;: [&quot;.&quot;],<br>  &quot;exclude&quot;: [&quot;dist&quot;, &quot;build&quot;, &quot;node_modules&quot;]<br>}</pre><h3>wraffle-webview</h3><p>wraffle-webview는 next.js로 진행하기 때문에 next.js프로젝트를 생성한다.</p><pre>pnpx create next-app@latest</pre><pre>// apps/front/wraffle-webview/package.json<br><br>{<br>  &quot;name&quot;: &quot;wraffle-webview&quot;,<br>  &quot;version&quot;: &quot;0.1.0&quot;,<br>  &quot;private&quot;: true,<br>  &quot;scripts&quot;: {<br>    &quot;dev&quot;: &quot;next dev&quot;,<br>    &quot;build&quot;: &quot;next build&quot;,<br>    &quot;start&quot;: &quot;next start&quot;,<br>    &quot;lint&quot;: &quot;next lint&quot;<br>  },<br>  &quot;dependencies&quot;: {<br>    &quot;@wraffle/ui&quot;: &quot;workspace:*&quot;, // 공통 컴포넌트 패키지<br>    &quot;next&quot;: &quot;15.0.0-rc.0&quot;,<br>    &quot;react&quot;: &quot;19.0.0-rc-f994737d14-20240522&quot;,<br>    &quot;react-dom&quot;: &quot;19.0.0-rc-f994737d14-20240522&quot;<br>  },<br>  &quot;devDependencies&quot;: {<br>    &quot;@wraffle/eslint-config&quot;: &quot;workspace:*&quot;, // 공통 설정을 패키지로 받아 사용한다.<br>    &quot;@wraffle/tailwind-config&quot;: &quot;workspace:*&quot;,<br>    &quot;@wraffle/typescript-config&quot;: &quot;workspace:*&quot;,<br>    &quot;@types/node&quot;: &quot;^20&quot;,<br>    &quot;@types/react&quot;: &quot;^18&quot;,<br>    &quot;@types/react-dom&quot;: &quot;^18&quot;,<br>    &quot;autoprefixer&quot;: &quot;^10.4.19&quot;,<br>    &quot;eslint&quot;: &quot;^8&quot;,<br>    &quot;eslint-config-next&quot;: &quot;15.0.0-rc.0&quot;,<br>    &quot;postcss&quot;: &quot;^8&quot;,<br>    &quot;tailwindcss&quot;: &quot;^3.4.1&quot;,<br>    &quot;typescript&quot;: &quot;^5&quot;<br>  }<br>}</pre><h3>wraffle-native</h3><pre>pnpx create-expo-app@latest</pre><pre>// apps/front/wraffle-native/package.json<br><br>{<br>  &quot;name&quot;: &quot;wraffle-native&quot;,<br>  &quot;main&quot;: &quot;expo-router/entry&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;private&quot;: true,<br>  &quot;scripts&quot;: {<br>    &quot;start&quot;: &quot;expo start&quot;,<br>    &quot;reset-project&quot;: &quot;node ./scripts/reset-project.js&quot;,<br>    &quot;android&quot;: &quot;expo start --android&quot;,<br>    &quot;ios&quot;: &quot;expo start --ios&quot;,<br>    &quot;web&quot;: &quot;expo start --web&quot;,<br>    &quot;test&quot;: &quot;jest --watchAll&quot;,<br>    &quot;lint&quot;: &quot;expo lint&quot;<br>  },<br>  &quot;jest&quot;: {<br>    &quot;preset&quot;: &quot;jest-expo&quot;<br>  },<br>  &quot;dependencies&quot;: {<br>    &quot;@wraffle/ui&quot;: &quot;*&quot;, // 공통 컴포넌트 패키지<br>    &quot;@expo/vector-icons&quot;: &quot;^14.0.2&quot;,<br>    &quot;@react-navigation/native&quot;: &quot;^6.0.2&quot;,<br>    &quot;expo&quot;: &quot;~51.0.18&quot;,<br>    &quot;expo-constants&quot;: &quot;~16.0.2&quot;,<br>    &quot;expo-font&quot;: &quot;~12.0.7&quot;,<br>    &quot;expo-linking&quot;: &quot;~6.3.1&quot;,<br>    &quot;expo-router&quot;: &quot;~3.5.17&quot;,<br>    &quot;expo-splash-screen&quot;: &quot;~0.27.5&quot;,<br>    &quot;expo-status-bar&quot;: &quot;~1.12.1&quot;,<br>    &quot;expo-system-ui&quot;: &quot;~3.0.7&quot;,<br>    &quot;expo-web-browser&quot;: &quot;~13.0.3&quot;,<br>    &quot;react&quot;: &quot;18.2.0&quot;,<br>    &quot;react-dom&quot;: &quot;18.2.0&quot;,<br>    &quot;react-native&quot;: &quot;0.74.3&quot;,<br>    &quot;react-native-gesture-handler&quot;: &quot;~2.16.1&quot;,<br>    &quot;react-native-reanimated&quot;: &quot;~3.10.1&quot;,<br>    &quot;react-native-safe-area-context&quot;: &quot;4.10.1&quot;,<br>    &quot;react-native-screens&quot;: &quot;3.31.1&quot;,<br>    &quot;react-native-web&quot;: &quot;~0.19.10&quot;<br>  },<br>  &quot;devDependencies&quot;: {<br>    &quot;@babel/core&quot;: &quot;^7.20.0&quot;,<br>    &quot;@types/jest&quot;: &quot;^29.5.12&quot;,<br>    &quot;@types/react&quot;: &quot;~18.2.45&quot;,<br>    &quot;@types/react-test-renderer&quot;: &quot;^18.0.7&quot;,<br>    &quot;jest&quot;: &quot;^29.2.1&quot;,<br>    &quot;jest-expo&quot;: &quot;~51.0.3&quot;,<br>    &quot;react-test-renderer&quot;: &quot;18.2.0&quot;,<br>    &quot;typescript&quot;: &quot;~5.3.3&quot;<br>  }<br>}</pre><h4>turbo.json</h4><pre>{<br>  &quot;$schema&quot;: &quot;&lt;https://turbo.build/schema.json&gt;&quot;,<br>  &quot;tasks&quot;: {<br>    &quot;build&quot;: {<br>      &quot;dependsOn&quot;: [&quot;^build&quot;],<br>      &quot;inputs&quot;: [&quot;$TURBO_DEFAULT$&quot;, &quot;.env*&quot;],<br>      &quot;outputs&quot;: [&quot;dist/**&quot;, &quot;.next/**&quot;, &quot;!.next/cache/**&quot;]<br>    },<br>    &quot;lint&quot;: {<br>      &quot;dependsOn&quot;: [&quot;^lint&quot;]<br>    },<br>    &quot;dev&quot;: {<br>      &quot;cache&quot;: false,<br>      &quot;persistent&quot;: true<br>    }<br>  }<br>}</pre><p>루트에 있는 turbo.json이다.</p><p>outputs에 패키지들의 빌드 결과물인 dist/** 를 추가했다.<br>각 워크스페이스마다 실행 명령어가 달라서 루트 turbo.json에 모든 명령어와 설정을 추가할지 각 워크스페이스마다 turbo.json을 각각 설정할 지 고민 필요하다.<br>아마 후자로 선택하지 않을까 싶다.</p><h3>참고 자료</h3><p><a href="https://turbo.build/repo/docs">Introduction | Turborepo</a></p><p><a href="https://github.com/vercel/turbo/tree/main/examples">turbo/examples at main · vercel/turbo</a></p><p><a href="https://0422.tistory.com/344">Turborepo를 도입하게 된 이야기</a></p><p><a href="https://d2.naver.com/helloworld/7553804#ch4">모던 프론트엔드 프로젝트 구성 기법 — 모노레포 도구 편</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f7108557bb0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/wraffle-tech/turbrepo%EC%99%80-pnpm%EC%9D%84-%EC%82%AC%EC%9A%A9%ED%95%98%EC%97%AC-%EB%AA%A8%EB%85%B8%EB%A0%88%ED%8F%AC-%EA%B5%AC%EC%B6%95%ED%95%98%EA%B8%B0-3f7108557bb0">TurbRepo와 pnpm을 사용하여 모노레포 구축하기</a> was originally published in <a href="https://medium.com/wraffle-tech">Wraffle-Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Yarn Workspace와 Pnpm Workspace]]></title>
            <link>https://medium.com/wraffle-tech/yarn-workspace%EC%99%80-pnpm-workspace-c118e8ba3260?source=rss-2ace129286a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/c118e8ba3260</guid>
            <category><![CDATA[workspace]]></category>
            <category><![CDATA[yarn-workspace]]></category>
            <category><![CDATA[pnpm]]></category>
            <dc:creator><![CDATA[Sangmin Tsx]]></dc:creator>
            <pubDate>Wed, 18 Dec 2024 12:26:34 GMT</pubDate>
            <atom:updated>2024-12-18T12:32:34.897Z</atom:updated>
            <content:encoded><![CDATA[<p>wraffle 프로젝트에서 WebView, React Native, 어드민 시스템을 구성하기 위해 반복적인 프로젝트 셋업이 필요해지는 상황이 발생했다.<br>공통 패키지와 디자인 시스템을 생성하고 각 워크스페이스에서 이를 참조하도록 하여 프로젝트 셋업을 간소화 하고자 <strong>모노레포 방식</strong>을 도입해보기로 했다.</p><p>모노레포를 구성하는 방법으로는 패키지 매니저의 workspace를 사용하는 방법과 모노레포 도구 (turborepo, lerna 등..)을 사용하여 구축할 수 있다.</p><p>이번 포스팅에서는 <strong>패키지 워크스페이스</strong>에 대해서 먼저 알아보자.</p><h3>Yarn Workspace 사용하기</h3><h4>Yarn 1.x workspaces (yarn classic)</h4><ul><li>yarn 1.0부터 기본적으로 사용 가능</li><li>package.json 파일의 workspace 속성을 통해 정의</li><li>프로젝트 내의 모든 패키지 의존성이 함께 설치되고 관리되어 충돌이 적고, 최적화에 유리</li><li>최종적으로 <strong>npm workspace와 같은 방식이기 때문에 같은 한계</strong>를 가지고 있음<br>- node_modules의 근본적인 이슈로 인해 각 workspace에서 package.json에 등록되지 않은 패키지를 사용할 수 있음<br>- 이로 인해 의도하지 않은 문제를 일으킬 수 있음</li><li>Yarn 1.x에서는 루트 프로젝트에 private: true가 설정되어 있어야 함.</li></ul><pre>yarn init -y -p</pre><p>-p는 <strong>private을 true</strong>로 설정하겠다는 옵션</p><pre>mkdir packages packages/a packages/b</pre><p>후에 packages/a와 packages/b에서 yarn init으로 통해 package.json을 생성한다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/185/1*mqWUrJtKllB_FIPGpzwQcw.png" /></figure><p>packages에 있는 워크스페이스들을 <strong>선언적으로 처리</strong>하기 위해 루트에 있는 package.json에서 workspace 속성에 packages 폴더 하위에 있는 패키지들을 등록한다.</p><pre>{<br>  &quot;name&quot;: &quot;yarn-classic-workspace-example&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;main&quot;: &quot;index.js&quot;,<br>  &quot;license&quot;: &quot;MIT&quot;,<br>  &quot;private&quot;: true,<br>  &quot;workspaces&quot;: [<br>    &quot;packages/*&quot;<br>  ]<br>}</pre><p>이후 루트에서 yarn 명령어를 통해 패키지를 설치하면 node_modules폴더에 패키지 <strong>a와 b가 링크로 연결</strong>되어 있는 것을 확인할 수 있음</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/192/1*Rf5FPhNJYXTkcA5kTjgg5Q.png" /></figure><p>워크스페이스 a에 axios를 설치한다.</p><pre>yarn workspace a add axios</pre><p>워크스페이스 b에 axios를 사용하고 a에서 호출해보자.</p><pre>// packages/b/index.js</pre><pre>const axios = require(&#39;axios&#39;);<br>module.exports = async function() {<br>  const response = await axios.get(&quot;&lt;https://api.github.com/users&gt;&quot;);<br>  return response.data;<br>}</pre><pre>// packages/a/index.js</pre><pre>const b = require(&quot;b&quot;);<br>(async function main() {<br>  const users = await b();<br>  console.log(users.map((user) =&gt; user.login).join(&quot;, &quot;));<br>})();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*Yy87mWQvfllOB9mQSZFKsg.png" /></figure><p>문제 1) <strong>워크스페이스 b에는 axios를 설치하지 않았음에도 사용이 가능하다.</strong>문제 2) <strong>워크스페이스 a에서 b를 사용하고 있다는 그 어떤 dependency도 표현이 되어있지 않다.<br></strong>이유) 루트에 있는 node_modules에 axios와 관련된 의존성까지 전부 설치하기 때문</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/197/1*Nyxi06rVpjFWxZQTdDZRHg.png" /></figure><p>특정 workspace를 실행하는 것이 아닌 전체를 실행하는 방법</p><pre>yarn workspaces run start</pre><p>워크스페이스의 의존관계를 확인하는 방법</p><pre>yarn workspaces info</pre><pre>// 실행 결과<br>{<br>  &quot;a&quot;: {<br>    &quot;location&quot;: &quot;packages/a&quot;,<br>    &quot;workspaceDependencies&quot;: [],<br>    &quot;mismatchedWorkspaceDependencies&quot;: []<br>  },<br>  &quot;b&quot;: {<br>    &quot;location&quot;: &quot;packages/b&quot;,<br>    &quot;workspaceDependencies&quot;: [],<br>    &quot;mismatchedWorkspaceDependencies&quot;: []<br>  }<br>}</pre><h4>Yarn berry workspaces</h4><ul><li>yarn 2.x부터 현재 4.x</li><li>기본적으로 <strong>명시적인 의존 관계</strong>를 나타내야 사용이 가능</li><li>node_modules에 패키지를 저장하는 방식이 아닌 패키지를 압축하여 한개의 파일을 .yarn/cache 폴더에 <strong>수평적으로 저장</strong> ⇒ <strong>Plug’n’Play(PnP)<br>- </strong>수평적으로 존재하기 때문에 빠르게 찾을 수 있음<br>- 압축파일을 설치하기 때문에 파일 개수가 감소해 설치가 빠름 (Zero Install을 이용해 저장소에서 함께 관리도 가능)<br>- 팬텀 디펜던시가 발생하지 않음</li></ul><p>yarn berry는 corepack을 사용하여 설정함.</p><blockquote>💡 <strong>corepack이란?</strong></blockquote><blockquote>node를 설치하면 자동으로 설치됨.<br>프로젝트에서 어떤 패키지 매니저를 사용할지 package.json에 추가하는 기능package.json에 어떤 패키지 매니저의 어떤 버전을 사용할 지 지정해두면 그 프로젝트 안에서는 해당 패키지 매니저를 사용할 수 있게 자동으로 설정해준다.<br>corepack의 위치는 npm의 위치와 같음<br>해당 기능을 사용한다면 **<em>corepack enable</em>**을, 사용하지 않는다면 **<em>corepack disable</em>**을 입력한다.<br>corepack으로 직접 패키지를 명시하려면 <em>corepack use pnpm@9.4.0</em> 이렇게 사용할 수 있음</blockquote><pre>corepack enable<br>yarn init -2 -w</pre><p>-2는 yarn berry로 세팅하겠다는 옵션.<br>-w 옵션을 사용하면 package.json에 workspaces가 설정이 되고 packages에 모든 폴더가 워크스페이스로 활용되도록 설정이 됨.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/208/1*AccYRsqcgdBN0YMJDGmU8Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*rwlj8MfU403w5m-PCv-PrA.png" /></figure><p>package.json에 패키지 매니저에 대한 설정이 들어있음. (corepack을 사용했기 때문)<br>다른 사람이 해당 프로젝트를 받아서 실행하면 패키지 매니저에 맞춰서 실행하게됨</p><p><strong>packages 폴더</strong>에 a와 b 폴더를 생성하고 yarn init 명령어를 통해 워크스페이스를 생성한다.</p><p>워크스페이스 a에 axios를 설치한다.</p><pre>yarn workspace a add axios</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/208/1*CG7AORKsRsBgTG04bQdHnA.png" /></figure><blockquote><strong>🤔 axios를 설치했는데 왜 .yarn에 의존성이 추가되지 않았을까?</strong></blockquote><blockquote>yarn에서는 기본적으로 의존성을 Global하게 외부에서 관리하도록 되어있음.<br><em>yarn config enableGlobalCache</em> 명령어를 통해 확인해보면 true로 설정되어 있다.</blockquote><pre>yarn config set enableGlobalCache false</pre><p>해당 옵션을 false로 지정하고 다시 yarn을 통해 패키지를 설치하면</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/212/1*J8wRmplLrr5Z3jyc_falzA.png" /></figure><p>.yarn 폴더에 cache폴더가 생기고 의존성들이 zip으로 압축되어있는 것을 확인할 수 있다.<br>해당 설정에 대해서는 루트 경로에 있는 .yarnrc.yml파일에 기록되어 있음.</p><pre>// .yarnrc.yml</pre><pre>enableGlobalCache: false</pre><p>yarn classic 예제와 같이 워크스페이스 a에 axios를 설치하고 b에서 axios를 사용 후 a에서 b를 호출하여 실행해보자.</p><pre>yarn workspace a add axios</pre><pre>// packages/b/index.js</pre><pre>const axios = require(&#39;axios&#39;);<br>module.exports = async function() {<br>  const response = await axios.get(&quot;&lt;https://api.github.com/users&gt;&quot;);<br>  return response.data;<br>}</pre><pre>// packages/a/index.js</pre><pre>const b = require(&quot;b&quot;);<br>(async function main() {<br>  const users = await b();<br>  console.log(users.map((user) =&gt; user.login).join(&quot;, &quot;));<br>})();</pre><pre>yarn workspace a start</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JLWLiUG5YDKUkjUk-ZW0kw.png" /></figure><p>⇒ a에서 b를 접근하려고 하는데 dependencies에 선언되지 않아서 에러 발생<br>워크스페이스 a의 package.json에 b를 추가하자.</p><pre>{<br>  &quot;name&quot;: &quot;a&quot;,<br>  &quot;packageManager&quot;: &quot;yarn@4.3.1&quot;,<br>  &quot;dependencies&quot;: {<br>    &quot;axios&quot;: &quot;^1.7.2&quot;,<br>    &quot;b&quot;: &quot;workspace:*&quot;<br>  },<br>  &quot;scripts&quot;: {<br>    &quot;start&quot;: &quot;node index.js&quot;<br>  }<br>}</pre><p>workspace:*에서 워크스페이스 b의 특정 버전이 아닌 *를 사용했는데 어떤 버전이든 다 받겠다 라는 의미도 있고, 실제로 npm publish될 때 바뀌는 버전으로 자동으로 맞춰주기 때문에 사용함.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LUCugargec0BRz1FWGIRiw.png" /></figure><p>⇒ 워크스페이스 b에서 axios를 사용하고 있지만 b에서는 axios가 의존성으로 없기 때문에 에러 발생</p><p>a에서 axios를 제거하고 b에서 axios를 추가하면 정상 작동</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*3yov0ogz-11xwRRjdApitQ.png" /></figure><h4>Yarn berry workspace의 아쉬움</h4><ul><li>PnP는 기존의 패키지 관리 방식과 다르기 때문에 어색한 요소들이 있음</li><li>Install이 항상 빠른 것은 아님</li><li>Zero Install을 이용하여 압축파일들을 가지고 작업하면, 저장소 자체가 매우 커질 수 있음</li><li>Zero Install이라고 정말 설치하지 않는 것은 아님</li></ul><h3>pnpm workspace</h3><ul><li>빠르고 효율적인 패키지 매니저</li><li><strong>모노레포를 지원</strong>하고 <strong>평탄하지 않은 node_modules</strong>가 기본이기 때문에 <strong>엄격한 의존 관리</strong>가 가능</li><li><strong>시스템 내에 단일 패키지 스토어에 모든 의존성을 보관</strong>하기 때문에 디스크 공간이 절약</li><li>필요한 의존성을 식별하여 스토어로 가져오고, 디렉토리 구조를 계산하여 <strong>하드 링크</strong>하는 과정을 가지기 때문에 설치 속도가 빠름</li><li>기본적으로 symlink를 사용하여 프로젝트의 집중적인 의존성만을 모듈 디렉토리의 루트로 추가한다.</li></ul><pre>pnpm init<br>corepack use pnpm@9.4.0</pre><pre>// package.json</pre><pre>{<br>  &quot;name&quot;: &quot;pnpm-workspace-example&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;description&quot;: &quot;&quot;,<br>  &quot;main&quot;: &quot;index.js&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;test&quot;: &quot;echo \\&quot;Error: no test specified\\&quot; &amp;&amp; exit 1&quot;<br>  },<br>  &quot;keywords&quot;: [],<br>  &quot;author&quot;: &quot;&quot;,<br>  &quot;license&quot;: &quot;ISC&quot;,<br>  &quot;packageManager&quot;: &quot;pnpm@9.4.0+sha1.9217c800d4ab947a7aee520242a7b70d64fc7638&quot;<br>}</pre><pre>mkdir packages packages/a packages/b</pre><p>이후 a와 b에서도 pnpm init을 해준다.</p><p>기존에 npm과 yarn은 루트의 packages.json에서 workspace에 대해 선언적으로 표현을 해주었는데 pnpm은 다른 방식으로 관리한다.</p><h4>workspace 선언하기</h4><p>프로젝트 루트 경로에서 pnpm-workspace.yaml 파일을 생성한다.</p><pre>packages:<br>  - &quot;packages/*&quot;</pre><p>a 워크스페이스 axios를 설치하자.</p><pre>pnpm --filter a add axios</pre><p>다른 예제와 같이 b에서 axios를 사용하고 a에서 호출해보자.</p><pre>// packages/b/index.js</pre><pre>const axios = require(&quot;axios&quot;);<br>module.exports = async function () {<br>  const response = await axios.get(&quot;&lt;https://api.github.com/users&gt;&quot;);<br>  return response.data;<br>};</pre><pre>// packages/a/index.js</pre><pre>const b = require(&quot;b&quot;);<br>(async function main() {<br>  const users = await b();<br>  console.log(users.map((user) =&gt; user.login).join(&quot;, &quot;));<br>})();</pre><pre>pnpm --filter a start</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*JNHTX4eab57Sic-X0QU7Bg.png" /></figure><p>마찬가지로 b가 의존성에 추가되지 않아서 에러가 발생한다.</p><pre>// packages/a/package.json</pre><pre>{<br>  &quot;name&quot;: &quot;a&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;description&quot;: &quot;&quot;,<br>  &quot;main&quot;: &quot;index.js&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;test&quot;: &quot;echo \\&quot;Error: no test specified\\&quot; &amp;&amp; exit 1&quot;,<br>    &quot;start&quot;: &quot;node index.js&quot;<br>  },<br>  &quot;keywords&quot;: [],<br>  &quot;author&quot;: &quot;&quot;,<br>  &quot;license&quot;: &quot;ISC&quot;,<br>  &quot;dependencies&quot;: {<br>    &quot;axios&quot;: &quot;^1.7.2&quot;,<br>    &quot;b&quot;: &quot;workspace:*&quot;<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/204/1*t_aQ4jWZukaiLwfIwjloeQ.png" /></figure><p>a에 b가 링크로 연결되었다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*XwvXWypklDJoNE3groMRlA.png" /></figure><p>워크스페이스 b에는 axios가 없기 때문에 에러 발생.<br>다른 예제와 같이 a에서 axios를 삭제하고 b에 추가 후 실행하면 정상적으로 작동한다.</p><h4>pnpm의 node_modules 구조</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/192/1*4Tkll1GhNw2DtzrxcI2Btw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/203/1*jbn4kdTczm_Ds4QXkRzV1g.png" /></figure><p>워크스페이스 b의 node_modules에는 axios가 <strong>심볼릭 링크로 연결</strong>되어 있다.<br>프로젝트 루트에 있는 node_modules에는 axios뿐만 아니라 <strong>axios의 의존성까지 모두 존재</strong>한다.<br>symlink를 사용하여 프로젝트의 집중적인 의존성만을 모듈 디렉토리의 루트로 추가하기 때문이다.</p><p>pnpm에서는 어떻게 디스크 용량을 절약할 수 있는걸까?<br>프로젝트 루트에 있는 node_modules/.pnpm 는 virtual store라고 불린다.<br>프로젝트 전체에서 사용하는 패키지들의 <strong>이름</strong>과 <strong>버전</strong>이 표기되어 있다.<br>.pnpm에 있는 패키지들은 <strong>다른 저장소에 하드링크 방식으로 연결</strong>되어 있다.</p><p>즉 .pnpm에 있는 axios 파일은 실제로는 다른 저장소(store)에 파일이 존재하는 것을 하드링크 하고 있는 것이다. (한 곳의 용량만 사용함)</p><pre>pnpm config get store-dir</pre><p>위 명령어를 통해 store의 경로를 볼 수 있다 (저는 등록하지 않아서 undefined라고 나오네요)</p><p>pnpm store 설정하기</p><pre>pnpm config set store-dir ~/.pnpm-store</pre><h4>pnpm을 사용하여 워크스페이스 실행하기</h4><p>특정 워크스페이스 실행하기</p><pre>pnpm --filter a start</pre><p>모든 워크스페이스 실행하기</p><pre>pnpm -r run start</pre><p>전체 워크스페이스 중 start라는 스크립트가 있는 패키지만 실행이 된다</p><p>루트까지 포함해서 실행하고 싶다면 --include-workspace-root 옵션을 추가하면 된다.</p><p>모든 워크스페이스의 의존성을 확인하는 방법</p><pre>pnpm -r list</pre><h4>정리</h4><ul><li>pnpm은 기존의 방식을 해치지 않으며, 빠르고 효율적인 방식을 사용함</li><li>모노레포를 지원하며, 엄격한 의존성 해석을 통해 의도하지 않게 사용되는 경우를 피할 수 있음</li><li>pnpm workspace를 통해 프로젝트 특정 폴더를 패키지로 활용하는 방법이 있음</li><li>여러가지 장점으로 인해 모노레포를 운영할 수 있는 좋은 패키지 매니저로 부상</li></ul><h3>패키지 매니저만으로 모노레포를 운영할 수 있을까?</h3><p>npm, yarn (classic, berry), pnpm에는 <strong>workspace 기능</strong>이 있고 이를 통해 각 패키지에 독립적으로 무언가를 수행하거나, 전체 패키지를 순회하며 무언가를 수행할 수 있음</p><p>작은 규모에서는 특별한 문제를 못 느낄 수 있지만 모노레포를 운영하면서 프로젝트가 점점 커지게 된다면 <strong>매우 느리고 불편해질 수 있다</strong></p><ul><li>모노레포에 패키지 A, B, C가 있고, A는 B를 사용하고, B는 C를 사용한다고 했을 때 C의 변경으로 인해 B와 A도 영향을 받는다. 이런 관계에 따라 항상 정확한 순서를 기억하여 빌드를 하거나 테스트를 해야한다.</li><li>이런 패키지들의 작업 수행을 효율적으로 관리하기 위해 <strong>모노레포 빌드시스템 도구</strong>를 사용할 수 있다.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c118e8ba3260" width="1" height="1" alt=""><hr><p><a href="https://medium.com/wraffle-tech/yarn-workspace%EC%99%80-pnpm-workspace-c118e8ba3260">Yarn Workspace와 Pnpm Workspace</a> was originally published in <a href="https://medium.com/wraffle-tech">Wraffle-Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[webview-bridge를 사용하여 Next.js React-Native 웹뷰 브릿지 연결하기]]></title>
            <link>https://medium.com/wraffle-tech/webview-bridge%EB%A5%BC-%EC%82%AC%EC%9A%A9%ED%95%98%EC%97%AC-next-js-react-native-%EC%9B%B9%EB%B7%B0-%EB%B8%8C%EB%A6%BF%EC%A7%80-%EC%97%B0%EA%B2%B0%ED%95%98%EA%B8%B0-6163daa66c57?source=rss-2ace129286a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/6163daa66c57</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[webview]]></category>
            <category><![CDATA[bridge]]></category>
            <dc:creator><![CDATA[Sangmin Tsx]]></dc:creator>
            <pubDate>Tue, 17 Dec 2024 19:20:55 GMT</pubDate>
            <atom:updated>2024-12-17T20:14:53.594Z</atom:updated>
            <content:encoded><![CDATA[<h3>Bridge 워크스페이스 생성하기</h3><p>2024 FE-CONF에서 소개한 react-native-webivew 패키지를 한 단계 래핑하는 <a href="https://gronxb.github.io/webview-bridge/">webview-bridge</a> 라이브러리를 사용하기로 했다.<br><a href="https://equinox-dolphin-3e9.notion.site/React-Native-Web-15fd9c78211b804dbd9ad2a3a656adba?pvs=4">(React Native와 Web이 공존하는 또 하나의 방법)</a></p><p><a href="https://gronxb.github.io/webview-bridge/">WebViewBridge</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FGyU9-pE0dAg&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DGyU9-pE0dAg&amp;image=http%3A%2F%2Fi.ytimg.com%2Fvi%2FGyU9-pE0dAg%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0daf8430ca6658fbb07b393d98aa353/href">https://medium.com/media/d0daf8430ca6658fbb07b393d98aa353/href</a></iframe><p>모노레포를 사용하고 있기 때문에 bridge 메소드와 타입을 정의하는 패키지를 만들어 wraffle-webview와 wraffle-native 워크스페이스 간 통신을 위한 브릿지 라이브러리 워프스페이스를 생성한다.</p><pre>pnpm init</pre><h4>패키지 설치</h4><pre>pnpm add -D typescript vitest</pre><pre>pnpm add @webview-bridge/react @webview-bridge/react-native @webview-bridge/web react@^18 react-native-webview tsup</pre><pre>// webview-bridge/package.json<br><br>{<br>  &quot;name&quot;: &quot;@wraffle/bridge&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;description&quot;: &quot;Wraffle Webview Bridge&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;build&quot;: &quot;tsup src/**/** --format cjs,esm --dts&quot;,<br>    &quot;lint:es&quot;: &quot;eslint &#39;**/*.{ts,tsx}&#39; --cache&quot;,<br>    &quot;lint:es:fix&quot;: &quot;eslint &#39;**/*.{ts,tsx}&#39; --ext .ts --fix --cache&quot;,<br>    &quot;lint:etc&quot;: &quot;prettier &#39;**/*.{js,ts,tsx,json,yaml,md}&#39; --check --cache&quot;,<br>    &quot;lint:etc:fix&quot;: &quot;prettier &#39;**/*.{js,ts,tsx,json,yaml,md}&#39; --write --cache&quot;,<br>    &quot;lint&quot;: &quot;pnpm lint:es &amp;&amp; pnpm lint:etc&quot;,<br>    &quot;lint:fix&quot;: &quot;pnpm lint:es:fix &amp;&amp; pnpm lint:etc:fix&quot;<br>  },<br>  &quot;author&quot;: &quot;Wraffle Team&quot;,<br>  &quot;license&quot;: &quot;ISC&quot;,<br>  &quot;main&quot;: &quot;./src/index.web.ts&quot;,<br>  &quot;react-native&quot;: &quot;./src/index.native.ts&quot;,<br>  &quot;types&quot;: &quot;./src/index.ts&quot;,<br>  &quot;dependencies&quot;: {<br>    &quot;@webview-bridge/react&quot;: &quot;^1.7.5&quot;,<br>    &quot;@webview-bridge/react-native&quot;: &quot;^1.7.5&quot;,<br>    &quot;@webview-bridge/web&quot;: &quot;^1.7.5&quot;,<br>    &quot;react&quot;: &quot;^18&quot;,<br>    &quot;react-native-webview&quot;: &quot;^13.12.5&quot;,<br>    &quot;tsup&quot;: &quot;^8.3.5&quot;<br>  },<br>  &quot;devDependencies&quot;: {<br>    &quot;@wraffle/eslint-config&quot;: &quot;workspace:*&quot;,<br>    &quot;@wraffle/prettier-config&quot;: &quot;workspace:*&quot;,<br>    &quot;@wraffle/typescript-config&quot;: &quot;workspace:*&quot;,<br>    &quot;typescript&quot;: &quot;^5.7.2&quot;,<br>    &quot;vitest&quot;: &quot;^2.1.8&quot;<br>  }<br>}</pre><p>tsup 번들러를 사용하여 프로젝트를 번들링한다.</p><h4>tsconfig, Prettier, Eslint, Turbo.json 설정</h4><pre>// tsconfig.json<br><br>{<br>  &quot;extends&quot;: &quot;@wraffle/typescript-config/react-library.json&quot;,<br>  &quot;compilerOptions&quot;: {<br>    &quot;baseUrl&quot;: &quot;./&quot;,<br>    &quot;outDir&quot;: &quot;dist&quot;,<br>    &quot;rootDir&quot;: &quot;src&quot;,<br>    &quot;incremental&quot;: false<br>  },<br>  &quot;include&quot;: [&quot;src&quot;],<br>  &quot;exclude&quot;: [&quot;node_modules&quot;, &quot;dist&quot;]<br>}</pre><pre>// .prettierrc.json<br><br>&quot;@wraffle/prettier-config&quot;</pre><pre>// .eslintrc.js<br><br>/** <strong>@type</strong> {import(&quot;eslint&quot;).Linter.Config} */<br>module.exports = {<br>  root: true,<br>  extends: [&#39;@wraffle/eslint-config/react-internal.js&#39;],<br>  parser: &#39;@typescript-eslint/parser&#39;,<br>  parserOptions: {<br>    project: true,<br>  },<br>};</pre><pre>// turbo.json<br><br>{<br>  &quot;$schema&quot;: &quot;&lt;https://turbo.build/schema.json&gt;&quot;,<br>  &quot;extends&quot;: [&quot;//&quot;],<br>  &quot;tasks&quot;: {<br>    &quot;build&quot;: {<br>      &quot;outputs&quot;: [&quot;dist/**&quot;]<br>    }<br>  }<br>}</pre><h4>Bridge 설정하기</h4><p><a href="https://gronxb.github.io/webview-bridge/getting-started.html">WebViewBridge</a></p><p>webview-bridge 공식 문서에 문서화가 아주 잘 되어있다.</p><p>Native 파트와 Web 파트로 나누어져 있는데, Native에서는 bridge 오브젝트를 선언해 브릿지 통신으로 실행할 함수를 정의한다.</p><pre>import { createWebView, bridge } from &quot;@webview-bridge/react-native&quot;;<br><br>// Register functions in the bridge object in your React Native code<br>export const appBridge = bridge({<br>  async getMessage() {<br>    return &quot;Hello, I&#39;m native&quot;;<br>  },<br>  async sum(a: number, b: number) {<br>    return a + b;<br>  },<br>  async openInAppBrowser(url: string) {<br>    if (await InAppBrowser.isAvailable()) {<br>      await InAppBrowser.open(url);<br>    }<br>  },<br>  // ... Add more functions as needed<br>});<br>// Export the bridge type to be used in the web application<br>export type AppBridge = typeof appBridge;</pre><p>해당 브릿지 오브젝트를 사용해 createWebView 메소드로 React Native에서 사용할 웹뷰 컴포넌트를 생성할 수 있다.</p><pre>export const { WebView } = createWebView({<br>  bridge: appBridge,<br>  debug: true, // Enable console.log visibility in the native WebView<br>});<br><br>// Use the WebView component in your app<br>function App(): JSX.Element {<br>  return (<br>    &lt;SafeAreaView style={{ height: &quot;100%&quot; }}&gt;<br>      &lt;WebView<br>        source={{<br>          uri: &quot;&lt;http://localhost:5173&gt;&quot;,<br>        }}<br>        style={{ height: &quot;100%&quot;, flex: 1, width: &quot;100%&quot; }}<br>      /&gt;<br>    &lt;/SafeAreaView&gt;<br>  );<br>}<br>export default App;</pre><p>Web 파트에서는 Native에서 만든 bridge 타입을 제네릭으로 linkBridge를 생성하여 bridge 오브젝트에 선언한 함수나 변수를 가져와 사용할 수 있다.</p><pre>import { linkBridge } from &quot;@webview-bridge/web&quot;;<br>import type { AppBridge } from &quot;&quot;; // Import the type &#39;appBridge&#39; declared in native<br><br>const bridge = linkBridge&lt;AppBridge&gt;({<br>  onReady: async (method) =&gt; {<br>    console.log(&quot;bridge is ready&quot;);<br>    const version = await method.getBridgeVersion();<br>    console.log(&quot;currentBridgerVersion&quot;, version);<br>  },<br>});<br><br>bridge.getMessage().then((message) =&gt; console.log(message)); // Expecting &quot;Hello, I&#39;m native&quot;<br>bridge.sum(1, 2).then((num) =&gt; console.log(num)); // Expecting 3<br>bridge.openInAppBrowser(&quot;&lt;https://google.com&gt;&quot;); // Open google in the native inAppBrowser</pre><p>위 튜토리얼 코드 기반으로 @wraffle/bridge 패키지를 구성해보자.</p><h4>@wraffle/bridge app</h4><pre>// src/app/module/app-bridge.ts<br><br>import {bridge} from &#39;@webview-bridge/react-native&#39;;<br>type AppBridgeState = {<br>  tokens: {accessToken: string; refreshToken: string} | null;<br>  setBridgeWraffleTokens: (tokens: {<br>    accessToken: string;<br>    refreshToken: string;<br>  }) =&gt; Promise&lt;void&gt;;<br>};<br>export const appBridge = bridge&lt;AppBridgeState&gt;(({set}) =&gt; ({<br>  tokens: null,<br>  setBridgeWraffleTokens: async tokens =&gt; {<br>    set({<br>      tokens: {<br>        accessToken: tokens.accessToken,<br>        refreshToken: tokens.refreshToken,<br>      },<br>    });<br>  },<br>}));<br>export type AppBridge = typeof appBridge;</pre><p>bridge에 우선 토큰과 토큰을 set 하는 함수만 선언한다. appBridge와 appBridge 타입을 export한다.</p><pre>// src/app/hooks/useNativeBridge.ts<br><br>import {appBridge} from &#39;../module/app-bridge&#39;;<br>import {createWebView, useBridge} from &#39;@webview-bridge/react-native&#39;;<br>export const useNativeBridge = () =&gt; {<br>  return useBridge(appBridge);<br>};<br>export const {WebView} = createWebView({<br>  bridge: appBridge,<br>  debug: true, // Enable console.log visibility in the native WebView<br>});</pre><p>createWebView를 통해 WebView를 export하고 useBridge를 통해 useNativeBridge를 호출하여 메소드를 쓸 수 있게끔 구현한다.</p><h4>@wraffle/bridge web</h4><pre>// src/web/providers/BridgeProvider.ts<br><br>&#39;use client&#39;;<br>import {type AppBridge} from &#39;../../app/module/app-bridge&#39;;<br>import {createLinkBridgeProvider} from &#39;@webview-bridge/react&#39;;<br>export const {<br>  BridgeProvider,<br>  useBridgeStore,<br>  useBridgeStatus,<br>  useBridgeLoose,<br>  useBridgeEventListener,<br>} = createLinkBridgeProvider&lt;AppBridge&gt;({<br>  throwOnError: true,<br>  initialBridge: {<br>    tokens: null,<br>  },<br>  onReady: () =&gt; {<br>    console.log(&#39;bridge is ready&#39;);<br>  },<br>});</pre><p>createLinkBridgeProvider를 통해 BridgeProvider와 useBridgeStore 등 훅을 export하도록 설정한다.</p><pre>// src/web/hooks/useWebBridge.ts<br><br>import {useBridgeStore} from &#39;../providers/BridgeProvider&#39;;<br>export const useWebBridge = () =&gt; {<br>  return useBridgeStore(state =&gt; state);<br>};</pre><p>useBridgeStore를 통해 useWebBridge를 호출하여 메소드를 쓸 수 있게끔 구현한다.</p><h4>wraffle-webview</h4><p>wraffle-webview 프로젝트에서 layout에 BridgeProvider를 감싸준다.</p><pre>// wraffle-webview/app/layout.tsx<br><br>import {BridgeProvider} from &#39;@wraffle/bridge/src/web&#39;;<br>...<br>export default function RootLayout({<br>  children,<br>}: Readonly&lt;{<br>  children: React.ReactNode;<br>}&gt;) {<br>  return (<br>    &lt;html lang=&#39;en&#39;&gt;<br>      &lt;body className={`${pretendard.variable} font-pretendard`}&gt;<br>        &lt;div className=&#39;container h-screen min-h-screen&#39;&gt;<br>          &lt;ReactQueryProviders&gt;<br>            &lt;BridgeProvider&gt;<br>              &lt;Toaster /&gt;<br>              {IconLoader}<br>              {children}<br>            &lt;/BridgeProvider&gt;<br>          &lt;/ReactQueryProviders&gt;<br>        &lt;/div&gt;<br>      &lt;/body&gt;<br>    &lt;/html&gt;<br>  );<br>}</pre><h4>wraffle-native</h4><p>react-native-webview 패키지를 설치해야한다.</p><pre>pnpm add react-native-webview</pre><p>wraffle-native 프로젝트에서 app/index.js에서 WebView 컴포넌트를 import해서 설정한다.</p><pre>import {StyleSheet} from &#39;react-native&#39;;<br>import {SafeAreaView} from &#39;react-native-safe-area-context&#39;;<br>import {Colors} from &#39;@/shared/ui/constants/Colors&#39;;<br>import {WebView} from &#39;@wraffle/bridge/src/index.native&#39;;<br><br>const Home = () =&gt; {<br>  return (<br>    &lt;SafeAreaView style={styles.safeArea} edges={[&#39;top&#39;, &#39;left&#39;, &#39;right&#39;]}&gt;<br>      &lt;WebView<br>        style={styles.webview}<br>        source={{<br>          uri: &#39;&lt;http://localhost:3000&gt;&#39;,<br>        }}<br>      /&gt;<br>    &lt;/SafeAreaView&gt;<br>  );<br>};<br>export default Home;<br>const styles = StyleSheet.create({<br>  safeArea: {<br>    height: &#39;100%&#39;,<br>    backgroundColor: Colors.light.background,<br>  },<br>  webview: {<br>    flex: 1,<br>    width: &#39;100%&#39;,<br>    height: &#39;100%&#39;,<br>  },<br>});</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/1*HunMMZ61aMIn3jRfztIrdA.png" /></figure><h3>트러블 슈팅</h3><h4>모노레포 환경에서 pnpm 패키지 매니저와 expo를 사용하는 경우</h4><p>프로젝트 루트에 있는 .npmrc 에 아래와 같이 설정한다.</p><pre># Expo doesn&#39;t play nice with pnpm by default. <br># The symbolic links of pnpm break the rules of Expo monorepos.<br># @link &lt;https://docs.expo.dev/guides/monorepos/#common-issues&gt;<br>node-linker=hoisted<br>strict-peer-dependencies=false<br><br># Prevent pnpm from adding the &quot;&quot;&quot; prefix to local<br># packages as it causes issues with manypkg<br># @link &lt;https://pnpm.io/npmrc#prefer-workspace-packages&gt;<br>prefer-workspace-packages=true<br>save-workspace-protocol=false</pre><p>node-linker=hoisted 옵션은 pnpm의 하드링크/심볼릭링크 방식으로 의존성을 관리하는 것이 아닌 Yarn Classic이나 npm처럼 평탄화하여 관리하겠다는 옵션이다.</p><blockquote><em>By default, pnpm manages dependencies using hard links and does not flatten the dependency structure. This is incompatible with expo project structure.<br>Using the node-linker=hoisted setting in the .npmrc file tells pnpm to manage dependencies in a more traditional structure, similar to how other tools like npm or yarn do it.</em></blockquote><p>Expo는 pnpm과 호환이 좋지 않고 pnpm의 심볼릭 링크 방식이 Expo monorepo의 룰에서 break 될 수 있다고 한다.</p><h4>Input 클릭 시 화면이 줌 되는 이슈</h4><p>웹뷰 페이지에서 Input 터치 시 화면이 zoom 되는 이슈가 있다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*NZ_mstbxbG4PAm3MHa8nsQ.gif" /></figure><p><a href="https://talkwithcode.tistory.com/7">input 모바일 확대 방지</a></p><p>html meta 태그에 아래와 같은 값을 추가하면 해결할 수 있다.</p><ul><li>initial-scale=1.0 // 초기 크기를 설정.</li><li>user-scalable=no // 확대 기능을 사용하지 않음.</li><li>maximum-scale=1 // 최대 배율, 크기를 설정.</li><li>width=device-width // 화면이 표현하는 사이즈를 디바이스 사이즈에 맞춤.</li></ul><p>user-scalable 속성이 확대되는 이슈의 원인인 듯 하다.</p><p>Next.js 14 버전에서는 Viewport 를 통해 해당 값을 등록할 수 있다.</p><pre>// layout.tsx<br><br>import type {Viewport} from &#39;next&#39;;<br>...<br>export const viewport: Viewport = {<br>  userScalable: false,<br>  initialScale: 1.0,<br>  maximumScale: 1,<br>  width: &#39;device-width&#39;,<br>};<br>...</pre><h4>IOS 시뮬레이터에서 키보드가 나타나지 않는 이슈</h4><p>Input을 클릭해도 하단에 키보드가 나오지 않는다.<br>이는 시뮬레이터에서 Input을 포커스하고 CMD + K 를 입력해주면 나타난다.</p><h4>android 실행되지 않는 이슈</h4><p>pnpm android를 통해 안드로이드로 실행시키면 다음과 같은 에러가 발생한다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*jU2HJfrdsmEfF5MYL5lytA.png" /></figure><p>정확히는 모르겠지만 에러 메세지를 읽어봤을 때 expo-router/entry를 찾지 못하는 문제인 듯 싶어서 찾아보니 같은 에러를 겪는 사람들이 있었다.</p><p><a href="https://github.com/t3-oss/create-t3-turbo/issues/741#issuecomment-1812454342">bug(android): `main: expo-router/entry` is not resolved · Issue #741 · t3-oss/create-t3-turbo</a></p><p>→ package.json에 명시된 main의 경로인 expo-router/entry를 index.js로 변경해주고 index.js에 expo-router/entry를 import 한다.</p><pre>// package.json<br>...<br>&quot;main&quot;: &quot;index.js&quot;, // &quot;expo-router/entry&quot;에서 변경<br>...</pre><pre>// /index.js<br><br>import &#39;expo-router/entry&#39;;</pre><h4>이번엔 또다른 이슈..</h4><p>이제 위와 같은 에러는 발생하지 않지만 새로운 이슈가 발생했다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*5GEMwjcNfWXpZvEpKwhJXg.png" /></figure><p>ERR_CONNECTION_REFUSED 라는 에러가 발생했는데 WebView에서 source uri로 입력한 localhost:3000과의 연결 자체를 거부하는 것 같다. 바로 구글링을 해봤다.</p><p><a href="https://velog.io/@euuuunii/ReactNative-WebView%EC%97%90%EC%84%9C-localhost-%EC%A0%91%EC%86%8D">ReactNative WebView에서 localhost 접속</a></p><p>요약하면 <strong>안드로이드 에뮬레이터에서는 localhost로 바로 진입이 불가능</strong>하다고 한다. localhost가 아닌 ip 주소로 접근해야한다..</p><p>wraffle-webview 서버를 ip주소로 실행시킨다.<br>터미널에 ipconfig getifaddr en0 를 입력하여 local IP 주소를 알아내고, 해당 IP 주소로 웹 서비스를 실행시킨다.</p><pre>// wraffle-webview<br><br>pnpm dev -H 192.168.XXX.XXX</pre><p>WebView의 source uri도 IP 주소로 설정하여 안드로이드 에뮬레이터를 실행시킨다.</p><pre>&lt;SafeAreaView style={styles.safeArea} edges={[&#39;top&#39;, &#39;left&#39;, &#39;right&#39;]}&gt;<br>  &lt;WebView<br>    style={styles.webview}<br>    source={{<br>      uri: &#39;&lt;http://192.168.XXX.XXX:3000&gt;&#39;,<br>    }}<br>  /&gt;<br>&lt;/SafeAreaView&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*ryiMthKTsEbh6ar9RVrdZQ.png" /></figure><p>실행이 잘 된다 👍</p><p>근데 안드로이드 실행할 때 마다 uri 코드를 바꿔줘야 하니 꼭 확인이 필요한 경우가 아니라면 IOS 환경에서 개발할 것 같다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6163daa66c57" width="1" height="1" alt=""><hr><p><a href="https://medium.com/wraffle-tech/webview-bridge%EB%A5%BC-%EC%82%AC%EC%9A%A9%ED%95%98%EC%97%AC-next-js-react-native-%EC%9B%B9%EB%B7%B0-%EB%B8%8C%EB%A6%BF%EC%A7%80-%EC%97%B0%EA%B2%B0%ED%95%98%EA%B8%B0-6163daa66c57">webview-bridge를 사용하여 Next.js React-Native 웹뷰 브릿지 연결하기</a> was originally published in <a href="https://medium.com/wraffle-tech">Wraffle-Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Next.js에서 확장성을 고려한 Fetch API Client와 Auth.js를 사용한 인증 구현하기]]></title>
            <link>https://medium.com/wraffle-tech/fetch-api-client%EC%99%80-auth-js-nextauth-js-%EB%A5%BC-%EC%82%AC%EC%9A%A9%ED%95%9C-%EC%9D%B8%EC%A6%9D-%EA%B5%AC%ED%98%84%ED%95%98%EA%B8%B0-6fe9b1062bc2?source=rss-2ace129286a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/6fe9b1062bc2</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[nextauth]]></category>
            <category><![CDATA[authjs]]></category>
            <category><![CDATA[turborepo]]></category>
            <category><![CDATA[fetch-api]]></category>
            <dc:creator><![CDATA[Sangmin Tsx]]></dc:creator>
            <pubDate>Mon, 02 Dec 2024 16:56:06 GMT</pubDate>
            <atom:updated>2025-02-11T17:47:13.321Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*fXJLrEqU5uwiR6kJ7ijiiA.png" /></figure><p>이번 포스팅에서는 Wraffle 프로젝트에 Fetch API Client와 Auth.js를 사용해 인증/인가 처리를 구현한 내용을 공유하려고 한다.</p><h3>Fetch API Client 생성하기</h3><p>이 프로젝트에서는 데이터 캐싱을 위해 fetch와 tanstack-query를 사용하고 있다.</p><p>매번 반복적으로 작성해야 하는 개인화된 API 요청, Base URL 설정, 응답 타입 추론 등의 작업을 효율화하기 위해 공통 Fetch API Client를 만들어 관리하고자 했다.</p><p>백엔드 API의 응답은 status와 code 필드와 함께 data 필드에 값이 래핑되어 반환된다.<br>요청이 실패하면 data 필드 대신 message 필드가 포함된 응답이 반환된다.</p><p>먼저 API 응답에 사용할 타입을 정의한다.<br>에러 타입에 대한 타입가드 함수도 정의한다.</p><pre>// src/shared/api/type.ts<br><br>export interface ApiResponse {<br>  status: number;<br>  code: string;<br>}<br><br>export type ApiResponseError = ApiResponse &amp; {<br>  message: string;<br>};<br><br>export type ApiResponseWithData&lt;T&gt; = ApiResponse &amp; {<br>  data: T;<br>};<br><br>export const isApiResponseError = (<br>  error: unknown,<br>): error is ApiResponseError =&gt; {<br>  return (<br>    typeof error === &#39;object&#39; &amp;&amp;<br>    error !== null &amp;&amp;<br>    &#39;status&#39; in error &amp;&amp;<br>    &#39;code&#39; in error &amp;&amp;<br>    &#39;message&#39; in error<br>  );<br>};<br><br>export interface Tokens {<br>  accessToken: string;<br>  refreshToken: string;<br>}</pre><h4>요구사항</h4><ol><li>baseURL을 생성자에서 입력받는다.</li><li>인증이 필요한 API 요청의 경우, Authorization 헤더에 토큰을 포함한다.<br>+ Content Type에 대한 설정도 받을 수 있어야 한다.</li><li>응답 타입이 자동으로 추론될 수 있어야 한다.</li></ol><h4>FetchClient 클래스 구현</h4><pre>// src/shared/api/fetchClient.ts<br><br>import {auth} from &#39;../util/auth&#39;;<br>import {type ApiResponseError, type ApiResponseWithData} from &#39;./type&#39;;<br><br>type Params&lt;T = unknown&gt; = {<br>  [K in keyof T]?: string | number | boolean | null | undefined;<br>};<br><br>type FetchOptions&lt;TBody = unknown, TParams = unknown&gt; = Omit&lt;<br>  RequestInit,<br>  &#39;headers&#39; | &#39;body&#39;<br>&gt; &amp; {<br>  headers?: Record&lt;string, string&gt;;<br>  body?: TBody;<br>  withAuth?: boolean;<br>  contentType?: string;<br>  params?: Params&lt;TParams&gt;;<br>};<br><br>export class FetchClient {<br>  private baseUrl: string;<br><br>  constructor(baseUrl: string) {<br>    this.baseUrl = baseUrl;<br>  }<br><br>  /*<br>  request 메소드 오버로드 정의<br>  TResponse를 지정하는 경우 리턴 타입은 Promise&lt;ApiResponseWithData&lt;TResponse&gt;&gt;<br>  TResponse를 지정하지 않는 경우 리턴 타입은 Promise&lt;ApiResponseWithData&lt;undefined&gt; | null&gt;<br>  */<br>  private async request&lt;TResponse, TBody = unknown&gt;(<br>    url: string,<br>    options: FetchOptions&lt;TBody&gt;,<br>  ): Promise&lt;ApiResponseWithData&lt;TResponse&gt;&gt;;<br>  private async request&lt;TBody = unknown&gt;(<br>    url: string,<br>    options: FetchOptions&lt;TBody&gt;,<br>  ): Promise&lt;ApiResponseWithData&lt;undefined&gt; | null&gt;;<br><br>  private async request&lt;TResponse = undefined, TBody = unknown&gt;(<br>    url: string,<br>    options: FetchOptions&lt;TBody&gt;,<br>  ): Promise&lt;ApiResponseWithData&lt;TResponse&gt; | null&gt; {<br>    const {<br>      withAuth = false,<br>      contentType = &#39;application/json&#39;,<br>      headers,<br>      body,<br>      ...restOptions<br>    } = options;<br>    const session = await auth();<br><br>    const allHeaders = new Headers(<br>      Object.assign(<br>        {<br>          &#39;Content-Type&#39;: contentType,<br>        },<br>        withAuth ? {Authorization: `Bearer ${session?.accessToken}`} : {},<br>        headers,<br>      ),<br>    );<br><br>    const fetchUrl = `${this.baseUrl}${url}${<br>      params &amp;&amp;<br>      &#39;?&#39; +<br>        new URLSearchParams(<br>          Object.entries(params)<br>            // eslint-disable-next-line @typescript-eslint/no-unused-vars<br>            .filter(([_, value]) =&gt; value != null)<br>            .map(([key, value]) =&gt; [key, String(value)]),<br>        ).toString()<br>    }`;<br><br>    const response = await fetch(fetchUrl, {<br>      ...restOptions,<br>      headers: allHeaders,<br>      body: body ? JSON.stringify(body) : undefined,<br>    });<br><br>    if (response.status === 204) {<br>      return null;<br>    }<br><br>    const responseData = await response.json();<br><br>    if (!response.ok) {<br>      throw responseData as ApiResponseError;<br>    }<br><br>    return responseData as ApiResponseWithData&lt;TResponse&gt;;<br>  }<br><br>  public get&lt;TResponse&gt;(url: string, options?: FetchOptions) {<br>    return this.request&lt;TResponse&gt;(url, {method: &#39;GET&#39;, ...options});<br>  }<br><br>  public post&lt;TResponse, TBody&gt;(url: string, options?: FetchOptions&lt;TBody&gt;) {<br>    return this.request&lt;TResponse&gt;(url, {method: &#39;POST&#39;, ...options});<br>  }<br><br>  public put&lt;TResponse, TBody&gt;(url: string, options?: FetchOptions&lt;TBody&gt;) {<br>    return this.request&lt;TResponse&gt;(url, {method: &#39;PUT&#39;, ...options});<br>  }<br><br>  public patch&lt;TResponse, TBody&gt;(url: string, options?: FetchOptions&lt;TBody&gt;) {<br>    return this.request&lt;TResponse&gt;(url, {method: &#39;PATCH&#39;, ...options});<br>  }<br><br>  public delete&lt;TResponse&gt;(url: string, options?: FetchOptions) {<br>    return this.request&lt;TResponse&gt;(url, {method: &#39;DELETE&#39;, ...options});<br>  }<br>}</pre><p>status가 204인 경우에는 서버로부터 아무런 content도 받아오지 않으므로 ApiResponseWithData&lt;TResponse&gt;타입이 아닌 null이어야 한다.<br><strong>함수 오버로드</strong>를 정의해 FetchClient의 제네릭 타입에서 TResponse가 undefined라면 ApiResponseWithData&lt;TResponse&gt; | null을 반환하도록 구현했다.</p><p>인증이 필요한 경우 Auth.js의 auth()를 사용하여 Authorization 헤더에 토큰을 담아 요청한다.</p><p>Auth.js 설정은 아래 설명 글 참고..</p><h4>ApiClient 인스턴스 생성</h4><pre>// src/shared/api/apiClient.ts<br><br>import {FetchClient} from &#39;./fetchClient&#39;;<br><br>const baseUrl =<br>  process.env.NODE_ENV === &#39;production&#39;<br>    ? process.env.API_BASE_URL<br>    : process.env.API_BASE_URL_DEV;<br><br>const apiClient = new FetchClient(baseUrl || &#39;&#39;);<br><br>export default apiClient;</pre><p>Development와 Production 환경을 분리하여 API URL을 주입한다.</p><p>이렇게 ApiClient 인스턴스를 생성하고 데이터 페칭이 필요한 곳에서 해당 인스턴스를 import해서 사용한다.</p><h4>사용 예시</h4><pre>const response = await apiClient.post&lt;<br>  {accessToken: string}, // Response 타입<br>  {refreshToken: string} // body 타입 (get과 delete 메소드에서는 작성할 필요 없음)<br>&gt;(&#39;/auth/refresh&#39;, {<br>  body: {refreshToken: token.refreshToken},<br>  withAuth: true, // 인증이 필요한 API 요청일 경우 추가<br>});</pre><p>apiClient를 통해 인증과 타입 안정성을 갖춘 API 호출을 간편하게 수행할 수 있다.</p><h3>하지만 Fetch Client에서 발생한 문제…</h3><p>만든 Fetch Client를 서버 컴포넌트에서 호출할 때는 문제 없이 동작한다.</p><pre>import apiClient from &#39;@/shared/api/apiClient&#39;;<br>import {isApiResponseError} from &#39;@/shared/api/type&#39;;<br><br>export const getCategories = async () =&gt; {<br>  try {<br>   console.log(apiClient);<br>    const response = await apiClient.get(&#39;/raffles/recent&#39;, {<br>      withAuth: true,<br>    });<br>    return response.data;<br>  } catch (err) {<br>    if (isApiResponseError(err)) {<br>      throw err;<br>    }<br>  }<br>};</pre><pre>// Home<br><br>...<br>export default async function Home() {<br>  const data = await getCategories();<br>  console.log(data);<br>  ...</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CPKUIPjwG4ZFIyXyCEpTJA.png" /></figure><p>FetchClient와 응답이 정상적으로 반환된다.</p><p>하지만 클라이언트 컴포넌트에서 Fetch Client를 통해 API를 호출하게 된다면 아래와 같은 이슈가 발생한다.</p><pre>// Home<br><br>&#39;use client&#39;;<br>...<br>export default function Home() {<br>  const fn = async () =&gt; {<br>    const data = await getCategories();<br>    console.log(data);<br>  };<br>  useEffect(() =&gt; {<br>    fn();<br>  }, []);<br>  ...</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*heFqPFrZzKdqdYY1P4zZjw.png" /></figure><p>FetchClient에 BaseUrl이 초기화되지 않았고 응답결과도 undefined로 나왔다.</p><p>네트워크 탭을 확인해보니 API 요청 자체가 발생하지 않았다.</p><p>API 요청 자체가 발생하지 않은 것이 의아해서 확인해보니 Fetch Client 내부 구현에서 next-auth의 auth() 메소드를 사용하고 있었던 것이 문제였다.</p><pre>// fetchClient.ts<br><br>import {auth} from &#39;../util/auth&#39;;<br>...<br>  private async request&lt;TResponse, TBody = unknown&gt;(<br>    url: string,<br>    options: FetchOptions&lt;TBody&gt;,<br>  ): Promise&lt;ApiResponseWithData&lt;TResponse&gt;&gt; {<br>    const {<br>      withAuth = false,<br>      contentType = &#39;application/json&#39;,<br>      headers,<br>      body,<br>      ...restOptions<br>    } = options;<br>    const session = await auth();<br>    const allHeaders = new Headers(<br>      Object.assign(<br>        {<br>          &#39;Content-Type&#39;: contentType,<br>        },<br>        withAuth ? {Authorization: `Bearer ${session?.accessToken}`} : {},<br>        headers,<br>      ),<br>    );<br>    const response = await fetch(`${this.baseUrl}${url}`, {<br>    ...</pre><p>auth() 는 <strong>서버사이드에서만 동작하는 함수</strong>이므로 클라이언트 컴포넌트에서 요청 시 동작하지 않는다.</p><p>auth()를 제외하고 직접 token을 주입하여 테스트를 해봤다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tcRe80QxVY0_fPYuPZhMvg.png" /></figure><p>API 요청은 동작하나 baseURL이 적용되지 않아서 404 Not Found 에러가 발생한다.</p><h4>baseURL이 적용되지 않는 이유</h4><p>클라이언트 환경에서 환경 변수를 적용하려면 환경 변수 이름에 NEXT_PUBLIC 접두사가 붙어야한다.</p><p>API_BASE_URL 환경 변수를 NEXT_PUBLIC_API_BASE_URL로 수정한다.</p><p>NEXT_PUBLIC이 붙으면 turbo.json에 env를 등록할 필요가 없다.</p><p>환경 변수명을 수정하고 fetchClient 내부 구현사항에서 auth()메소드를 제거한 뒤 클라이언트 컴포넌트에서 API를 호출하면 정상적으로 응답이 온다.</p><h4>그렇다면 FetchClient를 어떻게 분리할까?</h4><p>현재 구현한 Fetch Client는 인증이 필요한 API라면 auth() 메소드를 통해 token값을 헤더에 주입하는 방식으로 구현되어 있다.</p><p>auth()는 서버사이드에서만 동작하므로 클라이언트 사이드의 경우에는 다른 방법이 필요하다.</p><h4>getSession()</h4><p>getSession()을 사용하면 클라이언트 사이드에서 session 정보를 불러올 수 있다고 한다.</p><pre>import {auth} from &#39;../util/auth&#39;;<br>import {getSession} from &#39;next-auth/react&#39;; <br>...<br><br>  private async getSession() {<br>    if (typeof window === &#39;undefined&#39;) {<br>      return auth();<br>    }<br>    return getSession();<br>  }<br>  <br>  private async request&lt;TResponse, TBody = unknown&gt;(<br>    url: string,<br>    options: FetchOptions&lt;TBody&gt;,<br>  ): Promise&lt;ApiResponseWithData&lt;TResponse&gt;&gt; {<br>    const {<br>      withAuth = false,<br>      contentType = &#39;application/json&#39;,<br>      headers,<br>      body,<br>      ...restOptions<br>    } = options;<br>    const session = withAuth ? await this.getSession() : null;<br><br>    const allHeaders = new Headers(<br>      Object.assign(<br>        {<br>          &#39;Content-Type&#39;: contentType,<br>        },<br>        withAuth &amp;&amp; session<br>          ? {<br>              Authorization: `Bearer ${session.accessToken}`,<br>            }<br>          : {},<br>        headers,<br>      ),<br>    );</pre><p>이렇게 하면 원하는대로 동작하지만 클라이언트 사이드에서 인증이 필요한 API를 호출할 시 session 정보를 매번 호출하게 되는데 브라우저 개발자 도구에서 네트워크 탭에 <strong>session 요청 정보가 전부 노출</strong>되게 된다.</p><p>세션 정보는 브라우저 쿠키에 저장되어 있어서 사실 언제든지 노출되어 있지만.. 매번 API 요청할 때 마다 session API가 호출되고 노출되는 것이 찜찜했다.</p><h4>Server Action</h4><p>getSession()은 next-auth v4에서 v5로 업데이트 되면서 auth()로 통합되었다. 지금 사용하는 getSession은 deprecated 되는 것 같다.</p><p>auth()는 서버에서만 동작하므로 <strong>클라이언트에서도 서버 함수를 실행시키기 위해서 서버 액션 함수로 분리</strong>하여 사용한다.</p><p><a href="https://www.heropy.dev/p/MI1Khc#h3_%EC%84%9C%EB%B2%84_%EC%95%A1%EC%85%98_%EA%B5%AC%EC%84%B1">Auth.js(NextAuth.js) 핵심 정리</a></p><pre>// auth/server.ts<br><br>&#39;use server&#39;;<br><br>import {auth, signIn} from &#39;./auth&#39;;<br>import type {z} from &#39;zod&#39;;<br>import type {loginSchema} from &#39;@/widgets/login/config&#39;;<br><br>export const signInWithCredentials = async (<br>  data: z.infer&lt;typeof loginSchema&gt;,<br>) =&gt; {<br>  await signIn(&#39;credentials&#39;, {<br>    email: data.email,<br>    password: data.password,<br>    redirectTo: &#39;/&#39;,<br>  });<br>};<br><br>export {auth as getSession};</pre><p>로그인 함수도 서버 액션으로 분리하여 로그인 페이지에서 사용하도록 분리했다.</p><p>서버액션을 통해서 받아온 auth()를 Fetch Client에서 사용한다.</p><pre>import {getSession} from &#39;../util/auth/server&#39;;<br>...<br><br>private async request&lt;TResponse, TBody = unknown&gt;(<br>    url: string,<br>    options: FetchOptions&lt;TBody&gt;,<br>  ): Promise&lt;ApiResponseWithData&lt;TResponse&gt;&gt; {<br>    const {<br>      withAuth = false,<br>      contentType = &#39;application/json&#39;,<br>      headers,<br>      body,<br>      ...restOptions<br>    } = options;<br>    const session = withAuth ? await getSession() : null;<br>    const allHeaders = new Headers(<br>      Object.assign(<br>        {<br>          &#39;Content-Type&#39;: contentType,<br>        },<br>        withAuth &amp;&amp; session<br>          ? {<br>              Authorization: `Bearer ${session.accessToken}`,<br>            }<br>          : {},<br>        headers,<br>      ),<br>    );<br> ...</pre><p>이제 서버와 클라이언트 사이드 모두 Fetch Client에 접근하여 사용할 수 있다.</p><h3>Auth.js(NextAuth.js)를 사용한 인증 구현하기</h3><p>Wraffle 프로젝트에서는 사용자 인증을 위해 <strong>Auth.js</strong>를 도입했다.<br>Auth.js는 OAuth, 이메일/비밀번호, SMS 등 다양한 인증 방식을 지원하며, 사용자 인증과 세션 관리를 간편하게 처리할 수 있는 라이브러리다.</p><p>아직 베타버전이긴 하나 메이저 버전 업데이트된지 1년 가까이 되었다보니 문서와 레퍼런스가 꽤 많아서 도입해볼만 하다고 느꼈다.</p><p>이전 버전보다 더 간편해진 설정과 인증 관련 훅들이 auth()훅으로 통합되어 편리한 것 같다.</p><p><strong>Auth.js 주요 특징</strong></p><ul><li>OAuth, Credentials(이메일/비밀번호) 등 다양한 Provider 지원</li><li>사용자 세션 관리 및 보안 강화</li></ul><p>Wraffle 프로젝트에서는 추후 OAuth 방식의 로그인을 추가할 계획이지만, 현재는 이메일과 비밀번호를 사용해 백엔드 서버에서 인증을 처리한다. <br>따라서 <strong>Credentials Provider</strong>를 사용하려고 한다.</p><h4>Auth.js 설치</h4><pre>pnpm add next-auth@beta</pre><p>Auth.js를 설치한다. 5버전부터는 Next.js 14버전 이상을 요구한다.</p><h4>AUTH_SECRET 생성</h4><p>터미널에서 다음 명령어를 실행하여 AUTH_SECRET 환경 변수를 생성한다.</p><pre>npx auth secret</pre><p>이 값은 토큰과 이메일 확인 해시를 암호화하는 데 사용된다.</p><h4>TurboRepo 환경 변수 설정</h4><p>AUTH_SECRET과 같은 환경 변수를 TurboRepo에서 사용하려면, turbo.json에 등록해야 한다.</p><pre>// apps/front/wraffle-webview/turbo.json<br><br>{<br>  &quot;$schema&quot;: &quot;https://turbo.build/schema.json&quot;,<br>  &quot;extends&quot;: [&quot;//&quot;],<br>  &quot;tasks&quot;: {<br>    &quot;build&quot;: {<br>      &quot;outputs&quot;: [&quot;.next/**&quot;, &quot;!.next/cache/**&quot;],<br>      &quot;env&quot;: [&quot;AUTH_SECRET&quot;]<br>    }<br>  }<br>}</pre><p><strong>wraffle-webview</strong> 워크스페이스의 turbo.json에서 AUTH_SECRET환경 변수를 env에 등록하여 <strong>해당 워크스페이스에서 독립적으로 사용하는 환경 변수를 선언</strong>한다.</p><p>루트 경로의 turbo.json에서 globalEnv 설정으로는 <strong>모든 작업에서</strong> <strong>공유할 환경 변수</strong>를 관리하고자 할때 사용한다.</p><pre>// /turbo.json<br><br>{<br>  &quot;$schema&quot;: &quot;https://turbo.build/schema.json&quot;,<br>  &quot;globalEnv&quot;: [&quot;NODE_ENV&quot;], // NODE_ENV 환경 변수 정의<br>  &quot;tasks&quot;: {<br>    &quot;build&quot;: {<br>      &quot;dependsOn&quot;: [&quot;^build&quot;],<br>      &quot;inputs&quot;: [&quot;$TURBO_DEFAULT$&quot;, &quot;.env*&quot;]<br>    },<br>    &quot;dev&quot;: {<br>      &quot;cache&quot;: false,<br>      &quot;persistent&quot;: true<br>    },<br>    &quot;format&quot;: {<br>      &quot;cache&quot;: false<br>    }<br>  }<br>}</pre><h4>Auth.js 설정</h4><p>공식 문서의 가이드를 참고하여 기본 설정을 적용한다.</p><pre>// app/api/auth/[...nextauth]/route.ts<br><br>import {handlers} from &#39;@/shared/util/auth&#39;;<br><br>export const {GET, POST} = handlers;</pre><pre>// src/shared/util/auth.ts<br><br>import NextAuth from &quot;next-auth&quot;<br> <br>export const { handlers, signIn, signOut, auth } = NextAuth({<br>  providers: [],<br>})</pre><p>providers를 제외하고는 모두 선택 항목이다.</p><h4>필수 항목: providers</h4><p>providers는 <strong>Credentials</strong>, <strong>Google</strong>, <strong>GitHub</strong> 등 인증 공급자를 설정하는 필수 항목이다.<br>이외에도 선택적으로 설정 가능한 주요 항목은 다음과 같다:</p><ul><li><strong>session</strong>: 세션 관리 방식을 지정.</li><li><strong>pages</strong>: 사용자 정의 페이지 경로 설정. 기본 로그인 페이지 경로는 /auth/signin.</li><li><strong>callbacks</strong>: 인증 및 세션 관리 중 호출되는 핸들러를 정의.</li></ul><h4>주요 콜백</h4><ul><li><strong>callbacks.signIn<br></strong> 로그인 시 호출. true 반환 시 성공, false 반환 시 실패 처리.</li><li><strong>callbacks.redirect<br></strong> 페이지 이동 시 호출. 반환값은 리다이렉션할 URL.</li><li><strong>callbacks.jwt<br></strong> JWT 생성 또는 업데이트 시 호출. 암호화된 토큰은 쿠키에 저장.</li><li><strong>callbacks.session<br></strong> JWT 콜백에서 반환된 token을 기반으로 세션 확인 시 호출.</li></ul><h4>콜백 호출 순서</h4><ul><li>로그인 시: signIn → (redirect) → jwt → session</li><li>세션 업데이트 시: jwt → session</li><li>세션 확인 시: session</li></ul><h4>Credentials Provider 설정</h4><p><strong>Credentials Provider</strong>를 사용해 사용자 인증을 구현했다.</p><pre>providers: [<br>  Credentials({<br>    name: &#39;credentials&#39;,<br>    credentials: {<br>      email: {label: &#39;Email&#39;, type: &#39;email&#39;},<br>      password: {label: &#39;Password&#39;, type: &#39;password&#39;},<br>    },<br>    authorize: async credentials =&gt; {<br>      const validationFields = await loginSchema.safeParseAsync(credentials);<br>      if (!validationFields.success) return null;<br><br>      const {email, password} = validationFields.data;<br><br>      try {<br>        const response = await apiClient.post&lt;Tokens, LoginRequestBody&gt;(<br>          &#39;/auth/login&#39;,<br>          {<br>            body: {email, password},<br>          },<br>        );<br><br>        return response.data;<br>      } catch (error) {<br>        const credentialsSignin = new CredentialsSignin();<br>        if (isApiResponseError(error) &amp;&amp; error.status === 401) {<br>          credentialsSignin.code = error.code;<br>          credentialsSignin.message = error.message;<br>        }<br>        throw credentialsSignin;<br>      }<br>    },<br>  }),<br>],</pre><p><a href="https://authjs.dev/getting-started/authentication/credentials">공식문서</a>에서는 parseAsync(credentials)를 사용해 스키마의 데이터를 비동기적으로 검증하고, catch를 통해 ZodError를 처리한다. <br>그러나 Wraffle 프로젝트의 로그인 페이지에서는 Zod와 React Hook Form으로 유효성 검사를 별도로 수행하며, authorize 함수에서 Zod 에러를 따로 처리하지 않는다.<br>따라서 런타임 에러를 방지하기 위해 safeParseAsync를 사용했다.</p><p>로그인에 실패할 경우(유저가 없거나 비밀번호가 틀린 경우) 어떤 에러가 발생했는지 프론트에 넘겨야 상황에 맞는 메세지를 표시할 수 있다.</p><p>catch를 통해 응답 코드가 401일 경우(Wraffle 프로젝트에서는 보안을 위해 로그인 API의 모든 에러를 고의적으로 401 에러만 반환) <strong>CredentialsSignin 에러를 throw한다.<br></strong>해당 에러를 프론트에서 받으려면 signIn 함수에서 redirect를 true로 설정해주어야한다.</p><pre>const onSubmit = (data: z.infer&lt;typeof loginSchema&gt;) =&gt; {<br>  signIn(&#39;credentials&#39;, {<br>    email: data.email,<br>    password: data.password,<br>    redirect: true // 기본값이 true인 것 같다.<br>    redirectTo: &#39;/&#39;,<br>  });<br>};</pre><p>이렇게 설정하면 로그인 실패 시 페이지가 리다이렉트되면서 쿼리스트링으로 에러 코드가 같이 나오게 된다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*zBA2CxLv6Rsjs8Nnl1Selw.png" /></figure><p>useSearchParams()을 사용하여 에러 코드에 따라 토스트 메세지를 보여주면 된다. (redirect되는 불편함이 있기는 하다.)</p><pre>import {useEffect} from &#39;react&#39;;<br>import {ERROR_STATUS} from &#39;@/shared/util&#39;;<br>import {useToast} from &#39;@wraffle/ui&#39;;<br><br>interface Props {<br>  code: string | null;<br>}<br><br>// useSearchParams()를 통해 페이지에서 code 전달<br>const useLoginToast = ({code}: Props) =&gt; { <br>  const {toast} = useToast();<br><br>  if (!code) return;<br><br>  useEffect(() =&gt; {<br>    switch (code) {<br>      case ERROR_STATUS.NON_EXISTENT_ACCOUNT.code: {<br>        toast({<br>          title: ERROR_STATUS.NON_EXISTENT_ACCOUNT.message,<br>          duration: 2000,<br>          variant: &#39;warning&#39;,<br>          icon: &#39;close&#39;,<br>        });<br>        break;<br>      }<br>      case ERROR_STATUS.MISMATCHED_PASSWORD.code: {<br>        toast({<br>          title: ERROR_STATUS.MISMATCHED_PASSWORD.message,<br>          duration: 2000,<br>          variant: &#39;warning&#39;,<br>          icon: &#39;close&#39;,<br>        });<br>        break;<br>      }<br>      default: {<br>        toast({<br>          title: &#39;로그인에 실패했습니다.&#39;,<br>          duration: 2000,<br>          variant: &#39;warning&#39;,<br>          icon: &#39;close&#39;,<br>        });<br>      }<br>    }<br>  }, []);<br>};<br><br>export default useLoginToast;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*AyEq5jwOQp7vlwvqv9mNKA.png" /></figure><h4>로그인에서 발생한 이슈 (server action)</h4><p>Auth.js에서 Credential Provider의 authorize() 메소드를 실행시키기 위한 로그인 함수인 signIn을 서버액션으로 바꾸면서 발생한 이슈이다.</p><p>기존에는 클라이언트 컴포넌트인 로그인 컴포넌트에서 직접적으로 signIn 메소드를 호출하여 사용했다.</p><pre>import {signIn} from &#39;next-auth/react&#39;;<br>...<br>const onSubmit = (data: z.infer&lt;typeof loginSchema&gt;) =&gt; {<br>  signIn(&#39;credentials&#39;, {<br>    email: data.email,<br>    password: data.password,<br>    redirectTo: &#39;/&#39;,<br>  });<br>};<br><br>return (<br> ...<br> {/* react-hook-form을 사용하기 위한 Form 컴포넌트 */}<br> &lt;GenericForm <br>   onSubmit={onSubmit}<br>   formOptions={{<br>     mode: &#39;onChange&#39;,<br>     resolver: zodResolver(loginSchema),<br>     defaultValues: loginDefaultValues,<br>   }}<br> &gt;<br>   &lt;EmailForm /&gt;<br> &lt;/GenericForm&gt;;<br> ...<br>)</pre><p>signIn을 signInWithCredentials 서버액션 함수로 분리하게 되면서 onSubmit에 signInWithCredentials을 넣어주었다.</p><pre>import {signInWithCredentials} from &#39;@/shared/util/auth/server&#39;<br><br>...<br>return (<br> ...<br> {/* react-hook-form을 사용하기 위한 Form 컴포넌트 */}<br> &lt;GenericForm <br>   onSubmit={signInWithCredentials}<br>   formOptions={{<br>     mode: &#39;onChange&#39;,<br>     resolver: zodResolver(loginSchema),<br>     defaultValues: loginDefaultValues,<br>   }}<br> &gt;<br>   &lt;EmailForm /&gt;<br> &lt;/GenericForm&gt;;<br> ...<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CmpNxZmxSnMRKH6pmSjBzg.png" /></figure><blockquote><strong><em>Error: Only plain objects, and a few built-ins, can be passed to Server Actions. Classes or null prototypes are not supported.</em></strong></blockquote><p>서버 액션 함수는 form의 action 속성에 전달되어야 하는데 react hook form을 사용하고 있기 때문에 action이 아닌 onSubmit에 서버 액션을 적용하고 있어서 해당 에러가 발생했다.</p><p>클라이언트 컴포넌트에서 form action이 아닌 곳에서 서버 액션을 호출하기 위해서 startTransition 을 사용할 수 있다.</p><p>signInWithCredentials 서버 액션 함수를 startTransition으로 감싸주어 사용한다.</p><pre>import {startTransition} from &#39;react&#39;;<br>import {signInWithCredentials} from &#39;@/shared/util/auth/server&#39;;<br>...<br>const onSubmit = (data: z.infer&lt;typeof loginSchema&gt;) =&gt; {<br>  startTransition(async () =&gt; {<br>    await signInWithCredentials(data);<br>  });<br>};<br><br>return (<br> ...<br> {/* react-hook-form을 사용하기 위한 Form 컴포넌트 */}<br> &lt;GenericForm <br>   onSubmit={onSubmit}<br>   formOptions={{<br>     mode: &#39;onChange&#39;,<br>     resolver: zodResolver(loginSchema),<br>     defaultValues: loginDefaultValues,<br>   }}<br> &gt;<br>   &lt;EmailForm /&gt;<br> &lt;/GenericForm&gt;;<br> ...<br>)</pre><p>로그인에 성공했을 때는 문제없이 동작하지만 로그인에 실패하여 서버에서 에러를 던져줄때 문제가 생겼다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sWYB-VfXRAsGWOPTWyd2PA.png" /></figure><p>기존엔 Auth.js의 authorize()에서 throw하는 CredentialSignIn 에러를 페이지가 리다이렉트 되면서 쿼리스트링으로 전달되는 에러 코드로 토스트 메세지를 띄우는 방식으로 구현했지만.. 중간에 서버액션이 생기면서 Auth.js에서 던져주는 에러를 클라이언트가 아닌 서버 응답으로 에러를 던져주고 있다.</p><p>그렇기 때문에 클라이언트 페이지에서도 페이지 리다이렉션이 일어나지 않고 에러를 내뱉고 있는 것 같다고 생각했다.</p><p>쿼리 파라미터로 전달된 code로 토스트 메세지를 보여주는 방식 대신에 서버에서 응답으로 오는 message를 토스트로 보여주는 방식으로 변경한다.</p><pre>const onSubmit = (data: z.infer&lt;typeof loginSchema&gt;) =&gt; {<br>  startTransition(async () =&gt; {<br>    try {<br>      await signInWithCredentials(data);<br>    } catch (error) {<br>      toast({<br>        title: (error as Error).message,<br>        duration: 2000,<br>        variant: &#39;warning&#39;,<br>        icon: &#39;close&#39;,<br>      });<br>    }<br>  });<br>};</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*fPUMg_oFwnmhtKc5xGafHw.png" /></figure><h4>사용자 정의 타입 추가</h4><p>next-auth 기본 타입에 없는 accessToken과 refreshToken을 다음과 같이 확장했다.</p><pre>// src/entities/auth/auth.d.ts<br><br>export declare module &#39;next-auth&#39; {<br>  interface User {<br>    accessToken: string;<br>    refreshToken: string;<br>  }<br>  interface Session {<br>    accessToken: string;<br>    refreshToken: string;<br>  }<br>}<br>export declare module &#39;@auth/core/jwt&#39; {<br>  interface JWT {<br>    accessToken: string;<br>    refreshToken: string;<br>    accessTokenExpires: number;<br>  }<br>}</pre><h4>콜백 구성</h4><p>callbacks.jwt와 callbacks.session에서 토큰을 관리하고 세션 데이터를 반환한다.</p><pre>callbacks: {<br>  async jwt({ token, user }) {<br>    if (user) {<br>      token.accessToken = user.accessToken;<br>      token.refreshToken = user.refreshToken;<br>      token.accessTokenExpires = Date.now() + ACCESS_TOKEN_EXPIRES_IN * 1000;<br>    }<br><br>if (Date.now() &lt; token.accessTokenExpires) {<br>      return token;<br>    }<br>    return await refreshAccessToken(token);<br>  },<br>  async session({ session, token }) {<br>    session.accessToken = token.accessToken;<br>    session.refreshToken = token.refreshToken;<br>    return session;<br>  },<br>},</pre><h4>토큰 갱신</h4><p>토큰이 만료되면 refreshAccessToken 함수로 새로운 accessToken을 발급받는다.</p><h4>Middleware 설정: 로그인 상태에 따른 페이지 접근 제한</h4><p>로그인 상태에 따라 페이지 접근을 제한하기 위해 <strong>Middleware</strong>를 사용하여 인증 로직을 구현했다.</p><p>이를 통해 인증이 필요한 페이지에 접근할 때 로그인 여부를 확인하고 로그인 상태에 맞는 리다이렉션을 처리할 수 있다.</p><h4>middleware.ts 설정</h4><pre>// middleware.ts<br><br>import type {NextRequest} from &#39;next/server&#39;;<br>import {NextResponse} from &#39;next/server&#39;;<br>import {getSession} from &#39;@/shared/util/auth/server&#39;;<br><br>const PUBLIC_ROUTES = [&#39;/login&#39;, &#39;/join&#39;];<br>const LOGIN = &#39;/login&#39;;<br>const MAIN = &#39;/&#39;;<br><br>export async function middleware(req: NextRequest) {<br>  const {nextUrl} = req;<br>  const session = await getSession();<br><br>  const isAuthenticated = !!session;<br><br>  const isPublicRoute = PUBLIC_ROUTES.find(route =&gt;<br>    nextUrl.pathname.startsWith(route),<br>  );<br><br>  if (isAuthenticated &amp;&amp; isPublicRoute) {<br>    return NextResponse.redirect(new URL(MAIN, req.url));<br>  }<br><br>  if (!isAuthenticated &amp;&amp; !isPublicRoute) {<br>    return NextResponse.redirect(new URL(LOGIN, nextUrl));<br>  }<br><br>  return NextResponse.next();<br>}<br><br>export const config = {<br>  matcher: [&#39;/((?!api|_next/static|_next/image|.*\\.png$).*)&#39;],<br>};</pre><p>config matcher에 정규표현식을 사용하여 api나 _next/static 등의 특정 경로에서는 미들웨어가 호출되지 않도록 설정했다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*qgpHUssgvC8GVR-zgBNQJg.png" /></figure><p>참고자료</p><p><a href="https://authjs.dev/getting-started">https://authjs.dev/getting-started</a></p><p><a href="https://www.heropy.dev/p/MI1Khc">https://www.heropy.dev/p/MI1Khc</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6fe9b1062bc2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/wraffle-tech/fetch-api-client%EC%99%80-auth-js-nextauth-js-%EB%A5%BC-%EC%82%AC%EC%9A%A9%ED%95%9C-%EC%9D%B8%EC%A6%9D-%EA%B5%AC%ED%98%84%ED%95%98%EA%B8%B0-6fe9b1062bc2">Next.js에서 확장성을 고려한 Fetch API Client와 Auth.js를 사용한 인증 구현하기</a> was originally published in <a href="https://medium.com/wraffle-tech">Wraffle-Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>