<?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 Teawon on Medium]]></title>
        <description><![CDATA[Stories by Teawon on Medium]]></description>
        <link>https://medium.com/@teawon.jeong.dev?source=rss-d580fa80743e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*qBinclOdxLq76LHz</url>
            <title>Stories by Teawon on Medium</title>
            <link>https://medium.com/@teawon.jeong.dev?source=rss-d580fa80743e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 03:52:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@teawon.jeong.dev/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[복잡한 분기처리, 의사결정 테이블 형태로 표현하기]]></title>
            <link>https://blog.techeer.net/%EB%B3%B5%EC%9E%A1%ED%95%9C-%EB%B6%84%EA%B8%B0%EC%B2%98%EB%A6%AC-%ED%85%8C%EC%9D%B4%EB%B8%94-%ED%98%95%ED%83%9C%EB%A1%9C-%ED%91%9C%ED%98%84%ED%95%98%EA%B8%B0-71137db790e8?source=rss-d580fa80743e------2</link>
            <guid isPermaLink="false">https://medium.com/p/71137db790e8</guid>
            <category><![CDATA[swtich]]></category>
            <category><![CDATA[if]]></category>
            <category><![CDATA[trie]]></category>
            <category><![CDATA[condition]]></category>
            <dc:creator><![CDATA[Teawon]]></dc:creator>
            <pubDate>Sat, 17 May 2025 15:46:21 GMT</pubDate>
            <atom:updated>2025-05-17T16:20:35.971Z</atom:updated>
            <content:encoded><![CDATA[<h3>개요</h3><p>개발을 진행하다 보면 다양한 케이스에 따른 분기 처리가 빈번하게 발생합니다.</p><p>대부분의 경우 if문이나 switch문을 사용해 해결하곤 하지만, 조건이 복잡해지고 중첩이 깊어질수록 가독성 저하와 유지보수의 어려움이 뒤따르게 됩니다.</p><p>이러한 문제점에 직면했을때, 복잡한 조건문을 더욱 직관적이고 유지보수하기 쉬운 구조로 개선하고 고민했던 과정에 대해 소개시켜드리려고 합니다.</p><h3>배경</h3><p>사내에서는 클라우드 자원을 화면에 표현할 때, 여러 내부 시스템의 상태값을 조합하여 최종적으로 UI에 보여줄 상태로 매핑해야 합니다.</p><p>하지만 실제로는 각 자원의 내부 상태와 다양한 속성들이 복합적으로 얽혀 있어, 이 상태 매핑 로직이 매우 복잡하게 구성될 수밖에 없었습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MozkFqm3A1Nsie8tJ2mN8w.png" /><figcaption>각 상태값에 따른 정책 내용의 일부분을 재구성한 내용</figcaption></figure><p>초기 개발 단계에서는 단순히 반복되는 규칙을 찾고, if 문으로 그룹화하여 조건을 처리했습니다.</p><pre>if (status2 === &quot;A_&quot;) {<br>  return {<br>    cluster: stateMap.error,<br>    node: stateMap.error,<br>  };<br>}<br><br>if (status1 === &quot;A&quot;) {<br>  return {<br>    cluster: stateMap.creating,<br>    node: stateMap.creating,<br>  };<br>}<br><br>if (status1 === &quot;B&quot;) {<br>  if (status2 === &quot;H_&quot;) {<br>    return {<br>      cluster: stateMap.creating,<br>      node: stateMap.creating,<br>    };<br>  }<br><br>  if (status2 === &quot;D_&quot;) {<br>    return {<br>      cluster: stateMap.error,<br>      node: stateMap.error,<br>    };<br>  }<br><br>  if (status2 === &quot;F_&quot;) {<br>    return {<br>      cluster: stateMap.deleting,<br>      node: stateMap.deleting,<br>    };<br>  }<br><br>  { ... }<br><br><br>  // 조기리턴을 통해 위 조건에 해당하지 않는 모든 케이스를 일괄 처리<br>  // =&gt; 그래서 어떤 케이스들이 있는데? (조건식 분석 필요)<br>  return {<br>    cluster: stateMap.normal,<br>    node: stateMap.normal,<br>  };<br>}<br><br>return {<br>  cluster: stateMap.no_defined,<br>  node: stateMap.no_defined,<br>};<br>```</pre><p>그런데 위 코드는 아래와 같은 문제점이 있었습니다.</p><ol><li>중첩된 if문 로직에 의해 코드 가독성이 떨어집니다.</li><li>중복된 로직 처리가 개발자의 해석에 의존하기 때문에, 코드에 반영된 로직을 직관적으로 이해하기 어려웠습니다.</li><li>조건이 누락되거나, 예외 케이스(Edge Case)가 발생했을 때 디버깅이 어려웠으며, 중첩된 로직을 일일이 추적해야만 원인을 파악할 수 있었습니다.</li><li>반복을 감안하고 모든 케이스를 정의하는 방법도 있지만 코드가 길어지는 문제가 있습니다.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rNFn9bRM3A_gcq6EsjyIJg.png" /><figcaption>if문 중첩 내부에서 case4는 위 예시의 else문에 해당합니다. 해당 케이스에 어떤 요소들이 있는지 확인하기 위해서는 상위 if문 블록부터 타고 들어야 확인해야하는 번거로움이 있습니다.</figcaption></figure><p>이러한 조건식을 보다 직관적이고 이해하기 쉽게 표현하도록 어떻게 개선할 수 있을까요?</p><h3>개선</h3><p>복잡한 조건문 대신, 각 케이스에 대해 정의된 <strong>의사 결정 테이블(Decision Table)</strong> 형태로 표현한다면 이러한 문제를 해결할 수 있다고 생각했습니다.</p><blockquote>의사결정 테이블이란?</blockquote><blockquote>다양한 조건 조합에 따른 결과를 표 형태로 명확하게 정의하는 방법입니다.</blockquote><blockquote>조건이 많아질수록 복잡해지는 if-else 구조를 간단한 매핑 테이블로 대체할 수 있습니다.</blockquote><p>결국 위 로직은 정책 명세서를 기반으로 케이스를 분리하여 처리하고 있습니다.</p><p>이러한 정책 역시 테이블 형태로 정의되어있으니, 정책 명세서의 구조에 맞춰 코드에 반영한다면, 각 케이스의 조건과 결과를 보다 직관적으로 확인할 수 있습니다.</p><pre>// pseudo code<br>const decisionTable = [<br>  [[&quot;A1&quot;, &quot;B1&quot;, &quot;C1&quot;], &quot;a&quot;],<br>  [[&quot;A2&quot;, &quot;B2&quot;, &quot;C2&quot;], &quot;b&quot;],<br>  [[&quot;A3&quot;, &quot;*&quot;, &quot;*&quot;], &quot;c&quot;],<br>];<br><br>getResult(decisionTable, A, B, C); // &quot;a&quot;</pre><p>아이디어는 간단합니다. 사전에 정의한 상태 값에 매칭되는 케이스를 찾아, 그에 맞는 결과 값을 반환합니다.</p><pre>const WILD_SYMBOL = &quot;*&quot;;<br><br>type WithWildcard&lt;T&gt; = T | typeof WILD_SYMBOL;<br><br>export type Mapping&lt;I extends readonly unknown[], T&gt; = {<br>  key: { [K in keyof I]: WithWildcard&lt;I[K]&gt; };<br>  result: T | undefined;<br>};</pre><ul><li>*는 어떤 값이 와도 매칭될 수 있는 와일드카드입니다. <br>(조건을 신경쓰지 않고 넘어가도록 처리)</li><li>Mapping은 조건(Key)과 결과(Result)를 정의하는 타입입니다.</li><li>외부에서 다양한 타입을 Generic으로 전달받을 수 있도록 타입을 정의합니다.</li></ul><pre>export const createDecisionTable = &lt;TKey extends unknown[], TResult&gt;(<br>  mappings: Mapping&lt;TKey, TResult&gt;[]<br>) =&gt; {<br>  return (...inputs: [...TKey]): TResult | undefined =&gt; {<br>    //  모든 매핑된 케이스를 순회<br>    outer: for (const mapping of mappings) {<br>      for (let i = 0; i &lt; inputs.length; i++) {<br>        const keyPart = mapping.key[i];<br>        const inputPart = inputs[i];<br><br>        // 🛑 조건 불일치 시 다음 케이스로 넘어감<br>        if (keyPart !== WILD_SYMBOL &amp;&amp; keyPart !== inputPart) continue outer;<br>      }<br>      // 모든 조건이 만족되면 결과 반환<br>      return mapping.result;<br>    }<br>    return undefined;<br>  };<br>};</pre><ul><li>매핑 정보를 받고, 이를 활용한 결정 로직을 가진 함수를 반환하는 고차함수 형태로 처리합니다</li></ul><pre><br>type InputStatus = [Status1Type, Status2Type, Status3Type];<br>type ResultStatus = {<br>  cluster: statusType;<br>  node: statusType;<br>};<br><br>const statusMappings: Mapping&lt;InputStatus, ResultStatus&gt;[] = [<br>  { key: [&quot;*&quot;, &quot;A_&quot;, &quot;*&quot;], result: { cluster: &quot;error&quot;, node: &quot;error&quot; } },<br>  { key: [&quot;A&quot;, &quot;*&quot;, &quot;*&quot;], result: { cluster: &quot;creating&quot;, node: &quot;creating&quot; } },<br>  { key: [&quot;B&quot;, &quot;B_&quot;, &quot;f&quot;], result: { cluster: &quot;normal&quot;, node: &quot;no_defined&quot; } },<br>  { key: [&quot;B&quot;, &quot;B_&quot;, &quot;g&quot;], result: { cluster: &quot;normal&quot;, node: &quot;error&quot; } },<br>  { key: [&quot;B&quot;, &quot;B_&quot;, &quot;h&quot;], result: { cluster: &quot;normal&quot;, node: &quot;error&quot; } },<br>  { key: [&quot;B&quot;, &quot;B_&quot;, &quot;e&quot;], result: { cluster: &quot;normal&quot;, node: &quot;deleting&quot; } },<br>  { key: [&quot;B&quot;, &quot;B_&quot;, &quot;*&quot;], result: { cluster: &quot;normal&quot;, node: &quot;normal&quot; } },<br>  { key: [&quot;B&quot;, &quot;C_&quot;, &quot;f&quot;], result: { cluster: &quot;normal&quot;, node: &quot;no_defined&quot; } },<br>  { key: [&quot;B&quot;, &quot;C_&quot;, &quot;g&quot;], result: { cluster: &quot;normal&quot;, node: &quot;error&quot; } },<br>  { key: [&quot;B&quot;, &quot;C_&quot;, &quot;h&quot;], result: { cluster: &quot;normal&quot;, node: &quot;error&quot; } },<br>  { key: [&quot;B&quot;, &quot;C_&quot;, &quot;e&quot;], result: { cluster: &quot;normal&quot;, node: &quot;deleting&quot; } },<br>  { key: [&quot;B&quot;, &quot;C_&quot;, &quot;*&quot;], result: { cluster: &quot;normal&quot;, node: &quot;normal&quot; } },<br>  { ... }<br>];<br><br><br>const getStatusResult = createDecisionTable(statusMappings);<br>const result = getStatusResult(status1, status2, node);</pre><ul><li>createDecisionTable로 생성된 getStatusResult는 입력받은 상태 값과 정의된 매핑 정보를 순회하며 매칭 여부를 확인합니다.</li><li>매칭된 결과가 있으면 해당 값을 반환하고, 없으면 undefined를 반환합니다.</li></ul><p>그러나, 현재 로직은 입력받은 상태 값을 기준으로 모든 매핑 정보를 순회하며 매칭 여부를 확인하는 구조입니다.</p><p>즉, N개의 케이스가 정의되어 있을 때, <strong>최대 O(N)</strong>의 순회가 발생합니다.</p><p>이는 케이스의 개수가 많아질수록 탐색 시간이 선형적으로 증가하는 문제를 야기합니다.</p><p>따라서 매핑 정보가 많아질수록 성능 저하가 발생할 수 있습니다.</p><p>이 문제를 해결하기 위해 계층적 탐색이 가능한<strong> Trie(트라이) </strong>자료구조를 활용했습니다.</p><h4>성능 개선</h4><p>Trie는 문자열이나 키 조합을 효율적으로 관리하기 위한 트리 형태의 자료구조입니다.</p><p>예를 들어, 다음과 같은 키 조합이 있다고 가정한다면 Trie로 표현했을때 다음과 같은 구조를 가지게됩니다.</p><pre><br>[&quot;*&quot;, &quot;A_&quot;, &quot;*&quot;] { cluster: &quot;error&quot;, node: &quot;error&quot; }<br>[&quot;A&quot;, &quot;*&quot;, &quot;*&quot;]   { cluster: &quot;creating&quot;, node: &quot;creating&quot; }<br>[&quot;B&quot;, &quot;B_&quot;, &quot;*&quot;] { cluster: &quot;normal&quot;, node: &quot;normal&quot; }<br><br><br>root<br> ├── *<br> │   └── A_<br> │       └── *<br> │           └── ✨ { cluster: &quot;error&quot;, node: &quot;error&quot; }<br> ├── A<br> │   └── *<br> │       └── *<br> │           └── ✨ { cluster: &quot;creating&quot;, node: &quot;creating&quot; }<br> └── B<br>     └── B_<br>         └── *<br>             └── ✨ { cluster: &quot;normal&quot;, node: &quot;normal&quot; }<br></pre><p>즉, 접두사 단위로 트리 노드를 이동하며 모든 매핑을 순회하지 않고 키의 길이에 해당하는 필요한 경로만 우선적으로 탐색하게됩니다.</p><p>구현을 위해 먼저, Trie의 기본 단위인 TrieNode와 이를 관리하는 Trie 클래스를 정의합니다.</p><pre>class TrieNode&lt;TResult&gt; {<br>  children: Map&lt;string, TrieNode&lt;TResult&gt;&gt;;<br>  result: TResult | null;<br><br>  constructor() {<br>    this.children = new Map();<br>    this.result = null;<br>  }<br>}<br><br>class Trie&lt;TResult&gt; {<br>  root: TrieNode&lt;TResult&gt;;<br><br>  constructor() {<br>    this.root = new TrieNode&lt;TResult&gt;();<br>  }<br><br>  //  키 등록<br>  insert(keyParts: string[], result: TResult) {<br>    let currentNode = this.root;<br><br>    for (const part of keyParts) {<br>      if (!currentNode.children.has(part)) {<br>        currentNode.children.set(part, new TrieNode&lt;TResult&gt;());<br>      }<br>      currentNode = currentNode.children.get(part)!;<br>    }<br>    currentNode.result = result;<br>  }<br><br>  //  키 탐색<br>  search(keyParts: string[]): TResult | undefined {<br>    return this._searchRecursive(this.root, keyParts, 0);<br>  }</pre><p>이어서, 와일드카드(*)에 대한 탐색을 지원하기 위해, 재귀적으로 탐색을 진행하며 자식 노드를 방문합니다.</p><pre>//  재귀 탐색 (와일드카드 포함)<br>private _searchRecursive(<br>  node: TrieNode&lt;TResult&gt;,<br>  keyParts: string[],<br>  index: number<br>): TResult | undefined {<br>  if (index === keyParts.length) {<br>    return node.result ?? undefined;<br>  }<br><br>  const part = keyParts[index];<br><br>  for (const [childKey, childNode] of node.children) {<br>    if (childKey === part || childKey === WILD_SYMBOL) {<br>      const res = this._searchRecursive(childNode, keyParts, index + 1);<br>      if (res !== undefined) return res;     // 첫 매칭 결과 즉시 반환<br>    }<br>  }<br>  return undefined;<br>}</pre><pre>onst createDecisionTable = &lt;TKey extends string[], TResult&gt;(<br>  mappings: Mapping&lt;TKey, TResult&gt;[]<br>) =&gt; {<br>  const trie = new Trie&lt;TResult&gt;();<br><br>  //  Trie에 모든 매핑을 등록<br>  for (const mapping of mappings) {<br>    trie.insert(mapping.key, mapping.result);<br>  }<br><br>  //  검색 함수 반환<br>  return (...inputs: [...TKey]): TResult | undefined =&gt; {<br>    return trie.search(inputs);<br>  };<br>};</pre><p>Trie자료구조를 통해 <strong>키의 각 부분(상태값)</strong>을 계층적으로 분기하여 저장하고 탐색 시에는 각 상태값에 해당하는 분기만 따라갈 수 있도록 개선되었습니다.</p><p>즉 <strong>O(N)이 아니라 O(K) </strong>(K=키의 길이, 즉 상태값의 개수)로 탐색 성능을 향상시킬 수 있었습니다.</p><blockquote>처음 구조를 생성할때에는 O(N * K)의 시간복잡도를 가지지만, 테이블은 처음 생성 후 조건문에서 반복문으로 사용하므로 탐색이 반복되는 위 구조에서는 유리한 이점을 가져올 수 있습니다.</blockquote><h3>결론</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*dNBSSuz3f_RbhQ5tU29WNw.gif" /><figcaption>수정 변경 사항 before / after</figcaption></figure><p>결과적으로 복잡한 if 문을 객체 기반 매핑 테이블로 재구성함으로써, 각 케이스를 더욱 빠르고 직관적으로 조회할 수 있는 구조로 개선할 수 있었습니다.</p><p>물론, if 문이나 switch 문에서도 모든 케이스를 정의한다는 관점으로 접근했을때 동일하게 처리할 수 있지만, 코드가 길어지고 복잡해져 가독성이 떨어진다는 단점이 있습니다.</p><p>반면, 객체 매핑 방식은 상태와 결과를 명확하게 정의하기 때문에, 개발 중 매핑 정보가 변경되더라도 해당 상태값이 어떤 결과를 반환할지 쉽게 파악할 수 있습니다.</p><p>덕분에 디버깅 시간도 단축되었으며, 케이스 분기가 많아질수록 그 유용성이 더욱 두드러지는 구조라고 생각합니다. 😄</p><p><strong>참고자료</strong></p><p><a href="https://en.wikipedia.org/wiki/Radix_tree">Trie</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71137db790e8" width="1" height="1" alt=""><hr><p><a href="https://blog.techeer.net/%EB%B3%B5%EC%9E%A1%ED%95%9C-%EB%B6%84%EA%B8%B0%EC%B2%98%EB%A6%AC-%ED%85%8C%EC%9D%B4%EB%B8%94-%ED%98%95%ED%83%9C%EB%A1%9C-%ED%91%9C%ED%98%84%ED%95%98%EA%B8%B0-71137db790e8">복잡한 분기처리, 의사결정 테이블 형태로 표현하기</a> was originally published in <a href="https://blog.techeer.net/">Techeer Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Observer Pattern 기반의 에러핸들링 로직 구현하기]]></title>
            <link>https://blog.techeer.net/observer-pattern-%EA%B8%B0%EB%B0%98%EC%9D%98-%EC%97%90%EB%9F%AC%ED%95%B8%EB%93%A4%EB%A7%81-%EB%A1%9C%EC%A7%81-%EA%B5%AC%ED%98%84%ED%95%98%EA%B8%B0-ec99320f732d?source=rss-d580fa80743e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec99320f732d</guid>
            <category><![CDATA[observer-pattern]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Teawon]]></dc:creator>
            <pubDate>Fri, 28 Mar 2025 03:22:52 GMT</pubDate>
            <atom:updated>2025-03-28T08:32:35.630Z</atom:updated>
            <content:encoded><![CDATA[<p>혹시 개발을 진행하며 아래의 에러에 마주하신 경험이 있으신가요?</p><blockquote>“React Hooks must be called in a React function component or a custom React Hook function”</blockquote><p>이 에러는 React Hooks 규칙을 위반할때 발생합니다.</p><p>대체로 이런 에러를 마주하면, React Hooks의 규칙을 준수하도록 코드를 수정하거나, 아예 Hooks를 사용하지 않는 방식으로 문제를 해결합니다.</p><p>하지만 Hooks을 꼭 사용해야만 하는 상황이 있다면 어떤식으로 우회해야할까요?</p><p>이 글에서는 React Hooks의 제약으로 인한 문제를 해결하기 위해 Observer Pattern을 활용한 사례 및 상태 변경을 관찰하고 이벤트를 중앙에서 관리하는 미들웨어 로직을 구현하는 방법과 그 과정에서 고려해야 했던 주요 사항들을 소개합니다.</p><h3>배경</h3><p>React에서는 다양한 방법으로 에러를 전역적으로 핸들링하고 관리할 수 있습니다.</p><p>예를 들어, axios를 사용하는 경우 interceptor를 활용해 공통 에러 처리 로직을 정의할 수 있으며 React Query에서는 queryClient를 통해 에러 핸들링 로직을 전역적으로 관리할 수 있습니다.</p><p>그런데, 다음과 같은 요구사항을 구현해야한다면 어떻게 해야할까요?</p><blockquote><strong><em>1. 일부 API 요청이 실패했을 때, 사용자에게 Modal을 띄워 알린다. <br>(=특정 에러 코드가 반환 되었을 때)</em></strong></blockquote><blockquote><strong><em>2. Modal에서 특정 로직(예: 사용자 확인, 추가 입력 등)을 수행한다</em></strong></blockquote><blockquote><strong><em>3. 정상적으로 수행했다면 기존에 실패했던 api 요청을 재시도 한다.</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*IPG_w2hozbkfPELG3aJSAw.gif" /><figcaption>(예시 상황) 서버에서 너무 많은 요청을 보내면 에러를 발생시키고 사용자 확인을 통해 재시도 로직을 수행</figcaption></figure><p>Modal은 React의 상태(useState , useContext…)에 의해 의존해 관리되어야 합니다.</p><p>위에서 사례로 언급한 interceptor , queryClient은 React 컴포넌트 외부에서 동작하는 순수 함수의 성격을 가지고 있어 모달을 띄우려면 React 컴포넌트 트리 내부에서 반드시 상태가 제어되어야합니다.</p><pre>// Axios Interceptor<br>axios.interceptors.response.use(<br>  (response) =&gt; response,<br>  (error) =&gt; {<br>    // 여기서 React 상태를 사용해 모달을 열 수 없음 ❌<br>    if (shouldShowModal(error)) {<br>      // 모달을 띄우고 재시도 로직 실행 필요<br>    }<br>    return Promise.reject(error);<br>  }<br>);</pre><pre>// React-query QueryClient<br>const queryClient = new QueryClient();<br>queryClient.setDefaultOptions({<br>  queries: {<br>    onError: (error) =&gt; {<br>      // 여기서 React 상태를 사용해 모달을 열 수 없음 ❌<br>      if (shouldShowModal(error)) {<br>        // 모달을 띄우고 재시도 로직 실행 필요<br>      }<br>    },<br>  },<br>});</pre><blockquote>&gt;React의 렌더링 사이클과 무관하게 실행되는 위 로직 내부에 React 상태나 컴포넌트 라이프사이클에 의존하는 로직을 직접 적용할 수 없다.</blockquote><h3>해결 방안 모색</h3><p>결국 위와 같은 문제를 해결하기 위해 3가지 방법을 고려해볼 수 있었습니다.</p><ol><li>전역으로 핸들링하지않고 각 사용처에서 개별적인 에러 로직 처리</li><li>전역 핸들링 로직을 React Hooks 형태로 변경</li><li>중간 계층을 두고 외부 함수와 React 로직을 분리</li></ol><p><strong>개별 처리</strong></p><p>첫번째 방법은 각 API 호출하는 로직에서 직접 에러를 처리하고 모달을 제어하는 방식입니다.</p><pre>const MyComponent1 = () =&gt; {<br><br>  const { open } = useModal();<br><br>  const { mutate } = useMutation({<br>    mutationFn: () =&gt; {...}<br>    onError: (error) =&gt; {<br>      if (shouldShowModal(error)) {<br>        open();<br>      }<br>      { ... }<br>    },<br>  });<br><br>  return &lt;Page /&gt;;<br>};<br><br>const MyComponent2 = () =&gt; { ... };</pre><p>이 방법은 가장 직관적이며, 에러 발생 지점을 명확히 파악할 수 있다는 장점이 있습니다.</p><ul><li>명확한 책임 분리 (사용범위가 명확함)</li><li>추후 복잡한 비즈니스 로직 추가에 대한 각 로직의 맞춤형 처리가 가능</li></ul><p>그러나 이 방식은 에러가 발생할 수 있는 모든 API의 관계를 파악해야 하며, 코드량이 많아질수록 <strong>코드 중복과 유지보수의 어려움</strong>이 명확하게 드러납니다.</p><ul><li>호출 지점에 대한 관리 포인트가 증가</li><li>코드 중복 및 유지보수 어려움</li><li>핸들링 로직을 별도의 함수로 분리해 공통으로 사용하더라도 결국에는 전역 처리의 단점을 가진 채 관리 비용만 증가</li><li>현 요구사항은 반환되는 에러 코드값을 기준으로 처리하기때문에 복잡한 커스텀 기능이 요구되는 기능사항이 아님</li></ul><p><strong>2. hook으로 수정</strong></p><p>모달을 제어하는 로직(Hooks)을 사용할 수 없다면, 전역 핸들링 로직을 커스텀 훅 형태로 확장하는 방법을 고려할 수 있습니다.</p><p>이 방식은 Axios Interceptor를 커스텀 훅으로 감싸 React 상태와 연동하여 공통 에러 처리 로직을 한 곳에서 관리하는 접근법입니다.</p><pre>export const useAxiosInterceptor = () =&gt; {<br><br>  useEffect(() =&gt; {<br>    const interceptor = axios.interceptors.response.use(<br>      (response) =&gt; response,<br>      (error) =&gt; {<br>        if (shouldShowModal(error)) {<br>          openModal();<br>        }<br>        return Promise.reject(error);<br>      }<br>    );<br><br>    return () =&gt; axios.interceptors.response.eject(interceptor);<br>  }, []);</pre><pre>// 최상단 Layout에 해당 요소 선언<br>function App() {<br>  useAxiosInterceptor();<br><br>  return {...}<br>}</pre><p>이 방법의 장점은 공통 로직을 한 곳에서 관리할 수 있다는 점입니다.</p><p>동일한 에러 처리 로직이 전체 애플리케이션에 일관되게 적용되어 중복 코드를 제거하고 유지보수 효율성을 높일 수 있습니다.</p><p>하지만 이러한 접근법에는 다음과 같은 한계가 있었습니다</p><ol><li>React와의 강한 의존성</li></ol><ul><li>훅이 마운트된 컴포넌트(예: App)에서만 인터셉터가 활성화됨</li><li>이 로직을 재사용하려면 반드시 React 컴포넌트로 감싸져야 함</li></ul><p>2. 환경 격리</p><ul><li>테스트 코드를 작성하기 어려움</li></ul><p>결국 어떠한 로직이 React Hooks에 강하게 결합된 구조를 가지게 된다면 추후 해당 로직은 결국 React 컴포넌트 내부에서만 동작할 수 있는 제한성을 가지며 이는 다른 라이브러리 도입 및 기능 확장 시 <strong>해당 로직을 분리하거나 재사용하기 어려운 문제</strong>에 직면하게 만듭니다.</p><p>더욱이 해당 구조를 사용한다면 기존 코드베이스의 형태를 Hooks형태로 수정하는 작업이 필연적으로 발생해 명확한 한계점이 있다고 생각했습니다.</p><blockquote>React와의 강한 의존성이 가지는 문제 예시</blockquote><pre>export const Route = createFileRoute(&quot;NeedErrorHandlePageRange&quot;)({<br>  beforeLoad: () =&gt; {<br>    // 에러 핸들링 로직을 여기에서 사용하고 싶음<br>    errorHandleLogic(); // ✅<br>    // errorHandleLogicWithHooks(); // ❌<br>  },<br>  component: () =&gt; {<br>    return &lt;SubLayout /&gt;;<br>  },<br>});</pre><p>tanstack router 라이브러리에서는 각 페이지 단위로 렌더링 이전에 특정 로직을 수행시킬 수 있는 beforeLoad 기능을 사용할 수 있습니다.</p><p>요구사항이 변경되어 페이지 단위로 이러한 로직을 적용하고 싶다면 어떻게 될까요?</p><p>만약 해당 로직이 Hooks 형태로 엮여 있다면, 그 로직을 분리하여 조건부로 적용하는 것이 어려워질 수 있습니다.</p><p>즉 특정 로직을 필요에 따라 유연하게 사용하거나 수정하기에 어려움이 발생할 수 있는거죠.</p><p><strong>3. React 로직의 분리</strong></p><p>해결 방안의 마지막으로, 중간 계층을 도입하여 외부 함수와 React 로직을 분리하는 방식을 고려하였습니다.</p><p>핵심 아이디어는 React 외부의 순수 함수 영역과 React 내부의 상태 관리 로직을 명확하게 분리하는 것입니다.</p><ol><li>순수 함수 영역</li></ol><ul><li>에러 핸들링 로직을 React와 완전히 분리된 순수 함수로 구현합니다</li></ul><p>2. 관찰자 컴포넌트</p><ul><li>상태 변경을 감지하는 별도의 컴포넌트를 두고 업데이트된 상태 값에 따라 모달 핸들링 및 재시도 로직을 수행합니다.</li></ul><p>이러한 구조는 상태 변화에 따른 반응 로직을 관찰자(observer)에게 위임함으로써 전체 코드의 구조를 더욱 깔끔하게 만들고 역할과 책임의 분리를 명확히 할 수 있다는 장점이 있습니다.</p><p>그리고 이를 구현하기 위한 방법으로 Observer Pattern을 활용하였습니다.</p><h3>Observer Pattern</h3><p>Observer Pattern은 객체의 상태 변화를 관찰하는 관찰자들이 주체(Subject)에 등록되고, 주체의 상태가 변경될 때 등록된 관찰자들에게 자동으로 알림을 전달하는 디자인 패턴입니다.</p><p>아래는 이를 활용해 애러 핸들링을 중앙에서 관리하는 구현 코드의 일부입니다.</p><p><strong>Subject</strong></p><pre>class MyErrorMiddleware {<br>  private listeners: MyErrorListener | null = null;<br>  private failedMutations: MyMutation[] = [];<br><br>  // 관찰자 등록<br>  public subscribe(listener: MyErrorListener) {<br>    if (this.listeners) {<br>      throw new Error(&quot;이미 구독되어있는 리스너가 있습니다.&quot;);<br>    }<br><br>    this.listeners = listener;<br>    return () =&gt; {<br>      this.listeners = null;<br>    };<br>  }<br><br>  // 상태 변경을 알리는 내부 메서드<br>  private notifyListeners() {<br>    this.listeners?.(this.failedMutations);<br>  }<br><br>  // 상태 추가<br>  public publish(mutation: Mutation, variables: unknown) {<br>    this.failedMutations = [...this.failedMutations, { mutation, variables }];<br>    this.notifyListeners();<br>  }<br><br>  // 상태 초기화<br>  public clearMutations() {<br>    this.failedMutations = [];<br>    this.notifyListeners();<br>  }<br>}<br><br>// 중앙 관리 인스턴스 생성<br>export const myErrorMiddleware = new MyErrorMiddleware();</pre><p>주체 역할인 MyErrorMiddleware 클래스는 에러 정보를 저장하고, 등록된 옵저버에게 상태 변화를 알리는 역할을 담당합니다.</p><p>내부적으로는 failedMutations 배열을 활용해 에러가 발생한 mutation 정보를 별도로 관리하고 있습니다.</p><p>이는 하나의 요청 내에서 여러 개의 API 호출이 발생하거나, 실패한 요청을 추후 재시도해야 하는 상황에 대처하기 위해 내부 상태로 관리되어야하기 때문입니다.</p><p>또한 이 로직은 전역에서 하나의 컴포넌트에게만 에러 상태를 전달하는 것을 의도하여 설계되었기 때문에, 리스너는 단일 컴포넌트만 등록 가능하도록 구현하였습니다.</p><p><strong>Error Publisher</strong></p><pre>// 최상위 Provider의 queryClient<br>const queryClient = new QueryClient({<br>  mutationCache: new MutationCache({<br>    onError: (error, variables, _, mutation) =&gt; {<br>      if (myErrorMiddleware.isMyError(error)) {<br>        myErrorMiddleware.publish(mutation, variables, error);<br>        throw error;<br>      }<br>    },<br>  }),</pre><p>이어서 전역에서 발생하는 에러를 일관되게 관리하기 위해, 상위 queryClient 객체의 mutationCache 옵션에 에러 발생 시 처리할 로직을 등록합니다.</p><p>이를 통해 모든 mutation 요청에 대해 조건에 부합하는 에러가 발생한다면 일괄적인 핸들링 로직을 적용시킬 수 있습니다.</p><blockquote>queryClient의 mutationCache에서 에러를 처리한 이유?</blockquote><p>첫번째 이유는 Mutation 중심의 비즈니스 로직에 명확하게 대응하기 위함입니다.</p><p>Axios를 사용하고 있었기 때문에 Interceptor를 활용해 에러를 처리 할 수 있었지만 Muation Context 내에서 실패한 요청 정보를 명확히 구분짓고자 하는 의도가 있었습니다.</p><p>두번째 이유는 <strong>에러전파를 막기 위함</strong>입니다.</p><p>조건에 부합하는 에러가 발생하면 각 컴포넌트에서 사용중인 에러 핸들링 로직이 발생시키는것을 막을 필요가 있었고 이를 막고자 에러를 의도적으로 throw 하여 에러 전파를 방지했습니다.</p><p><strong>Observer</strong></p><pre>// MyErrorModal<br>export const MyErrorModal = () =&gt; {<br>  const [failedMutations, setFailedMutations] = useState&lt;MyMutation[]&gt;([]);<br><br>  useEffect(() =&gt; {<br>    // 이벤트가 발생을 구독하고 상태값을 업데이트<br>    const unsubscribe = myErrorMiddleware.subscribe(failedMutations =&gt; {<br>      setFailedMutations(failedMutations);<br>    });<br><br>    // CleanUp시 구독을 해제<br>    return () =&gt; {<br>      unsubscribe();<br>    };<br>  }, []);</pre><p>이어서, Observer 역할을 하는 컴포넌트에서는 Subject인 myErrorMiddleware를 구독하여 상태 변화를 감지하고, 에러 상태에 따라 필요한 UI 및 로직을 처리합니다.</p><p>Subject에서는 특정 비즈니스 로직에 의해 에러를 발생시킨 Mutation정보를 내부 상태값으로 관리하며, 상태가 변경될 때마다 등록된 옵저버에게 해당 정보를 전달합니다.</p><pre>// MyErrorModal<br><br>{ ... }<br><br>const hasFailedMutations = failedMutations.length &gt; 0;<br><br>const { mutate } = useMutation({<br>    mutationFn: async (mutations: MyMutation[]) =&gt; {<br>      const results = await Promise.allSettled(mutations.map(mutation =&gt; mutation.mutation.execute(mutation.variables)));<br>      const failedMutations = results.filter(result =&gt; result.status === &#39;rejected&#39;);<br><br>      if(failedMutations.length &gt; 0) {<br>        throw new Error(&quot;retry failed mutations exist&quot;);<br>      }<br>      return results;<br>    },<br>    onError: () =&gt; {<br>     // error handle<br>     { ... }<br>    },<br>    onSettled: () =&gt; {<br>      myErrorMiddleware.clearMutations();<br>    },<br>  });<br><br><br><br>return (<br>  &lt;MyModal open={hasFailedMutations}&gt;<br>    { ... }<br>  &lt;/MyModal&gt;<br>)</pre><p>특히 주의해야 할 부분은, 에러가 발생한 mutation을 재요청할 때, 동일한 오류가 반복되지 않도록 예외 처리를 명확하게 구현해야 한다는 점입니다.</p><p>특정 이슈에 의해 동일한 에러코드가 반환되고 미들웨어에 저장되는 형태의 루프에 빠질 위험이 있기때문입니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-3jdNl4AMX-T6pk2P3cqaQ.png" /><figcaption>전체 플로우 정리</figcaption></figure><h3>결론</h3><p>Observer Pattern을 사용하여 에러 핸들링 문제를 위와 같이 해결할 수 있었고 필요한 경우에만 UI를 업데이트하는 방식으로 효율적인 에러 핸들링을 구현할 수 있었습니다.</p><p>이 접근법을 통해 다음과 같은 개선점을 얻을 수 있었습니다:</p><ol><li>유지보수성 강화: 에러 핸들링 로직을 중앙에서 관리함으로써, 상태 관리와 비즈니스 로직을 분리할 수 있었습니다.</li></ol><p>2. 일관된 에러 처리 방식: 개별 컴포넌트가 아닌 전역에서 에러를 감지하고 처리함으로써, 중복 코드 없이 일관된 방식으로 예외를 다룰 수 있었습니다.</p><p>그러나 아래와 같은 부분에서 개선할 부분이 남아있습니다.</p><p>1. Mutation 단위의 에러 처리 한계: 커스텀 에러를 발생시키는 경우, 전역 에러 핸들러에서 이를 감지하지 못하는 상황이 발생할 수 있습니다.</p><ul><li>즉 개발자 입장에서는 전역 에러 핸들러 로직을 알고 있어야 하며, 이를 고려하지 않으면 특정 에러가 누락되거나 잘못 처리될 수 있음</li><li>ex) Promise.allSettled 내부에서 커스텀 에러를 발생시키는 경우</li></ul><h3>참고자료</h3><p><a href="https://www.patterns.dev/vanilla/observer-pattern/">Observer Pattern</a></p><p><a href="https://ko.react.dev/reference/react/hooks">React Hooks</a></p><p><a href="https://tanstack.com/query/latest/docs/reference/MutationCache">React Query Mutacion Cache</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec99320f732d" width="1" height="1" alt=""><hr><p><a href="https://blog.techeer.net/observer-pattern-%EA%B8%B0%EB%B0%98%EC%9D%98-%EC%97%90%EB%9F%AC%ED%95%B8%EB%93%A4%EB%A7%81-%EB%A1%9C%EC%A7%81-%EA%B5%AC%ED%98%84%ED%95%98%EA%B8%B0-ec99320f732d">Observer Pattern 기반의 에러핸들링 로직 구현하기</a> was originally published in <a href="https://blog.techeer.net/">Techeer Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Nuxt(Legacy) 프로젝트에 React 모듈 연결하기]]></title>
            <link>https://blog.techeer.net/nuxt-legacy-%ED%94%84%EB%A1%9C%EC%A0%9D%ED%8A%B8%EC%97%90-react-%EB%AA%A8%EB%93%88-%EC%97%B0%EA%B2%B0%ED%95%98%EA%B8%B0-749516b27ec5?source=rss-d580fa80743e------2</link>
            <guid isPermaLink="false">https://medium.com/p/749516b27ec5</guid>
            <category><![CDATA[nuxt]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Teawon]]></dc:creator>
            <pubDate>Tue, 11 Mar 2025 16:46:11 GMT</pubDate>
            <atom:updated>2025-03-12T15:54:55.526Z</atom:updated>
            <content:encoded><![CDATA[<h4>1. 개요</h4><p>프레임워크는 개발을 용이하게 해주지만, 때로는 확장이나 새로운 기능 추가에 제약을 불러오기도 합니다.</p><p>특히, 특정 프레임워크나 환경에서만 실행 가능한 라이브러리는 제한된 선택지를 제공하며, 이로 인해 적합한 솔루션을 찾기 어렵게 만들 수 있습니다. 이러한 점은 아래의 프로젝트에서 직면한 문제와도 맞물렸습니다.</p><p>회사의 레거시 시스템은 Nuxt1을 기반으로 운영되고 있었고, 이 환경에서 PDF 생성 모듈을 새롭게 개발해야 했습니다. 그러나 PDF 생성 로직이 이미 React 기반의 라이브러리로 구현되기로 정해진 상황이었기 때문에, 이 두 가지 기술을 조화롭게 결합하는 것이 과제가 되었습니다.</p><blockquote>Nuxt1은 2018년에 출시되었으며, 현재는 deprecated 되어있다.</blockquote><p>결국 핵심 문제는 Nuxt1의 레거시 환경에서 요구되는 기능을 구현할 수 있도록 두 상이한 프레임워크를 성공적으로 통합하는 것이었습니다. 이 과정에서 시스템의 기능성을 확장하면서도 기존 시스템의 안정성을 유지하는 솔루션을 마련되어야 했습니다.</p><p>이 글에서는 이와 같은 문제를 해결하기 위해 고려했던 접근 방안과 그 과정에서 마주한 고민들을 정리해보고자 합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/0*jrlwVTvNbujdh3vp" /></figure><h4>2.1 기술적 선택의 배경</h4><p>PDF 모듈개발을 위해서는 다음과 같은 요구사항이 충족되어야 했습니다.</p><p>1. 다양한 차트를 그릴 수 있을 것</p><p>2. 확대된 PDF가 깨지지 않을 것 (텍스트가 비트맵 기반의 이미지로 처리되어선 안된다)</p><p>3. PDF 변환 작업은 프론트엔드에서 이루어져야 한다. (높은 결합도, 작업 의존성을 개선하기 위함)</p><p>즉 Canvas기반의 이미지를 사용하지 않아야 했고, 지속적으로 관리하고 확장할 수 있는 프로젝트를 구성하기 위한 조건이 필요했습니다.</p><p>가장 직관적인 방법은 Nuxt 프레임워크 내에서 직접 PDF 변환 모듈을 개발하는 것 이지만 Nuxt의 종속성에 의해 선택할 수 있는 차트 생성 및 PDF 변환 라이브러리에는 한계가 있었고, 이로 인해 높은 러닝 커브가 요구되었습니다. 더욱이, 이러한 방법은 지속적인 관리와 유지보수에도 명확한 제약이 따랐습니다.</p><p>따라서, 이러한 요구사항을 충족하면서 적정 시간 내 개발이 가능하도록, React와 호환 가능한 라이브러리를 사용하여 PDF 변환 모듈을 구현하기로 처리하게 되었습니다.</p><p>그럼에도 불구하고, 여전히 해결해야 할 과제가 있었습니다. 두 서로 다른 프레임워크 간의 통합을 어떻게 처리할 것인가 하는 문제였고, 이에 대해 두 가지 주요 접근 방안을 고려했습니다.</p><p><strong>1. 별도의 도메인을 분리하여 특정 URL에 접근했을 때 React 앱을 제한적으로 띄우는 방법</strong></p><p><strong>2. React 모듈을 배포한 후, 배포된 JavaScript 파일을 Nuxt 내부에서 동적으로 읽어들이는 방법</strong></p><p>첫 번째 방법은 별도의 도메인으로 관리하는 점에서, 개별 앱의 독립성을 보장하고 특정 기능을 분리하여 관리할 수 있다는 장점이 있었습니다.</p><p>그러나 이 방법은 별도의 도메인 관리 포인트가 늘어나고, URL에 종속되어 특정 페이지에서 모달을 띄우는 등의 사용처에 한계가 있었습니다. 또한, 분리된 두 도메인 간의 인증 처리(Auth)가 복잡해질 수 있다는 단점도 고려해야 했습니다.</p><p>두 번째 접근 방법은 React 모듈을 배포한 뒤, 그 배포된 JavaScript 파일을 Nuxt 내부에서 동적으로 읽어들이는 방식이었습니다.</p><p>이 방법은 별도의 도메인 관리를 피할 수 있고, Nuxt 환경 내에서 React 모듈을 유연하게 활용할 수 있다는 점에서 큰 장점이 있었습니다. 이렇게 하면 모듈이 특정 페이지나 구성 요소에 종속되지 않고 쉽게 통합될 수 있습니다.</p><p>또한, 클라이언트 측에서 자바스크립트를 호출하여 필요한 기능을 실행할 수 있으므로, 페이지 전환이나 네비게이션에 제한이 없고, 통합된 UI 흐름을 유지할 수 있다는 이점도 있었습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*Bz5q_iPmbT8wQJZUEU5-sQ.png" /><figcaption>고려한 두 방법의 장단점 정리</figcaption></figure><p>따라서 위와 같은 이유를 고려해 두 번째 방법을 사용해 문제를 해결하고자 하였습니다.</p><h4>3. 구현 세부 사항</h4><p>서로 다른 프레임워크간의 이벤트를 처리하기 위해 이벤트 기반 접근 방식을 사용하여 두 프레임워크 간의 원활한 통신을 처리하도록 설계하였습니다.</p><p>이를 구현하기 위해 CustomEvent를 활용하여 이벤트를 생성하고, 이러한 이벤트를 통해 React와 Nuxt 간의 상호작용을 가능하게 했습니다.</p><blockquote>왜 CustomEvent을 사용했나?</blockquote><blockquote>초기에는 window.postMessage를 사용했으나 다른 출처를 가진 페이지간의 통신을 위해 필요한 기능이 아니라고 생각하여 CustomEvent로 전환하였습니다.</blockquote><blockquote>window객체는 전역에서 사용되므로 전역 네임스페이스 오염을 최소화하기위해 별도의 객체를 사용하여 데이터를 그룹화하고 응집도를 높이고자하였습니다.</blockquote><h4>3.1 React</h4><h4>3.1.1 이벤트 설계</h4><pre>// index.html<br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    { ... }<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;div id=&quot;react_pdf_module_id&quot;&gt;&lt;/div&gt;<br>    { ... }<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>index.html 은 기존 React 프로젝트에서 사용하는 구조와 동일합니다.</p><p>이때 id가 react_pdf_module_id인 div 요소는 React 앱이 마운트될 DOM 요소로 지정됩니다.</p><p>이를 기반으로 ReactDOM.createRoot를 통해 해당 DOM요소에 React 컴포넌트를 렌더링할 수 있도록 준비합니다</p><pre>// global.d.ts<br><br>declare global {<br>  interface Window {<br>    myMoudle: {<br>      mountApp: () =&gt; void;<br>      unMountApp: () =&gt; void;<br>      request: (param: { ... }) =&gt; void;<br>      close: () =&gt; void;<br>      { ... }<br>    };<br>  }<br>}<br><br>export {};</pre><p>global.d.ts 파일에서는 전역 객체 window에 추가될 모듈의 인터페이스를 선언합니다.</p><p>이 인터페이스는 CustomEvent를 통해 주고받을 이벤트 메서드들을 정의합니다.</p><pre>// main.tsx<br><br>const mountApp = (containerId: string) =&gt; {<br>  const container = document.getElementById(containerId);<br>  if (!container) return;<br><br>  if (root) {<br>    root.unmount();<br>  }<br><br>  root = ReactDOM.createRoot(container);<br>  root.render(<br>    &lt;React.StrictMode&gt;<br>      &lt;App /&gt;<br>    &lt;/React.StrictMode&gt;<br>  );<br>};<br><br>window.pdfModule = {<br>  mountApp: () =&gt; {<br>    mountApp(&quot;react_pdf_module_id&quot;);<br>  },<br>  unMountApp: () =&gt; {<br>    if (root) {<br>      root.unmount();<br>    }<br>  },<br>  request: ( param : { ... }) =&gt; {<br>    const event = new CustomEvent(&quot;requestEvent&quot;, {<br>      detail: { action: &quot;request&quot;, ...param },<br>    });<br>    window.dispatchEvent(event);<br>  },<br>  close: () =&gt; {<br>    const event = new CustomEvent(&quot;closeEvent&quot;, {<br>      detail: { action: &quot;close&quot; },<br>    });<br>    window.dispatchEvent(event);<br>  },<br>};</pre><p>main.tsx에서는 global.d.ts에서 정의된 인터페이스에 대한 실제 구현을 작성합니다.</p><p>기존의 React 환경에서는 애플리케이션을 시작과 동시에 마운트하는 방식으로 동작했다면, 현재 구조에서는 Nuxt가 앱을 동적으로 제어하고 요청에 따라 특정 이벤트를 발생시켜야 하므로, 각 동작을 별도의 이벤트로 분리하여 처리합니다.</p><pre>const MainPage = () =&gt; {<br>  { ... }<br><br>  useEffect(() =&gt; {<br>    const handleAwsReportEvent = (event: CustomEvent&lt;PdfRequestEvent&gt;) =&gt; {<br>      const { action, ...param } = event.detail;<br><br>      switch (action) {<br>        case &quot;request&quot;:<br>          { ... }<br>          break;<br>        case &quot;close&quot;:<br>          { ... }<br>          break;<br>        default:<br>          { ... }<br>      }<br>    };<br><br>    window.addEventListener(<br>      &quot;pdfModuleEvent&quot;,<br>      handlePdfModuleEvent<br>    );<br><br>    return () =&gt; {<br>      window.removeEventListener(<br>        &quot;pdfModuleEvent&quot;,<br>        handlePdfModuleEvent<br>      );<br>    };<br>  }, []);<br><br>  return (<br>     &lt;PdfPreviewPage { ... } /&gt;<br>  );<br>};<br><br>export default MainPage;</pre><p>실제 PDF 변환 로직에서의 시작 및 종료를 핸들링하는 이벤트는 구현 페이지에서 다음과 같이 처리합니다.</p><p>위 예제는 React 컴포넌트 MainPage에서 이벤트 리스너를 설정하고 이벤트가 발생하면 적절한 함수가 호출되어 미리 정의한 이벤트 동작을 수행합니다.</p><h4>3.1.2 빌드 및 캐싱</h4><p>앞서 구현한 React 모듈은 독립적인 웹사이트가 아니라 Nuxt에서 동적으로 로드되는 특성을 가지고 있습니다.</p><p>따라서, 빌드 후 생성된 파일을 Nuxt가 단순히 읽어들이기만 한다면, 브라우저 캐싱으로 인해 이전 버전의 파일을 계속 읽어오는 문제가 발생할 수 있습니다.</p><p>이 문제를 해결하기 위해, 빌드 시 파일 이름에 해시값을 추가하는 전처리 과정을 통해 캐싱 문제를 해결해야합니다.</p><pre>// defaultCache.ts<br><br>// 스크립트 동적 로드를 위한 함수<br>const loadScript = (src: string, name: string, type: string): Promise&lt;void&gt; =&gt; {<br>  return new Promise((resolve, reject) =&gt; {<br>    if (!document.querySelector(`script[data-name=&quot;${name}&quot;]`)) {<br>      const script = document.createElement(&quot;script&quot;);<br>      script.src = src;<br>      script.type = type;<br>      script.async = true;<br>      script.dataset.name = name;<br>      script.onload = resolve;<br>      script.onerror = () =&gt; reject(new Error(`Error loading ${src}`));<br>      document.body.appendChild(script);<br>    } else {<br>      resolve();<br>    }<br>  });<br>};<br><br>// CSS 동적 로드<br>const loadCSS = (href: string, name: string) =&gt; {<br>  if (!document.querySelector(`link[data-name=&quot;${name}&quot;]`)) {<br>    const link = document.createElement(&quot;link&quot;);<br>    link.href = href;<br>    link.rel = &quot;stylesheet&quot;;<br>    link.dataset.name = name;<br>    document.head.appendChild(link);<br>  }<br>};<br><br>// 메인 리소스 로드 함수<br>const loadResources = async () =&gt; {<br>  await loadScript(<br>    import.meta.env.VITE_DEPLOY_URL + &quot;assets/main.js&quot;,<br>    &quot;main&quot;,<br>    &quot;module&quot;<br>  );<br>  loadCSS(import.meta.env.VITE_DEPLOY_URL + &quot;assets/main.css&quot;, &quot;style&quot;);<br>};<br><br>loadResources().catch(console.error);</pre><p>애플리케이션에서 JavaScript와 CSS를 포함한 주요 리소스는 각 빌드 시마다 고유한 해시값이 포함된 파일명으로 생성되어 동적 로드가 필요합니다.</p><p>각각의 파일을 매번 직접적으로 웹에서 로드하기보다는, 한 곳에서 관리하는 방식은 리소스 로딩을 보다 체계적으로 조절할 수 있는 장점을 제공할 수 있기 때문에 이러한 역할을 수행하는 파일을 분리하였습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CvaIWx1yVyhYypxL" /></figure><pre>// vite.config.ts<br><br>export default defineConfig({<br>  { ... }<br>   build: {<br>    rollupOptions: {<br>      input: {<br>        main: &#39;./src/main.tsx&#39;,<br>        cache: &#39;./src/defaultCache.ts&#39;,<br>      },<br>      output: {<br>        entryFileNames: `assets/[name]-[hash].js`,<br>        chunkFileNames: &#39;assets/[name].js&#39;,<br>      },<br>    },<br>  },<br>});</pre><p>이어서 파일을 빌드하면 아래와 같은 파일들이 생성됩니다.</p><pre>{ ... }<br>dist/assets/index-D7WsOEMb.js                108.60 kB<br>dist/assets/main-C4_uRKNb.css                  0.75 kB │ gzip:   0.35 kB<br>dist/assets/cache-Cngjqysx.js                  1.10 kB │ gzip:   0.48 kB<br>dist/assets/main-o7EPCvhK.js               1,710.15 kB │ gzip: 547.53 kB</pre><p>이 과정에서 가장 중요한 점은 cache.js 파일이 항상 최신 버전의 스크립트를 참조하도록 보장해야한다는 부분 입니다.</p><p>매번 배포 시마다 변경되는 해시값을 모든 외부 프로젝트에서 직접 동기화시키는 것은 비효율적이므로 cache.js가 매번 최신의 해시값을 자체적으로 읽어들이고 이를 참조할 수 있도록 내부 처리가 필요합니다.</p><pre>//innerBuildHash.cjs<br>const fs = require(&quot;fs&quot;);<br>const util = require(&quot;util&quot;);<br><br>const directoryPath = __dirname + &quot;/dist/assets&quot;;<br><br>{ ... }<br><br>    // 해시 추출<br>    const mainHash = getHashByPath(/^main-(.*).js$/, files);<br>    const cssHash = getHashByPath(/^main-(.*).css$/, files);<br><br>    // 파일 경로와 대체 로직<br>    const cacheJsPath = `${directoryPath}/cache.js`;<br><br>    try {<br>      let content = fs.readFileSync(cacheJsPath, &quot;utf-8&quot;);<br>      content = content.replace(/main\.js/g, `main-${mainHash}.js`);<br>      content = content.replace(/main\.css/g, `main-${cssHash}.css`);<br>      fs.writeFileSync(cacheJsPath, content, &quot;utf-8&quot;);<br>    } catch (err) {<br>      console.error(&quot;Error processing files:&quot;, err);<br>    }<br>  })<br>  .catch((err) =&gt; {<br>    console.error(&quot;Error reading directory:&quot;, err);<br>  });</pre><p>이러한 전처리는 빌드된 파일의 해시 값을 추출하고 이를 기반으로 cache.js의 참조를 업데이트하는 과정을 포함합니다.</p><p>결과적으로 사용하는 클라이언트에서는 오직 cache.js 파일만을 읽어들여 최신의 스크립트들을 참조할 수 있는 환경이 구성됩니다.</p><h4>3.2 Nuxt</h4><pre>&lt;template&gt;<br>  { .. }<br>      &lt;div<br>        id=&quot;react_pdf_module_id&quot;<br>        class=&quot;modal-pdf-area&quot;&gt;<br>      &lt;/div&gt;<br>&lt;/template&gt;</pre><p>Nuxt에서는 React 모듈이 DOM에 렌더링될 때 사용할 id 값을 지정하여 template을 구성합니다. 이 id 값은 React 앱이 마운트될 DOM 요소를 지정하는 데 사용됩니다.</p><blockquote>해당 DOM요소에 Pdf모듈이 마운트되며 React앱이 동적으로 로드</blockquote><pre>&lt;script&gt;<br>{ ... }<br>   loadReactApp() {<br>      const existingScript = document.querySelector(<br>        &#39;script[data-name=&quot;react_pdf_module_id&quot;]&#39;<br>      )<br>      if (existingScript) {<br>        // 로드된 스크립트가 있다면 React 앱 마운트<br>        window.pdfModule.mountApp()<br>        this.$emit(&#39;scriptLoaded&#39;)<br>        return<br>      }<br><br>      // js read<br>      const script = document.createElement(&#39;script&#39;)<br>      const scriptSrc = `${process.env.REACT_PDF_MODULE_URL}?time=${new Date().getTime()}`<br>      script.type = &#39;module&#39;<br>      script.src = scriptSrc<br>      script.async = true<br>      script.onload = () =&gt; this.$emit(&#39;scriptLoaded&#39;)<br>      script.onerror = () =&gt;<br>        this.messageShow(&#39;pdf 모듈을 불러오는 중 오류가 발생했습니다.&#39;)<br>      document.body.appendChild(script)<br>    },<br>    requestPdfModule() {<br>      window.pdfModule.request({ ... })<br>    },<br>    closePdfModule() {<br>      window.pdfModule.close()<br>    },<br>  }<br>&lt;/script&gt;</pre><p>이어서, 스크립트를 동적으로 로드하고 이벤트를 발생시키는 로직을 작성합니다. loadReactApp 메서드는 로드된 스크립트 여부를 확인하고, 없는 경우 새로운 스크립트를 생성하여 DOM에 추가합니다.</p><p>이때 스크립트를 로드할 때 src URL 뒤에<strong> 현재 시간을 쿼리 파라미터로 추가함으로써 캐싱 문제를 해결</strong>합니다. 이렇게 하면 매번 새로고침할 때마다 브라우저가 항상 최신의 스크립트를 불러오게 됩니다.</p><p>또한, 이 과정에서 Pdf 모듈에서 전처리과정을 거친 cache.js 스크립트를 로드하면, 이 파일은 내부적으로 최신 리소스를 자동으로 참조합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tMvgXOmkJPzR5bbf" /><figcaption>상호 작용 다이어그램</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xaf2R0xVG9JcSDFc" /><figcaption>실제 필요한 페이지에서 다음과 같이 스크립트를 동적으로 로드</figcaption></figure><h4>4. 이슈 및 고려사항</h4><p>위 프로젝트를 진행하며 구현 과정에서 겪었던 이슈가 있었습니다. 이러한 문제들과 고민했던 해결 방안들을 다루어보려고 합니다.</p><h4>4.1 CSS 오염</h4><p>위 구조에 따르면, 결국 React에서 사용된 CSS 파일은 스크립트 형태로 읽어오게 됩니다. 이로 인해, Nuxt 프로젝트와 React 모듈 간의 스타일이 오염되는 문제가 발생했습니다.</p><p>특히 PdfModule 개발에 사용된 reset.css 파일이 기존 Nuxt 프로젝트 css와 서로 간섭하여 예기치 않은 문제가 발생했습니다.</p><p>위 문제는 결국 CSS Modules 기반의 로컬 스코프로 CSS 적용 범위를 제한하는 방식으로 해결할 수 있었습니다.</p><p>그럼에도 불구하고, 의도하지 않은 곳에서 동일한 구조나 이름을 가진 선택자가 예상치 못한 영향을 미칠 수 있다는 점은 예측하기 어렵다는 부분을 고려해야하며 두 환경은 완전히 독립적으로 분리되어야 하므로, CSS 간의 상호 영향에 대한 지속적인 주의와 개선점이 필요하다고 생각했습니다.</p><h4>4.2 테스트의 어려움</h4><p>위에서 구현한 PDF 모듈은 결국 이벤트 기반으로 작동하기 때문에 실제 변환된 PDF 결과를 디버깅하거나 코드를 테스트하려면 반복적으로 이벤트를 발생시키고 처리해야 하는 번거로움이 있었습니다.</p><p>이 문제를 해결하기 위해 테스트 전용 페이지를 따로 분리했습니다.</p><p>해당 페이지에서는 직접적인 상호작용을 통해 이벤트를 발생시키고 처리할 수 있도록 처리하였으며 테스트 페이지는 배포 환경에서는 제외되도록 조건부 렌더링을 적용하여 환경을 구성했습니다.</p><pre>// App.tsx<br><br>function App() {<br>  return (<br>    &lt;QueryClientProvider client={queryClient}&gt;<br>      &lt;Router&gt;<br>        &lt;Routes&gt;<br>          {/* 디버깅용 확인 페이지 */}<br>          {import.meta.env.MODE === &quot;development&quot; &amp;&amp; (<br>            &lt;Route path=&quot;/*&quot; element={&lt;DevPage /&gt;} /&gt;<br>          )}<br>          &lt;Route path=&quot;/*&quot; element={&lt;MainPage /&gt;} /&gt;<br>        &lt;/Routes&gt;<br>      &lt;/Router&gt;<br>    &lt;/QueryClientProvider&gt;<br>  );<br>}<br>export default App;</pre><p>또한, React 기반의 PDF 모듈은 Nuxt 환경에서 호출되므로, 정적 자산에 대한 경로는 Nuxt를 기준으로 설정해야 합니다.</p><p>이를 위해 환경 변수를 사용하여 전체 경로를 명시적으로 지정하고, 모든 환경에서 통일된 경로 참조가 가능하도록 다음과 같은 처리를 해야했습니다.</p><pre>&lt;Image src={import.meta.env.VITE_DEPLOY_URL + &quot;images/iconExample.png&quot;}&gt;&lt;/Image&gt;</pre><blockquote>local 환경에서는 명시적으로 “/” 경로를 지정하여 개발 환경 내 테스트에 문제가 없도록 처리</blockquote><h4>4.3 스크립트 의존성</h4><pre>// defaultCache.ts<br>const loadResources = async () =&gt; {<br>  await loadScriptSequentially([<br>    {<br>      src: import.meta.env.VITE_DEPLOY_URL + &quot;lib/a.js&quot;,<br>      name: &quot;a&quot;,<br>      type: &quot;text/javascript&quot;,<br>    },<br>    {<br>      src: import.meta.env.VITE_DEPLOY_URL + &quot;lib/b.js&quot;,<br>      name: &quot;b&quot;,<br>      type: &quot;text/javascript&quot;,<br>    },<br>    {<br>      src: import.meta.env.VITE_DEPLOY_URL + &quot;lib/c.js&quot;,<br>      name: &quot;c&quot;,<br>      type: &quot;text/javascript&quot;,<br>    },<br>    {<br>      src: import.meta.env.VITE_DEPLOY_URL + &quot;lib/d.js&quot;,<br>      name: &quot;d&quot;,<br>      type: &quot;text/javascript&quot;,<br>    },<br>  ]);<br><br>  // main.js<br>  loadScript(<br>    import.meta.env.VITE_DEPLOY_URL + &quot;assets/main.js&quot;,<br>    &quot;main&quot;,<br>    &quot;module&quot;<br>  );<br>  // main.css<br>  loadCSS(import.meta.env.VITE_DEPLOY_URL + &quot;assets/main.css&quot;, &quot;style&quot;);<br>};<br><br>loadResources().catch((error) =&gt; console.error(error));</pre><p>React PDF 모듈에서는 특정 라이브러리와의 호환을 위해 스크립트가 동적으로 로드되어야하는 문제가 존재했습니다.</p><p>단순히 스크립트를 읽어오는 로직을 넣었을때에는 스크립트의 의존관계가 고려되지 않아 문제가 발생했고,</p><p>스크립트를 관리하는 cache 파일에 다음과 같은 로직을 넣어 올바른 스크립트의 로드 순서를 보장할 필요가 있었습니다.</p><blockquote>React앱이 마운트되기전, 필요한 라이브러리의 스크립트가 로드되지 않으면 앱 자체가 띄워지지 않았다.</blockquote><h4>5. 결과 및 정리</h4><p>이번 프로젝트를 통해 Nuxt 환경에서 React 기반 모듈을 유연하게 호출하고 사용할 수 있는 시스템을 구현할 수 있었습니다.</p><p>결과적으로 다음과 같은 장점이 있었습니다.</p><p>1. <strong>독립적 모듈 관리</strong>: 모듈을 개별적으로 관리할 수 있게 되면서, 수정 사항이 발생할 경우 React 프로젝트만 독립적으로 배포할 수 있게 되었습니다.</p><p>2. <strong>프레임워크 제약 탈피</strong>: 기존 Nuxt 프레임워크의 종속성에서 벗어나, 새로운 기능을 보다 자유롭게 통합할 수 있는 유연성을 확보할 수 있었습니다.</p><p>그럼에도 불구하고 몇 가지 한계와 아쉬운 점도 있었습니다.</p><p>1. <strong>정보 관리의 복잡성</strong>: React 앱이 마운트될 때의 DOM ID 값이나 이벤트 정보는 두 프로젝트에서 별도로 명시해야 하기에, 잘못된 정보 입력 시 처리 어려움과 이벤트 요청의 타입 추론이 자동화되지 않아 사용상 직관성과 안정성이 부족할 수 있습니다.</p><p>2. <strong>추가적인 네트워크 및 복잡성</strong>: 웹 상에서 별도의 스크립트를 다운로드하여 처리해야 하므로, 추가적인 네트워크 자원이 필요하며, 시스템의 복잡도가 증가할 수 있다는 단점도 존재합니다.</p><p>결론적으로, 이번 프로젝트를 통해 많은 것을 배울 수 있었고, 이러한 경험을 바탕으로 향후 유사 프로젝트에서 더 나은 해결책을 찾을 수 있기를 기대합니다.</p><blockquote>모든 기술에는 정답이 없기 마련이지만, 이러한 아쉬운 점들을 보완해 나가는 것은 매우 중요하다고 생각합니다. 예를 들어, 웹컴포넌트에서는 `Shadow DOM` 개념을 사용해 위에서 언급했던 CSS오염문제를 해결했다고 하니 해당 방법을 사용하는 것도 좋은 접근방법이 되었을 것 같다는 생각이 드네요..!</blockquote><h4>참고자료</h4><p><a href="https://developer.mozilla.org/ko/docs/Web/API/CustomEvent/CustomEvent">CustomEvent</a></p><p><a href="https://create-react-app.dev/docs/adding-a-css-modules-stylesheet/">CSS Modules</a></p><p><a href="https://medium.com/twolinecode/%ED%94%84%EB%A1%A0%ED%8A%B8%EC%97%94%EB%93%9C-%EC%95%84%ED%82%A4%ED%85%8D%EC%B2%98-mfa-chapter4-by-%EC%9D%B4%EB%8F%99%ED%98%95%EB%8B%98-fbc155b718c6">MFA</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=749516b27ec5" width="1" height="1" alt=""><hr><p><a href="https://blog.techeer.net/nuxt-legacy-%ED%94%84%EB%A1%9C%EC%A0%9D%ED%8A%B8%EC%97%90-react-%EB%AA%A8%EB%93%88-%EC%97%B0%EA%B2%B0%ED%95%98%EA%B8%B0-749516b27ec5">Nuxt(Legacy) 프로젝트에 React 모듈 연결하기</a> was originally published in <a href="https://blog.techeer.net/">Techeer Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Github Actions, 테스트 코드 자동화]]></title>
            <link>https://medium.com/@teawon.jeong.dev/github-actions-%ED%85%8C%EC%8A%A4%ED%8A%B8-%EC%BD%94%EB%93%9C-%EC%9E%90%EB%8F%99%ED%99%94-6b8b5087bb66?source=rss-d580fa80743e------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b8b5087bb66</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[github-actions]]></category>
            <dc:creator><![CDATA[Teawon]]></dc:creator>
            <pubDate>Wed, 29 Nov 2023 09:09:40 GMT</pubDate>
            <atom:updated>2023-11-29T09:09:40.515Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. 개요</h3><p>이전 글에서는 테스트 코드를 작성해 Unit단위의 테스트를 진행하고, 확인하는 과정을 거쳤습니다.</p><p>하지만 만들어두고 활용하지 않으면 의미가 없죠. 아무래도 매 작업마다 테스트를 실행하기 위해 명령어를 치고 결과를 확인하는 것은 번거롭고 귀찮기 때문입니다.</p><p>저는 개발 브랜치에 PR을 요청 했을때 자동으로 작성된 테스트코드를 돌리고, 정상적으로 돌아간다면 merge가 가능하도록 처리하고 싶었습니다.</p><p>의도치 않게 기존 코드를 수정하고 유지보수를 진행해도 이미 작성된 테스트코드를 통해 최소한의 기능동작이 돌아간다는게 보장이 된다면 개발의 안정성과 실수를 줄일 수 있을 것 같았어요.</p><p>이 글에서는 CI/CD의 개념부터 시작해서, GitHub Actions를 통해 CI/CD 파이프라인을 어떻게 구축하는지 내용을 정리하고자 합니다.</p><h3>2. CI/CD</h3><p>CI/CD는 지속적 통합(Continuous Integration, CI)과 지속적 배포(Continuous Deployment, CD)의 약자입니다. 사실 많이 들어봤는데 개념적으로 접하니까 어색하네요.</p><p>CI는 개발 중인 코드를 공유 코드 저장소에 지속적으로 통합하는 과정을 의미합니다.</p><p>이러한 과정은 팀원들이 자신들의 변경사항을 즉시 공유하도록 독려하여, 버그를 빠르게 찾고 고칠 수 있도록 합니다. 이는 코드 베이스를 최신 상태로 유지하고, 프로젝트의 안정성을 높이는 데에 중요한 역할을 합니다.</p><p>CD는 CI의 다음 단계로, 개발된 코드를 실제 사용자에게 배포하는 과정을 자동화하는 것을 의미합니다. 이를 통해 개발 팀은 빠르게 피드백을 얻고, 프로덕트의 품질 개선을 위한 사이클을 짧게 가져갈 수 있습니다.</p><p>즉 위에서 언급한 “귀찮고 번거로운 작업들”을 자동화 하고 통합하여 개발프로세스의 안정성과 속도를 높일 수 있는거죠.</p><p>CI/CD 도구로는 Jenkins, Travis CI, GitLab CI/CD, GitHub Actions 등 다양한 도구가 있지만 아래 장점을 고려해 Github Action을 사용하였습니다.</p><ol><li>설치의 간결함: GitHub Actions는 GitHub에 내장되어 있기 때문에, 별도의 서버 설치나 구성이 필요 없음</li><li>통합성 : GitHub 저장소와의 자연스러운 통합과 코드 저장소와 CI/CD 파이프라인이 같은 위치에 있으므로 일관성 유지가 용이</li><li>사용 편의성: YAML 형식의 워크플로우 파일을 통해 CI/CD 프로세스를 명확하게 정의하고 관리 가능</li><li>가격 : public 경우 무료..! <a href="https://docs.github.com/ko/billing/managing-billing-for-github-actions/about-billing-for-github-actions">출처</a></li></ol><h3>3. Github Action</h3><p>GitHub Actions는 GitHub에서 직접 제공하는 CI/CD 도구입니다. 이 도구를 사용하면 소프트웨어 개발 워크플로우를 자동화할 수 있으며, 코드를 푸시하거나 풀 리퀘스트를 생성할 때 특정 작업을 자동으로 실행할 수 있습니다.</p><p>예를 들어, 테스트를 실행하거나 애플리케이션을 빌드하고 배포하는 등의 작업을 자동화할 수 있습니다.</p><h3>3.1 구성요소</h3><p>GitHub Actions의 워크플로우는 워크플로우 파일 내에 정의되며, 이 파일은 .github/workflows 디렉토리에 위치합니다. 워크플로우 파일은 YAML 형식으로 작성되며, 언제 어떤 작업을 실행할지를 정의합니다.</p><p>크게 워크플로우는 일반적으로 세 가지 구성 요소로 구분할 수 있으며 내용은 아래와 같습니다.</p><p>트리거(trigger): 워크플로우가 언제 실행될지를 결정합니다. 트리거는 GitHub 이벤트 (예: 푸시, 풀 리퀘스트, 이슈 생성 등) 또는 일정에 의해 설정될 수 있습니다.</p><p>작업(job): 각 워크플로우는 하나 이상의 작업으로 구성되며, 이는 워크플로우가 실제로 무엇을 수행할지를 정의합니다. 각 작업은 독립적으로 실행되며, 다른 작업과의 상호 작용은 제한적입니다.</p><p>단계(step): 각 작업은 여러 단계로 구성됩니다. 단계는 실제로 실행되는 명령어 또는 액션을 정의합니다.</p><p>[참고]</p><blockquote>GitHub Actions는 기본적으로 .github/workflows 디렉토리에서 워크플로우를 찾으며 이 디렉토리는 워크플로우를 실행할 브랜치에 존재해야 합니다.</blockquote><blockquote>예를 들어, develop 브랜치에 대한 이벤트가 워크플로우를 트리거하는 경우, .github/workflows 디렉토리와 그 안의 워크플로우 파일들은 develop 브랜치에 존재해야 합니다.</blockquote><blockquote>이는 GitHub Actions가 브랜치별로 독립적으로 워크플로우를 관리하므로, 각 브랜치에서 어떤 워크플로우를 실행할지 결정할 수 있기때문입니다.</blockquote><blockquote>(저는 잘 모르고 개발브랜치에 hotfix로 처리하면서 실수했었습니다ㅜㅜ)</blockquote><h3>3.2 test 실습</h3><pre># .github/workflows/test.yml<br># 워크 플로우의 이름 설정<br>name: TEST<br><br># 워크 플로우의 트리거 설정 (develop브랜치에 대한 push,pr에 대해 처리한다)<br>on:<br>  push:<br>    branches: [develop]<br>  pull_request:<br>    branches: [develop]<br><br># 워크 플로우에서 실행될 작업 정의<br>jobs:<br>  build:<br>    name: jest test<br>    # 작업을 실행할 운영체제 설정<br>    runs-on: ubuntu-latest<br><br>    # 병렬 실행 전략 설정 (Node사용)<br>    strategy:<br>      matrix:<br>        node-version: [16.x]<br><br>    steps:<br>      # 각 단계 설정<br>      - uses: actions/checkout@v2<br>      - name: Use Node.js $<br>        uses: actions/setup-node@v2<br>        with:<br>          node-version: $<br>      - run: yarn install<br>      - run: yarn test<br><br></pre><p>이 워크플로우가 실행되면, GitHub Actions는 가장 최신 버전의 Ubuntu에서 Node.js를 설정하고, 의존성을 설치한 다음 테스트를 실행합니다. 모든 단계가 성공적으로 완료되면, 워크플로우는 성공으로 마무리됩니다.</p><p>이제 테스트를 진행해볼까요?</p><p>우선 레포의 Actions탭으로 이동하면 아래와 같이 워크플로우가 생성되어있음을 확인할 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/0*7DBt1-xtEWZW229n" /></figure><p>단 위의 워크 플로우 자체는 “실패 시 merge 금지” 의 동작을 의미하지 않습니다.</p><p>별도의 설정이 필요하며 설정 순서는 다음과 같습니다</p><ol><li>해당 레포의 Settings페이지로 이동</li><li>Branch 클릭</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*e6YxBf5lseMYhFgw" /></figure><p>3. Add branch protection rule 클릭</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YTC4PhZra0mRk2Sb" /></figure><p>4. Branch name pattern에 적용할 브랜치명 작성</p><p>5. Require status checks to pass before merging 체크</p><p>6. Require branches to be up to date before merging 체크 및 생성한 워크플로우 선택</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/0*LTYbg7p4-6t-F_3I" /></figure><p>이제 임의로 브랜치를 만들어 테스트에 실패하도록 가정하고, develop브랜치에 PR을 요청하면 다음과 같이 테스트 실패 결과가 화면에 나타나며 merge할 수 없도록 되어있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/0*HUY2zhofON-MJplA" /></figure><p>그리고 의도적으로 틀린 부분을 다시 고치고 push하면 설정된 트리거에 의해 다시 워크플로우가 실행되면서 정상적으로 merge버튼이 활성화 되어 의도한 동작이 잘 돌아가는것을 확인할 수 있었습니다 🙌</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/0*zb4lyED0z1UWshoF" /></figure><h3>3.3 시크릿 키 관리</h3><p>배포와 관련된 설정등 때로는 환경변수를 별도로 분리해야할 때가 있습니다.</p><p>이때는 아래와 같이 사용합니다.</p><pre>name: DEPLOY<br>on:<br>  push:<br>    branches:<br>      - master<br>jobs:<br>  deploy:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - name: Checkout code<br>        uses: actions/checkout@v2<br><br>      - name: Configure AWS credentials<br>        uses: aws-actions/configure-aws-credentials@v1<br>        with:<br>          aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}<br>          aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}<br>          aws-region: ap-northeast-2<br><br>      - name: Build and Deploy<br>        run: |<br>          yarn install<br>          yarn build<br>          yarn ci-deploy<br><br>      - name: Invalidate CloudFront cache<br>        run: |<br>          aws cloudfront create-invalidation --distribution-id ${{ secrets.CLOUDFRONT_DISTRIBUTION_ID }} --paths &quot;/*&quot;</pre><p>위의 코드는 master브랜치에 push가 되면 aws에 배포하는 워크플로우 내용이며 AWS와 CloudFront에 접근하기 위한 인증정보를 별도의 시크릿키로 분리하고 관리하고 있습니다.</p><p>이러한 시크릿 설정은 다음과 같은 단계를 따릅니다</p><ol><li>GitHub의 프로젝트 페이지로 이동합니다. 그리고 상단 메뉴에서 “Settings”를 클릭합니다.</li><li>Settings 페이지 내의 사이드바에서 “Secrets”를 선택합니다.</li><li>이어서 “New repository secret” 버튼을 클릭합니다.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cNikazUGTnSVV89d" /></figure><p>4. 새로운 창에서 시크릿의 이름을 입력하고, 값(value) 필드에 시크릿 값을 입력합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/0*Zoi0r01xemWb4KH1" /></figure><ul><li>이때 대문자와 밑줄만을 사용해야 합니다</li></ul><p>이러한 설정을 마치면 워크 플로우 파일에서 secrets.MY_SECRET 등으로 접근해서 사용할 수 있습니다.</p><h3>참고 자료</h3><p><a href="https://satisfactoryplace.tistory.com/361">https://satisfactoryplace.tistory.com/361</a></p><p><a href="https://docs.github.com/ko/actions">https://docs.github.com/ko/actions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b8b5087bb66" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[에러를 놓치지 않는 방법, Sentry 도입]]></title>
            <link>https://medium.com/@teawon.jeong.dev/%EC%97%90%EB%9F%AC%EB%A5%BC-%EB%86%93%EC%B9%98%EC%A7%80-%EC%95%8A%EB%8A%94-%EB%B0%A9%EB%B2%95-sentry-%EB%8F%84%EC%9E%85-68b76725025d?source=rss-d580fa80743e------2</link>
            <guid isPermaLink="false">https://medium.com/p/68b76725025d</guid>
            <category><![CDATA[sentry]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Teawon]]></dc:creator>
            <pubDate>Wed, 29 Nov 2023 08:15:06 GMT</pubDate>
            <atom:updated>2023-11-29T08:15:06.195Z</atom:updated>
            <content:encoded><![CDATA[<h3><a href="https://teawon.github.io/react/Sentry/">에러를 놓치지 않는 방법, Sentry 도입 가이드</a></h3><h3>1. 개요</h3><blockquote>“혹시 어떤 상황에서 발생하셨나요?, 저는 재현이 안되는데요??”</blockquote><p>회사에서 개발을 하다가 팀원분께서 때때로 에러상황에 대해 전달해주실때가 종종 있습니다.</p><p>문제는 발생상황을 말씀해주셔도 재현이 안되거나, 하나하나 전달받을때마다 처리하는게 좋은 구조는 아니라고 생각했어요.</p><p>발생 당시의 로그를 파악해야하고, 그나마 배포전에 발견해서 망정이지 실 사용자에게 로그를 찍어달라고 부탁할 수는 없기때문입니다.</p><p>더군다나 사용자의 브라우저에 따라 호환성문제도 각기 다르게 발생할 수 있기 때문에 에러를 추척하고 모니터링하기 위한 기술은 필수적이라고 생각했습니다.</p><p>이런 상황이 발생했을 때 빠르게 대응할 수 있는 도구가 있으면 어떨까요?</p><h3>2. Sentry</h3><p>Sentry란 실시간으로 에러를 추적하고, 분석하여 알려주는 오픈 소스 서비스입니다.</p><p>에러에 대한 알림, 사용자의 브라우저나 기기 정보 및 이러한 정보를 대시보드형태로 시각화하고 에러를 추적하기 쉽게 도와주는 여러가지 서비스를 제공해주고 있습니다.</p><p>Sentry는 이러한 과제를 효과적으로 수행할 수 있는 강력한 도구로, 팀의 생산성 향상과 사용자 만족도 향상에 크게 기여할 수 있습니다</p><h3>2.1 사용법</h3><ol><li><a href="https://sentry.io/welcome/">https://sentry.io/welcome/</a> 사이트를 통해 회원가입을 진행</li><li>프로젝트를 생성</li><li>React에서 SDK 설정</li></ol><pre>yarn add @sentry/react</pre><pre>// index.tsx<br><br>// Sentry에서 제공하는 기본 시작 세팅<br><br>Sentry.init({<br>  dsn: &quot;your key&quot;, // Sentry 서버에 로그를 보내는데 필요한 인증 정보<br>  integrations: [<br>    new Sentry.BrowserTracing({<br>      tracePropagationTargets: [<br>        &quot;localhost&quot;,<br>        /^https:\/\/yourserver\.io\/api/,<br>      ],<br>    }),<br>    new Sentry.Replay(),<br>  ],<br>  // Performance Monitoring<br>  tracesSampleRate: 1.0, // 데이터 샘플링 비율 설정<br>  // Session Replay<br>  replaysSessionSampleRate: 0.1,<br>  replaysOnErrorSampleRate: 1.0,<br>});</pre><p>4. 에러 발생시키기</p><pre>import * as Sentry from &quot;@sentry/react&quot;;<br><br>  const causeCustomError = () =&gt; {<br>    try {<br>      throw new Error(&quot;커스텀 에러 발생&quot;);<br>    } catch (error) {<br>      console.error(error);<br>      Sentry.captureException(error); // 에러를 Sentry에 전송<br>    }<br>  };<br><br><br>{...}<br><br>return (<br>    &lt;div&gt;<br>      &lt;button onClick={causeCustomError}&gt; Custom Error&lt;/button&gt;<br>    &lt;/div&gt;<br>  );</pre><h3>2.2 기본 옵션</h3><p><strong>[Sentry SDK 설정 옵션]</strong></p><p>dsn</p><ul><li>SDK에게 이벤트를 어디로 보낼지 알려주는 식별자</li><li>보안을 위해 별도의 env파일로 관리</li></ul><p>release</p><ul><li>애플리케이션의 버전을 표현하기 위해 사용</li><li>각 릴리즈별로 오류 추적이 가능하기때문에 릴리즈별로 오류를 분석하기 용이</li></ul><p>tracesSampleRate</p><ul><li>Sentry에 보내는 트랜잭션의 샘플 비율 (0.0 ~ 1.0)</li><li>너무 많은 이벤트를 기록하지 않도록 부하를 조절</li></ul><p>replaysSessionSampleRate</p><ul><li>Sentry SDK에서 세션 리플레이 기능의 샘플링 비율을 제어</li></ul><p>replaysOnErrorSampleRate</p><ul><li>오류가 발생한 세션 중 어느 정도의 비율로 리플레이 데이터를 수집할지 결정</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*23_ibAOI5ZaGrIzH" /></figure><blockquote>Replay란 위 영상처럼 에러가 발생한 상황이 그대로 녹화되는 기능</blockquote><p>maxBreadcrumbs</p><ul><li>최대 breadcrumb의 양을 제어 (최근 n개의 데이터만 유지하고 삭제한다)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/0*wBsgay6SHRriBd-M" /></figure><blockquote>breadcrumb란 오류가 발생하기 이전에 어떤 일이 일어났는지 표현해주는 Sentry의 기능 중 하나</blockquote><p>tracePropagationTargets</p><ul><li>설정된 URL 패턴에 대해서만 추적 정보를 전파</li></ul><p>그 밖의 옵션은 <a href="https://docs.sentry.io/platforms/javascript/configuration/options/?original_referrer=https%3A%2F%2Ftech.kakaopay.com%2F">공식문서</a>을 참고</p><p><strong>[에러 전송 메서드]</strong></p><p>captureException</p><ul><li>예외 객체를 인자로 받아 Sentry에 에러를 보고</li></ul><pre>try {<br>  // Potentially erroneous code<br>  const value = someFunctionThatMightThrow();<br>} catch (error) {<br>  Sentry.captureException(error);<br>}</pre><p>captureMessage</p><ul><li>문자열 메시지를 인자로 받아 Sentry에 에러를 보고</li></ul><pre>if (someUnexpectedCondition) {<br>  Sentry.captureMessage(&quot;에러가 발생했습니다.&quot;);<br>}</pre><h3>2.3 에러를 구분짓기</h3><p>위 방식에 더해서, 수 많은 에러들을 무분별하게 수집하고 관리한다면 문제점을 빠르게 파악하고 관리하기 쉽지 않을 것 입니다. 사실 중요하게 확인해야하는 에러는 따로 있을테니까요</p><p>이를 위해 Sentry에서는 에러의 중요도를 구분짓거나 정보를 보내는 방법을 제공하고있습니다.</p><h4>2.3.1 Scope</h4><p>Scope는 Sentry에서 이벤트를 캡처하기 전에 이벤트 데이터에 추가 정보를 추가하거나 수정할 수 있는 방법으로</p><p>특정 범위(Scope) 내에서 발생한 모든 이벤트는 해당 범위에 설정된 매개변수와 함께 전송됩니다.</p><p>configureScope</p><ul><li>글로벌 scope에 대한 설정을 적용합니다 (모든 이벤트에 대해 공통적용)</li><li>사용자 정보 등</li></ul><pre>Sentry.configureScope(function (scope) {<br>  scope.setTag(userType, &quot;admin&quot;);<br>  scope.setUser({ email: &quot;admin@example.com&quot; });<br>});<br><br>Sentry.captureException(new Error(&quot;This is another error&quot;));</pre><p>withScope</p><ul><li>해당 범위에서만 설정을 적용합니다</li><li>에러 상황에 대한 상세 내용</li></ul><pre>Sentry.withScope(function (scope) {<br>  scope.setTag(&quot;page_locale&quot;, &quot;en-US&quot;);<br>  scope.setLevel(Sentry.Severity.Warning);<br><br>  Sentry.captureException(new Error(&quot;This is an error&quot;));<br>});</pre><p>Scope에서 사용할 수 있는 메서드들</p><ul><li>setTag: 이벤트에 태그를 추가합니다.</li><li>setUser: 이벤트에 사용자 정보를 추가합니다.</li><li>setLevel: 이벤트의 중요도 레벨을 설정합니다.</li><li>setExtras: 이벤트에 추가 데이터를 추가합니다.</li><li>addEventProcessor: Scope에 이벤트 프로세서를 추가하여 이벤트 데이터를 수정하거나 조작할 수 있습니다.</li></ul><p>즉 Scope에 따라 에러 추적에 있어서 필요한 메타데이터를 추가하고, 로깅을 더욱 효과적으로 수행할 수 있도록 돕습니다.</p><h4>2.3.2 Level</h4><p>레벨 설정은 로깅 시스템에서 중요한 부분으로, 로그 메시지가 얼마나 심각한지를 나타내는 데 사용됩니다</p><p>개별 이벤트에 대한 레벨 설정</p><pre>Sentry.captureMessage(&quot;디버그 레벨의 에러 발생&quot;, &quot;debug&quot;);</pre><p>Scope 내부에서 정의</p><pre><br>Sentry.withScope(function (scope) {<br>  scope.setLevel(&quot;fatal&quot;);<br><br>  Sentry.captureException(new Error(&quot;매우 심각한 에러 발생&quot;));<br>});</pre><p>순서대로 fatal, error, warning, log, info, debug 레벨정보가 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HoBsT9zijnK8B5qe" /></figure><blockquote>Sentry 이벤트의 레벨을 세밀하게 제어할 수 있으며, 이를 통해 로그의 중요도를 구분하고 관리할 수 있다</blockquote><h4>2.3.3 Context</h4><p>개별 에러 이벤트에 대해 추가정보를 제공하기 위해 context를 설정할 수 있습니다.</p><p>기본적으로 에러 발생 시각, 사용자 기기, 브라우저, 에러 타입등 발생정보를 확인할 수 있으나, 기타 세부정보를 추가적으로 기록하면 발생한 에러에 대한 정보와 영향을 쉽게 확인할 수 있겠죠</p><pre>const causeNetworkError = async () =&gt; {<br>  try {<br>    const response = await fetch(<br>      &quot;https://api.causeNetworkError.com/causeNetworkError&quot;<br>    );<br><br>    if (!response.ok) {<br>      throw new Error(&quot;Network error: &quot; + response.statusText);<br>    }<br>  } catch (error) {<br>    console.error(error);<br>    Sentry.withScope((scope) =&gt; {<br>      scope.setContext(&quot;apiInfo&quot;, {<br>        url: &quot;https://api.causeNetworkError.com/causeNetworkError&quot;,<br>        method: &quot;GET&quot;,<br>        status: 401,<br>        // (헤더, 파라미터 등의 추가정보 등록)<br>      });<br>      scope.setTag(&quot;errorType&quot;, &quot;NetworkError&quot;); // 태그 설정<br>      scope.setLevel(&quot;fatal&quot;); // 레벨 설정<br>      Sentry.captureException(error); // 에러를 Sentry에 전송<br>    });<br>  }<br>};</pre><blockquote>api와 같이 문제상황을 식별할 수 있는 정보를 추가로 담으면 로깅에 더 용이</blockquote><h4>2.3.3 Fingerprint</h4><p>Sentry는 기본적으로 오류 스택 트레이스를 사용하여 오류를 그룹화합니다.</p><p>그러나 경우에 따라 사용자는 이러한 그룹화 방식을 더 세밀하게 제어하고 싶을 수 있겠죠. 이 때 fingerprint를 사용하여 오류를 원하는 방식으로 그룹화할 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zdZnRxztvBYobHDy" /></figure><blockquote>AxiosError가 모두 하나로 그룹화되어 표현된다.</blockquote><blockquote>에러 상태를 확인하려면 그룹내부에서 하나하나 내용을 확인해서 불편</blockquote><p>이때 Sentry.withScope 메서드를 사용하여 fingerprint를 설정할 수 있습니다.</p><p>Api의 경우 상태코드에 따라 name속성을 바꾸면 더 구체적인 명칭으로 에러를 그룹화하고 확인할 수 있습니다.</p><pre> {...}<br><br>    Sentry.withScope((scope) =&gt; {<br><br>      scope.setFingerprint([<br>        originalRequest.method,<br>        error.response?.status,<br>        originalRequest.url,<br>      ]);<br><br>      error.name = errorType;<br>      Sentry.captureException(error);<br>    });</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cvzdiOlya5doTiV4" /></figure><blockquote>method, url , status에 따라 그룹핑을 하고, 상태코드에 따라 적절한 명칭을 부여</blockquote><h3>3 Source Map</h3><p>소스맵을 사용하지 않으면 기본적으로 에러가 발생된 코드의 위치가 표현되지 않습니다.</p><p>왜냐하면 배포 프로세스를 거치면 최적화,난독화,최소화 같은 변환 프로세스를 거쳐 원본 소스코드와 다르게 배포되기때문에 에러가 발생한 위치도 원본 소스 코드와 매칭할 수 없기 때문입니다.</p><p>소스맵은 이러한 문제점을 해결하기 위해 변환된 코드와 원본 코드 사이의 매핑을 제공합니다.</p><h3>3.1 소스맵 업로드</h3><p>Webpack을 기준으로 아래의 방법을 사용했습니다. 상세한 내용은 <a href="https://docs.sentry.io/platforms/javascript/guides/wasm/sourcemaps/uploading/webpack/">공식문서</a>를 참고해주세요</p><ol><li>플러그인 설치</li></ol><pre>yarn add @sentry/webpack-plugin --save-dev</pre><p>2. 웹팩 설정 수정</p><pre>const { sentryWebpackPlugin } = require(&quot;@sentry/webpack-plugin&quot;);<br><br>module.exports = {<br>  // ... other config above ...<br><br>  devtool: &quot;source-map&quot;,<br>  plugins: [<br>    sentryWebpackPlugin({<br>      org: &quot;example-org&quot;,<br>      project: &quot;example-project&quot;,<br>      authToken: process.env.SENTRY_AUTH_TOKEN,<br>    }),<br>  ],<br>};</pre><p>여기서 SENTRY_AUTH_TOKEN의 경우 Sentry 사이트에서 API 토큰을 생성해야합니다.</p><p>이 정보는 Sentry API에 요청을 보낼 때 사용되며, 이를 통해 사용자의 인증을 검증하고 Sentry 프로젝트에 접근을 허용합니다.</p><p>환경변수 파일은 .env.sentry-build-plugin 파일에 정의해 빌드시 자동으로 소스맵을 서버에 자동으로 업로드 될 수 있도록 합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_TcWq4VH42ySnmjk" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cd0U4MQtN25EPEzZ" /></figure><blockquote>소스맵 사용 전 / 후</blockquote><h3>4. 알림 보내기</h3><p>자 이제, 수집된 로그를 분석하고 에러를 빠르게 해결해야합니다.</p><p>가장 좋은 방법은 특정 문제상황에 대해 메일이나 Slack을 통해 빠르게 발생한 에러를 리포트해야겠죠.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MN1MXdxbydB9mWiO" /></figure><blockquote>횟수, 에러 종류, 문제 상황을 필터링하고 알림을 보낼 수 있다.</blockquote><blockquote><a href="https://docs.sentry.io/product/integrations/notification-incidents/slack/">문서</a>참고</blockquote><p>결과</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CyVocYLrp5HdADp8" /></figure><h3>5. 사용 후기</h3><p>Sentry를 사용하고나서, 몇 가지 실수했던 부분과 추가했던사항들이 있었습니다.</p><p><strong>[클래스 상속을 통한 타입명시]</strong></p><p>초기에는, 각 에러 로깅을 명확히 하기 위해 status코드에 따라 별도의 상수를 만들고 error.name속성을 직접 바꾸는 식으로 작업을 했었습니다.</p><pre>if (error.response) {<br>  const { status } = error.response;<br>  errorType = STATUS_CODE_ERROR_MAP[status] || DEFAULT_ERROR_TYPE;<br>}<br><br>// {...}<br><br>Sentry.withScope((scope) =&gt; {<br>  scope.setContext(&quot;API Request Info&quot;, {<br>    url: originalRequest.url,<br>    method: originalRequest.method,<br>    status: error.response?.status,<br>    params: originalRequest.params,<br>    headers: originalRequest.headers,<br>  });<br><br>  scope.setContext(&quot;API Response Info&quot;, {<br>    data: JSON.stringify(error.response?.data, null, 2),<br>    headers: error.response?.headers,<br>  });<br><br>  scope.setFingerprint([<br>    originalRequest.method,<br>    error.response?.status,<br>    originalRequest.url,<br>  ]);<br><br>  error.name = errorType; // 여기서 이름을 지정해서, Sentry로깅에 에러타입이 명시되도록 수정<br>  Sentry.captureException(error);<br>});</pre><p>그런데, 기존 플로우에 문제가 생겨서 에러를 표현하는 Snackbar가 나타나지 않는 문제가 발생했습니다.</p><p>원인은 참조타입인 에러 객체 자체의 속성을 변경해버려서, 다른 곳의 코드에도 영향을 미쳤던게 원인이였고</p><p>아래와 같이 에러 로깅을 위한 에러타입의 지정은 별도의 객체를 새로 생성해서 요청하도록 코드를 수정했습니다.</p><pre>Sentry.withScope((scope) =&gt; {<br>  scope.setContext(&quot;API Request Info&quot;, {<br>    url: originalRequest.url,<br>    method: originalRequest.method,<br>    status: error.response?.status,<br>    params: originalRequest.params,<br>    headers: originalRequest.headers,<br>  });<br><br>  scope.setContext(&quot;API Response Info&quot;, {<br>    data: JSON.stringify(error.response?.data, null, 2),<br>    headers: error.response?.headers,<br>  });<br><br>  scope.setFingerprint([<br>    originalRequest.method,<br>    error.response?.status,<br>    originalRequest.url,<br>  ]);<br><br>  Sentry.captureException(new SentryLoggingError(error)); // 별도의 Error객체를 새로 생성 후 처리<br>});<br><br>export class SentryLoggingError extends Error {<br>  constructor(error) {<br>    super(error.message);<br>    this.name = error.response.statusText;<br>    this.stack = error.stack;<br>    this.config = error.config;<br>    this.response = error.response;<br>  }<br></pre><p>추가로 statusText를 사용해서 에러이름을 처리했는데, 별도로 에러 타입에 따른 상수를 처리하지 않아도 의미가 식별되고,</p><p>모든 상태코드에 대한 상수를 다 정의하지 않아도 된다는 장점이 있어서 일단 해당 필드값을 이용했습니다.</p><p>물론 향후에 상태코드에 따라 다른 statusText를 분리해야한다면 별도의 상수로 분리를 해야겠지만요.</p><p><strong>[Error Boundary의 도입]</strong></p><p>사실 처음 Sentry의 도입 의도는 버그를 빠르게 고치고, 디버깅을 용이하게 하기 위함이였습니다.</p><p>그리고 거기서 가장 중요했던 버그는 <strong>예상치 못한 에러로 인해 앱이 중단되고, 흰 페이지가 화면상에 표현되는 문제점</strong>이였죠.</p><p>이 에러를 포착했을때, 별도의 에러로깅을 남기기 위해서는 이 트리거를 포착하고 로그를 보낼 필요가 있었습니다.</p><p>여기서 React의 Error Boundary를 도입해 로깅과 더불와 사용자에게 별도의 페이지를 렌더링 할 수 있도록 추가적인 작업을 진행했습니다.</p><blockquote>ErrorBoundary란?</blockquote><blockquote>React 컴포넌트로, 그 하위 컴포넌트 트리에서 발생하는 JavaScript 오류를 잡아내고, 오류 메시지를 표시하거나 대체 UI를 렌더링하는 데 사용.</blockquote><blockquote>일반적으로, JavaScript에서 오류가 발생하면 전체 앱이 중단될 수 있지만, ErrorBoundary를 사용하면 특정 컴포넌트의 하위 트리에서만 오류가 처리되고 앱의 나머지 부분은 정상적으로 동작한다.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*Iwz0Q-v2Rh7Rfv5J" /></figure><blockquote>앱이 중단되었을때 별도의 페이지를 렌더링함으로써 사용자 경험을 높이고, 이 상황에 대한 Slack알림을 보내도록 처리</blockquote><p><strong>[배포와 개발환경의 분리]</strong></p><pre>if (process.env.NODE_ENV === &quot;production&quot;) {<br>  Sentry.init({<br>    dsn: process.env.REACT_APP_SENTRY_DSN,<br>    integrations: [<br>      new Sentry.BrowserTracing({<br>        tracePropagationTargets: [process.env.example_1, process.env.example_2],<br>      }),<br>      new Sentry.Replay(),<br>    ],<br>  });<br>}</pre><p>로컬환경에서 발생하는 무분별한 로그기록을 분리하기 위해 production환경에서만 에러를 수집할 수 있도록 조건문을 추가하였습니다.</p><p>그래서 저는 결과적으로 Sentry도입을 통해 아래와 같은 이점을 얻을 수 있었다고 생각합니다.</p><ol><li>에러 상황을 빠르게 감지하고, 해결에 용이하도록 디버깅 제공</li><li>사용자 환경 (특히 브라우저..!)에 따른 특정 에러 확인</li></ol><blockquote>이전에 웹사이트 버전에 따라 Array.at()함수를 지원하지 않아 브라우저환경에 종속되는 에러가 발생한 케이스도 있었습니다.</blockquote><p>3. 에러를 재현하지 못해 겪었던 찝찝함의 해소</p><p>버그가 발생하지 않도록 개발하는게 가장 이상적이겠지만, 완전한 무결점의 프로그램을 만드는건 불가능하다고 생각합니다.</p><p>다만 빠르게 버그를 찾아 수정할 수 있는 개발환경을 마련하고 계속해서 개선해나아가야했고 이런 부분에 도움을 주는 Sentry를 도입했던게 좋은 경험이 되었던거같습니다.</p><h3>참고자료</h3><p><a href="https://tech.kakaopay.com/post/frontend-sentry-monitoring/">https://tech.kakaopay.com/post/frontend-sentry-monitoring/</a></p><p><a href="https://speakerdeck.com/kakao/sentryreul-iyonghan-ereo-cujeoggi-reactyi-seoneonjeog-ereo-ceori">https://speakerdeck.com/kakao/sentryreul-iyonghan-ereo-cujeoggi-reactyi-seoneonjeog-ereo-ceori</a></p><p><a href="https://docs.sentry.io/platforms/javascript/guides/react/?original_referrer=https%3A%2F%2Ftech.kakaopay.com%2F">공식문서</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68b76725025d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React에서 Next.js로, 마이그레이션 경험기]]></title>
            <link>https://medium.com/@teawon.jeong.dev/react%EC%97%90%EC%84%9C-next-js%EB%A1%9C-%EB%A7%88%EC%9D%B4%EA%B7%B8%EB%A0%88%EC%9D%B4%EC%85%98-%EA%B2%BD%ED%97%98%EA%B8%B0-6dc4d800716b?source=rss-d580fa80743e------2</link>
            <guid isPermaLink="false">https://medium.com/p/6dc4d800716b</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Teawon]]></dc:creator>
            <pubDate>Sat, 25 Nov 2023 13:46:21 GMT</pubDate>
            <atom:updated>2023-11-25T13:46:21.635Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. 마이그레이션 배경</h3><p>현재 진행 중인 프로젝트는 커뮤니티 기반의 서비스로, 사용자들이 다양한 정보와 지식을 공유하는 플랫폼입니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*h4FxoxrUIC2GqRam" /></figure><blockquote>하나의 페이지에서 글 작성, 조회, 댓글 작성 등 핵심 상호작용 요소를 처리</blockquote><p>이러한 특성상, 사용자의 참여와 콘텐츠의 가시성은 핵심 요소라고 생각했으며 SEO 성능의 향상은 프로젝트에 있어 매우 중요한 고려사항이 되었습니다. 검색 엔진을 통한 새로운 방문자의 유입과 콘텐츠의 더 넓은 확산을 위해서는 검색 엔진에 최적화되어야 했습니다.</p><p>또한 프로젝트의 핵심이 되는 주요 페이지는 다양한 상호작용이 중심이 되는 곳입니다. 그러나 이 페이지의 로딩 속도가 상대적으로 느려 사용자 경험에 부정적인 영향을 미치고 있었습니다. 이는 우리 서비스의 핵심 가치인 빠르고 효율적인 사용자 경험을 제공하는 데 장애가 되었습니다.</p><p>이러한 문제들을 해결하기 위해, React에서 Next.js로의 전환을 결정했습니다. Next.js의 서버 사이드 렌더링(SSR) 기능은 초기 페이지 로딩 속도를 크게 향상시킬 뿐만 아니라, SEO 최적화에도 큰 이점을 제공합니다. 이러한 기술적 전환을 통해, 사용자 경험을 개선하고, 검색 엔진을 통한 콘텐츠의 더 넓은 확산을 기대하였습니다.</p><h3>2. Next</h3><p>Next.js는 React 기반의 전체 스택 웹 애플리케이션을 구축하기 위한 프레임워크입니다. 사용자 인터페이스 구축을 위해 React 컴포넌트를 사용하고, 추가적인 기능과 최적화를 위해 Next.js를 활용합니다.</p><p>핵심 특징으로는 아래 요소가 있습니다.</p><p>라우팅: 파일 시스템 기반 라우터로, 레이아웃, 중첩 라우팅, 로딩 상태, 오류 처리 등을 지원합니다.</p><p>렌더링: 클라이언트 사이드 및 서버 사이드 렌더링 지원. 서버에서 정적 및 동적 렌더링을 최적화합니다. Edge 및 Node.js 런타임에서 스트리밍 지원.</p><p>데이터 페칭: 서버 컴포넌트에서 async/await을 사용한 간소화된 데이터 페칭. 요청 메모이제이션, 데이터 캐싱 및 재검증을 위한 확장된 fetch API 지원.</p><p>스타일링: CSS 모듈, Tailwind CSS, CSS-in-JS를 포함한 선호하는 스타일링 방법 지원.</p><p>최적화: 이미지, 글꼴 및 스크립트 최적화를 통해 애플리케이션의 핵심 웹 바이탈과 사용자 경험 개선.</p><p>TypeScript: 더 나은 타입 체킹과 효율적인 컴파일 지원, 사용자 정의 TypeScript 플러그인 및 타입 체커 지원.</p><blockquote><a href="https://nextjs.org/docs">공식문서</a></blockquote><p>저는 Next.js의 13버전을 사용했습니다. (2023년 11월 24일 현재 최신 버전은 14)</p><h3>3. 개선 결과</h3><p>이 부분에서는 동일한 API 서버를 대상으로 React와 Next.js의 코드 내용을 비교하며 얻은 결과를 다룹니다. (배포 환경)</p><h3>3.1 SEO</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ko_TsWDkfrMbyzwd" /></figure><blockquote>React</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EXzkQN6tSFGU7jfx" /></figure><blockquote>Next</blockquote><p>위 이미지는, Google Lighthouse를 통해 측정한 메인페이지의 지표입니다.</p><p>실제 SEO지표가 80에서, 100으로 유의미한 상승을 가져왔습니다.</p><p>React의 경우 메타 데이터 작성을 위해서는 별도의 라이브러리를 사용하거나 &lt;head&gt; 태그 내에 직접적으로 설정해야합니다.</p><p>이와 대조적으로 Next.js에서는 서버 사이드에서 동적으로 메타 데이터를 생성하고 관리할 수 있는 기능과 더불어, 페이지별로 레이아웃 기반의 메타 데이터 설정이 가능합니다.</p><p>따라서 상대적으로 쉽고 상세한 메타데이터를 보다 직관적으로 관리할 수 있는 이점이 크게 느껴졌습니다.</p><pre>// layout.tsx<br>export const metadata: Metadata = {<br>  title: &quot;Mindspace&quot;,<br>  description:<br>    &quot;Mindspace는 개발에 관련된 각 키워드를 노드와 노드 사이의 연결 관계로 표현하여 사용자에게 학습 방향을 제공하는 사이트입니다.&quot;,<br>  keywords: &quot;개발, 프로그래밍, 학습, 연결 관계, 노드, 키워드&quot;,<br>  metadataBase: new URL(&quot;http://localhost:3000&quot;), //FIXME : 향후 실제 도메인으로 수정<br>  openGraph: {<br>    title: &quot;Mindspace&quot;,<br>    description:<br>      &quot;Mindspace는 개발에 관련된 각 키워드를 노드와 노드 사이의 연결 관계로 표현하여 사용자에게 학습 방향을 제공하는 사이트입니다.&quot;,<br>    images: [<br>      {<br>        url: &quot;/images/logo.png&quot;,<br>      },<br>    ],<br>    type: &quot;website&quot;,<br>  },<br>};</pre><p>CSR을 사용하는 React 애플리케이션은 초기에 서버에서 빈 HTML을 불러온 후, 실제 콘텐츠를 클라이언트 측 JavaScript가 실행된 후에 화면에 표시합니다. 이 구조는 검색 엔진이 페이지의 핵심 콘텐츠를 제대로 인식하지 못하게 하여 SEO 순위에 부정적인 영향을 미칩니다.</p><p>반면, SSR을 사용하는 Next.js는 서버에서 페이지의 전체 HTML을 렌더링하고 필요한 콘텐츠와 데이터를 포함해 클라이언트에 전송합니다. 이 접근 방식은 검색 엔진이 페이지 콘텐츠를 즉시 인식하고 색인화할 수 있게 하여, SEO 성능을 크게 향상시키므로 이러한 부분도 점수 향상에 긍정적인 영향을 미쳤습니다.</p><p><a href="https://teawon.github.io/cs/csr-ssr/">관련 블로그 글</a></p><h3>3.2 초기 로딩 속도</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AXGU68ODqUHtMXa7" /></figure><blockquote>React</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LLNyRor70WB29gGV" /></figure><blockquote>Next</blockquote><p>이어서, 핵심 페이지의 Lighthouse 측정 지표 결과입니다. 실제 Performance 점수에서 차이가 두드러졌는데 실질적인 내용을 분석해보았습니다.</p><ol><li>api 요청 속도 비교</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/395/0*PfRpi_fQATvPQDNH" /></figure><blockquote>React에서의 “노드정보 반환 API” 응답 시간</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/395/0*pvDsjgTQ7v1bbbW8" /></figure><blockquote>Next.js에서의 “노드정보 반환 API” 응답 시간</blockquote><p>React에서는 API의 응답 시간이 약 10ms로 나타났습니다. 이는 클라이언트 사이드 렌더링(CSR) 방식에서 데이터를 브라우저에서 직접 처리하기 때문에 발생하는 짧은 응답 시간을 나타냅니다.</p><p>반면, SSR을 적용한 Next.js에서는 동일한 API 요청에 더 많은 시간이 소요되었습니다. SSR 환경에서 서버가 콘텐츠 렌더링을 담당하고, 이를 클라이언트에 전송하면서 데이터 처리와 전달에 추가 시간이 필요합니다. 이는 서버가 데이터를 불러와 HTML을 생성하는 과정에서 발생하는 지연 때문입니다.</p><p>이러한 결과에도 불구하고, Next.js의 초기 페이지 로딩 속도는 React보다 빠르게 나타났습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Qm3t2hFVKaQChqZ5" /></figure><blockquote>React</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-e0zy_A30p-ut8NF" /></figure><blockquote>Next</blockquote><p>실제 타이밍 지표 정보는 아래와 같습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*X0mJatFUVXqfqhqUONCkDA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kbsnG-UKstFLgr7H" /></figure><blockquote>FP(First Paint)는 웹 페이지 로딩 과정에서 사용자가 화면에 처음으로 어떤 시각적 변경을 볼 수 있는 시점</blockquote><blockquote>FM (First Meaningful Paint): 페이지의 주요 콘텐츠가 화면에 표시되기 시작하는 시점</blockquote><blockquote>FCP (First Contentful Paint): 페이지의 첫 번째 콘텐츠가 화면에 표시되기 시작하는 시점</blockquote><blockquote>DCL (DOMContentLoaded): HTML 문서가 완전히 로드되고 파싱되었지만, 스타일시트, 이미지, 프레임 같은 하위 리소스는 로드 중일 수 있는 시점</blockquote><blockquote>LCP (Largest Contentful Paint): 페이지의 가장 큰 콘텐츠가 화면에 표시된 시점</blockquote><blockquote>L(Onload Event) (Load): 전체 페이지와 모든 관련된 리소스가 완전히 로드된 시점</blockquote><p>이러한 결과는 두 프레임워크의 렌더링 방식 차이에서 비롯된다고 생각합니다.</p><p>React의 CSR(Client-Side Rendering)에서는 초기 콘텐츠 렌더링이 JavaScript 로드와 실행에 의존하기 때문에 상대적으로 늦게 나타났습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rp58g0fuUWLCqqRf" /></figure><p>반면, Next.js는 서버 사이드 렌더링(SSR)을 활용하여 초기에 서버로부터 받아온 HTML을 별도의 JavaScript 실행 없이 빠르게 화면에 표현합니다. 그러나 LCP와 전체 리소스 로드 시점간의 간격이 React에 비해 크게 나타났습니다. 이와 같은 간극은 사용자에게 혼란을 줄 수 있으며, 사용자 경험 측면에서는 주의 깊게 고려해야겠죠</p><p>아무튼 위의 결과는 Next.js의 최적화 로직이 어느 정도 반영되었다는 점을 감안할 때, 순수 SSR과 CSR 간의 속도 차이를 완전히 명확하게 평가하기는 어렵지만, 속도 측면에서의 이점은 분명하다고 생각합니다.</p><h3>4. 트러블 슈팅</h3><p>React에서 Next.js로의 마이그레이션을 시작할 때, 같은 React 기반 프레임워크라는 점에서 순조롭게 진행될 줄 알으나 실제 과정은 이러한 기대와는 달랐습니다😥</p><p>아래는 겪었던 이슈입니다.</p><ol><li>라이브러리 호환성 문제</li></ol><ul><li>Lottie, React-force-graph , TOAST-UI와 같이 사용하던 라이브러리에서 SSR지원을 해주지 않아 라이브러리를 동적으로 import하는 방식으로 코드를 수정해야 했습니다.</li></ul><pre>export default async function HydratedNode() {<br>  const MapPage = dynamic(() =&gt; import(&quot;./map&quot;), {<br>    ssr: false,<br>  });<br><br>{ ... }<br><br>return (<br>    &lt;HydrateOnClient state={dehydratedState}&gt;<br>      &lt;MapPage /&gt;<br>    &lt;/HydrateOnClient&gt;<br>  );<br>}</pre><ul><li>특히 서버 컴포넌트에서 사용해야 했던 로딩 컴포넌트는 Lottie와의 호환성 문제로 인해 다른 이미지 확장자로 변경하는 등의 조치가 필요했습니다.</li></ul><p>2. 로그인 토큰 관리</p><ul><li>SSR 환경에서는 기존에 로컬 스토리지에 저장되던 토큰 정보에 접근할 수 없었습니다. 이에 따라 토큰을 쿠키에 저장하는 방식으로 로직을 변경했습니다.</li></ul><p>3. 라우팅 관리</p><ul><li>React의 react-router-dom을 사용하는 대신, Next.js에서는 폴더 구조 기반의 라우팅을 사용했습니다. 이에 따라 로그인 권한 체크 및 라우팅 관리를 위해 미들웨어를 도입했습니다.</li><li><a href="https://teawon.github.io/next/auth-router-handle/">관련 블로그 링크</a></li></ul><p>4. Axios에서 Fetch로의 전환</p><ul><li>공식 문서에서는 Fetch 사용을 권장했습니다. 이에 따라 기존의 Axios 기반 코드를 Fetch로 전환했으며, SSR과 CSR 환경에서 쿠키 접근 방식의 차이로 인해 관련 로직 수정에도 문제를 겪었습니다.</li></ul><h3>5. 후기</h3><p>Next.js로의 전환은 성능 개선과 SEO 향상이라는 명확한 이점을 가져왔지만, 이 과정을 돌이켜보면 “과한 전환”은 아니었을까 싶은 의문도 들었습니다.</p><p>React에서도 충분히 SEO를 개선하고 초기 로딩 속도를 높일 수 있는 방안이 있었음에도, 마이그레이션은 상당한 시간과 노력을 요구했습니다. 특히, 단일 페이지에서의 다양한 상호작용과 실시간 API 요청이 필요한 프로젝트 특성상, SSR의 이점은 초기 노드 정보를 불러올 때에만 제한적으로 활용되었습니다.</p><p>이 경험은 프레임워크 선택과 기술적 전환에 있어 근본적인 질문을 던지게 합니다: “이 기술이 정말 필요한가? 프로젝트의 성격과 비용에 부합하는가?” Next.js가 가진 이점은 분명하지만, 프로젝트의 요구 사항과 특성에 맞는 기술 선택이 결국 중요하다고 느꼈네요.</p><p>그럼에도 불구하고, 이번 경험을 통해 Next.js및 SSR의 장점을 이해하고 응용하는 데 큰 도움을 얻었습니다. 이는 앞으로의 프로젝트에서 기술 선택에 큰 도움이 될 것 같다고 생각합니다.</p><h3>6. 참고자료</h3><p><a href="https://nextjs.org/docs">https://nextjs.org/docs</a></p><p><a href="https://velog.io/@iberis/%EC%9B%B9-%EC%B5%9C%EC%A0%81%ED%99%94-Lighthouse-CLI-%EC%84%B1%EB%8A%A5-%EC%A7%80%ED%91%9C">https://velog.io/@iberis/%EC%9B%B9-%EC%B5%9C%EC%A0%81%ED%99%94-Lighthouse-CLI</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6dc4d800716b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TOAST UI — 이미지 다중 업로드 구현]]></title>
            <link>https://medium.com/@teawon.jeong.dev/toast-ui-%EC%9D%B4%EB%AF%B8%EC%A7%80-%EB%8B%A4%EC%A4%91-%EC%97%85%EB%A1%9C%EB%93%9C-%EA%B5%AC%ED%98%84-6381c79f4e23?source=rss-d580fa80743e------2</link>
            <guid isPermaLink="false">https://medium.com/p/6381c79f4e23</guid>
            <category><![CDATA[image-upload]]></category>
            <category><![CDATA[toastui]]></category>
            <dc:creator><![CDATA[Teawon]]></dc:creator>
            <pubDate>Sat, 25 Nov 2023 13:40:31 GMT</pubDate>
            <atom:updated>2023-11-25T13:40:31.834Z</atom:updated>
            <content:encoded><![CDATA[<h3>TOAST UI — 이미지 다중 업로드 구현</h3><p><strong>1. 개요</strong></p><p>TOAST UI는 마크다운과 위지윅(WYSIWYG) 에디터를 지원하는 편리한 도구입니다. 이를 통해 사용자는 쉽게 텍스트 정보를 마크다운 형식으로 변환하여 표현할 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pHoCQAxVWqHGwW2F" /></figure><blockquote><a href="https://ui.toast.com/">[공식 홈페이지]</a></blockquote><p>하지만 TOAST UI의 기본 이미지 업로드 기능에는 한계가 있습니다. 이미지가 base64로 인코딩되어 매우 긴 문자열로 변환되는데, 이로 인해 생성되는 방대한 문자열 양은 다른 내용을 작성하는 것을 어렵게 만듭니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xU--5YOSquR8Ldhe" /></figure><blockquote>사용자의 가독성을 떨어뜨림</blockquote><blockquote>불필요하게 긴 문자열을 서버로 보내게되므로 리소스가 낭비</blockquote><p>따라서 이 글에서는 TOAST UI의 hooks와 AWS S3를 활용하여, 이미지 업로드 방식을 개선하는 방법을 소개하고자 합니다.</p><p><strong>[결과 미리보기]</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/0*hUOOto4ToK9qndr8" /></figure><p><strong>2. 이미지 업로드 방식</strong></p><p>이미지 업로드 과정은 단순하면서도 효과적입니다.</p><p>먼저, 프론트엔드에서 별도의 이미지 업로드 API를 서버로 전송합니다. 서버는 이 이미지를 AWS S3에 저장하고, 저장된 이미지의 URL을 프론트엔드로 다시 전달합니다. 프론트엔드는 이 URL을 받아 화면에 이미지를 표시합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/0*A0lEGX62yT75BAgr" /></figure><blockquote>전체 흐름도</blockquote><p>이를 위해, TOAST UI 에디터는 addImageBlobHook을 제공합니다.</p><p>이는 이미지가 업로드될 때 실행되는 훅(hook)을 사용자가 커스터마이즈할 수 있게 해주는 기능입니다. 이를 통해 사용자는 업로드된 이미지를 자유롭게 관리하고 조작할 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oxT8yy-31CNE9-eY72JUlQ.png" /></figure><blockquote><a href="https://nhn.github.io/tui.editor/1.4.10/addImageBlobHook">https://nhn.github.io/tui.editor/1.4.10/addImageBlobHook</a></blockquote><p>이를 기반으로 개선한 코드는 다음과 같습니다</p><pre>import { Editor } from &quot;@toast-ui/react-editor&quot;;<br><br>  const onUploadImage = async (<br>    blob: File,<br>    callback: (imageUrl: string, fileName: string) =&gt; void,<br>  ) =&gt; {<br>    uploadImageMutation(blob, {<br>      onSuccess: (data) =&gt; {<br>        callback(data.imageUrl, blob.name);<br>      },<br>    });<br>    return false;<br>  };<br><br><br>  return (<br>    &lt;&gt;<br>         { ... }<br>            &lt;Editor<br>              ref={editorRef}<br>              hooks=<br>              onChange={handleEditorChange}<br>              previewStyle=&quot;tab&quot;<br>              height=&quot;100%&quot;<br>              initialEditType=&quot;markdown&quot;<br>              usageStatistics={false}<br>            /&gt;<br>    &lt;/&gt;<br>  );<br>};</pre><p>- `onUploadImage` 함수는 이미지가 업로드되면 실행됩</p><p>- 서버에 이미지를 전송하고, 반환된 S3 URL을 통해 이미지를 화면에 표시</p><pre>export const uploadImage = async (file: File) =&gt; {<br>  const endpoint = `boards/image`;<br><br>  const formData = new FormData();<br>  formData.append(&quot;file&quot;, file);<br><br>  const data = await csrFetch(endpoint, {<br>    method: &quot;POST&quot;,<br>    body: formData,<br>  });<br><br>  return data;<br>};<br><br>export const useUploadImageMutation = () =&gt; {<br>  return useMutation(uploadImage);<br>};<br><br>const {<br>  mutate: uploadImageMutation,<br>  isLoading: isImageUploading,<br>  isError: isImageUploadError,<br>} = useUploadImageMutation();</pre><p>- api 호출에 대한 정보</p><p>또한 이미지가 업로드 중일때 상태를 표현해주기 위해, mutate의 `isLoading` 정보를 활용해 메세지를 표현해주도록 합시다.</p><pre>return (<br>    &lt;&gt;<br>          { ... }<br>            &lt;Editor<br>              ref={editorRef}<br>              hooks=<br>              onChange={handleEditorChange}<br>              previewStyle=&quot;tab&quot;<br>              height=&quot;100%&quot;<br>              initialEditType=&quot;markdown&quot;<br>              usageStatistics={false}<br>            /&gt;<br><br>        &lt;div className={styles.content__editor__message}&gt;<br>          {isImageUploading &amp;&amp; (<br>            &lt;span className={styles.content__editor__message__loading}&gt;<br>              이미지 업로드 중...<br>            &lt;/span&gt;<br>          )}<br>        &lt;/div&gt;<br><br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/0*LGvXEC576sHRwwhd" /></figure><blockquote>결과: 이전에 비해 짧은 이미지 url정보가 반환된다</blockquote><p><strong>2. 다중 업로드 처리</strong></p><p>앞서 소개한 이미지 업로드 방식은 효율적이지만, 한 가지 제한이 있습니다 이미지를 하나씩 사용자가 올려야한다는 부분입니다.</p><p>만약 사용자가 여러 파일을 동시에 업로드하고 싶어한다면 어떻게 해야 할까요?</p><p>이 문제를 해결하기 위해, TOAST UI 에디터를 외부 컴포넌트로 감싸고, 드롭다운 이벤트를 감지해서, 각 파일에 대해 순차적으로 업로드를 처리한다면 사용자는 여러 이미지를 한꺼번에 업로드할 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/0*KAtScN_oWNtOVizf" /></figure><p><strong>2.1 드롭다운 이벤트</strong></p><pre>const handleDrop = async (event: React.DragEvent&lt;HTMLDivElement&gt;) =&gt; {<br><br>  const files = Array.from(event.dataTransfer.files);<br>  for (const file of files) {<br>    if (file.type.startsWith(&quot;image/&quot;)) {<br>      await new Promise&lt;void&gt;((resolve, reject) =&gt; {<br>       // 이미지 업로드 로직 처리<br>      });<br>    }<br>  }<br>};<br><br>&lt;div onDrop={handleDrop}&gt;<br>    &lt;Editor<br>      ref={editorRef}<br>      hooks=<br>      onChange={handleEditorChange}<br>      previewStyle=&quot;tab&quot;<br>      height=&quot;100%&quot;<br>      initialEditType=&quot;markdown&quot;<br>      usageStatistics={false}<br>  /&gt;<br>&lt;/div&gt;</pre><p>이를 위해 Editor를 감싸는 `div`요소에 onDrop 이벤트를 감지하고 로직을 처리하는 함수를 생성합니다.</p><p>그러나, 실제 파일을 드래그래서 올려보면 div요소의 onDrop함수가 아니라 Editor내부의 `onUploadImage`메서드가 먼저 실행됩니다.</p><p><strong>이는 DOM의 이벤트 라이프사이클, 특히 이벤트 전파(Event Propagation) 메커니즘 때문입니다.</strong></p><p>&lt;br&gt;</p><p>DOM의 이벤트 전파는 크게<strong> 캡처 단계(capture phase)</strong>와 <strong>버블 단계(bubble phase)</strong>으로 나뉩니다. (target phase개념도 있긴 합니다)</p><p>캡처 단계에서는 이벤트가 상위 요소에서 하위 요소로 전달됩니다.</p><p>반면, 버블링 단계에서는 이벤트가 하위 요소에서 상위 요소로 전파됩니다.</p><p>Editor 내부의 onUploadImage 메서드가 먼저 실행되는 이유는, 이벤트가 버블링 단계에서 Editor로 전파되기 때문입니다. 이를 해결하기 위해 캡처링을 사용하면 이벤트가 상위 요소(여기서는 div)에서 먼저 감지되므로, 원하는 로직을 먼저 실행할 수 있습니다.</p><p>React에서는 onDrop를 캡처링 단계에서 실행하는 `onDropCapture`메서드를 제공하고 있으므로, 이를 통해 코드를 수정합니다</p><pre>const handleDrop = async (event: React.DragEvent&lt;HTMLDivElement&gt;) =&gt; {<br><br>    event.preventDefault(); // 기본 동작 X<br>    event.stopPropagation(); // 이벤트 전파 중치<br><br>  const files = Array.from(event.dataTransfer.files);<br>  for (const file of files) {<br>    if (file.type.startsWith(&quot;image/&quot;)) {<br>      await new Promise&lt;void&gt;((resolve, reject) =&gt; {<br>       // 이미지 업로드 로직 처리<br>      });<br>    }<br>  }<br>};<br><br><br>&lt;div onDropCapture={handleDrop}&gt;<br>  &lt;Editor<br>    ref={editorRef}<br>    hooks=<br>    onChange={handleEditorChange}<br>    previewStyle=&quot;tab&quot;<br>    height=&quot;100%&quot;<br>    initialEditType=&quot;markdown&quot;<br>    usageStatistics={false}<br>  /&gt;<br>&lt;/div&gt;</pre><p>또한 preventDefault 메서드를 사용하여 기본 드롭 동작을 방지하고, stopPropagation을 통해 불필요한 중첩 업로드가 발생하지 않도록 이벤트 전파를 중지합니다.</p><p><strong>2.2 업데이트</strong></p><pre>const updateEditorContent = (newContent: string) =&gt; {<br>  const currentContent = editorRef?.current?.getInstance().getMarkdown();<br><br>  editorRef?.current<br>    ?.getInstance()<br>    .setMarkdown(`${currentContent}\n${newContent}`);<br>};</pre><p>editorRef를 사용하면 현재 에디터의 내용을 쉽게 가져오고, 필요한 부분을 추가하여 업데이트할 수 있습니다.</p><p>따라서 별도의 업데이트 함수를 생성 후 이를 활용해 받아온 이미지를 순차적으로 에디터에 추가하는 전체 코드는 아래와 같습니다</p><pre>const handleDrop = async (event: React.DragEvent&lt;HTMLDivElement&gt;) =&gt; {<br>    event.preventDefault();<br>    event.stopPropagation();<br><br>    const files = Array.from(event.dataTransfer.files);<br>    for (const file of files) {<br>      if (file.type.startsWith(&quot;image/&quot;)) {<br>        await new Promise&lt;void&gt;((resolve, reject) =&gt; {<br>          uploadImageMutation(file, {<br>            onSuccess: (data) =&gt; {<br>              const markdownImageLink = `![${file.name}](${data.imageUrl})`;<br>              updateEditorContent(markdownImageLink);<br>              resolve();<br>            },<br>            onError: (error) =&gt; {<br>              console.log(error);<br>              updateEditorContent(&quot;이미지 업로드에 실패했습니다.&quot;);<br>              reject();<br>            },<br>          });<br>        });<br>      }<br>    }<br>  };<br><br>  { ... }<br><br>  &lt;div onDropCapture={handleDrop}&gt;<br>      &lt;Editor<br>          ref={editorRef}<br>          onChange={handleEditorChange}<br>          previewStyle=&quot;tab&quot;<br>          height=&quot;100%&quot;<br>          initialEditType=&quot;markdown&quot;<br>          usageStatistics={false}<br>      /&gt;<br>  &lt;/div&gt;</pre><blockquote>[<a href="https://github.com/techeer-sv/Mindspace/blob/develop/Mindspace_front_next/app/map/components/WriteModal/components/WriteEditor/index.tsx">github</a>]</blockquote><p><strong>3. 결과</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/0*LZGeZNWrCR-jRrI5" /></figure><p>위 이미지는 구현한 다중 이미지 업로드 기능의 최종 결과를 보여줍니다. 사용자가 여러 이미지를 드래그 앤 드롭하여 쉽게 업로드할 수 있으며, 업로드된 이미지들은 자동으로 TOAST UI Editor에 순차적으로 추가됩니다.</p><p>만약 직접 만든 컴포넌트였다면, 내부 Editor에서 event요소에 접근 후 ` event.preventDefault();` 메서드를 호출하는 방향으로 처리했을 것 같은데 접근 방법을 찾지 못해 캡처 단계를 활용하여 이벤트를 처리했습니다.</p><p>그러나 시스템이 만약 복잡해진다면 이 처리방식이 다른 요소에 영향을 미칠 수 있는 가능성도 고려해야 한다고 생각합니다. 조금 찝찝하지만, 더 나은 해결책이 있는지 모색해보고 싶네요.</p><p><strong>4. 트러블 슈팅</strong></p><p>초기 이미지 업로드 시도에서, 서버로부터 다음과 같은 에러 메시지를 받았습니다:</p><pre>{<br>    &quot;message&quot;: &quot;Unexpected token - in JSON at position 0&quot;,<br>    &quot;error&quot;: &quot;Bad Request&quot;,<br>    &quot;statusCode&quot;: 400<br>}</pre><p><strong>[1차 시도]</strong></p><p>이 에러는 FormData를 사용하여 이미지 데이터를 전송하면서 발생했습니다.</p><p>문제의 해결을 위해, 요청의 헤더에 “Content-Type”: “multipart/form-data”를 추가하는 방식으로 수정했습니다.</p><pre>export const uploadImage = async (file: File) =&gt; {<br>  const endpoint = `boards/image`;<br><br>  const formData = new FormData();<br>  formData.append(&quot;file&quot;, file);<br><br>  const data = await csrFetch(endpoint, {<br>    method: &quot;POST&quot;,<br>    headers: {<br>      &quot;Content-Type&quot;: &quot;multipart/form-data&quot;, // 해당 설정 추가<br>    },<br>    body: formData,<br>  });<br><br>  return data;<br>};</pre><blockquote>그런데 이어서 에러 발생.. Boundary가 없다고 표현</blockquote><p>Boundary란 multipart/form-data는 여러 부분으로 나누어진 데이터를 전송할 때 사용하는 인코딩 방식인데, 각 부분은 boundary라는 특정 문자열로 구분되기때문에 이때 해당 값이 꼭 필요하다고 합니다.</p><p><strong>[2차시도 — 해결]</strong></p><p>props에 따라 Header정보를 default로 넣지 않도록 코드를 추가하여 이를 해결했습니다.</p><p>즉 Fetch API를 사용할 때 FormData 객체가 있을 경우 기본 헤더를 덮어쓰지 않도록 코드를 수정했습니다. 이렇게 함으로써, Fetch API가 자동으로 ‘boundary’ 값을 설정할 수 있도록 했습니다.</p><pre>export const baseFetch = async &lt;T = any&gt;(<br>  endpoint: string,<br>  headers: HeadersInit,<br>  options?: RequestInit,<br>  skipDefaultHeaders?: boolean<br>): Promise&lt;T&gt; =&gt; {<br>  const response = await fetch(`${BASEURL}${endpoint}`, {<br>    ...options,<br>    headers: new Headers({<br>      ...(skipDefaultHeaders ? {} : defaultHeaders),<br>      ...headers,<br>      ...options?.headers,<br>    }),<br>  });<br><br>  return handleResponse &lt; T &gt; response;<br>};<br><br>export const csrFetch = async &lt;T = any&gt;(<br>  endpoint: string,<br>  options?: RequestInit<br>): Promise&lt;T&gt; =&gt; {<br>  const accessToken = Cookies.get(&quot;accessToken&quot;);<br>  const authHeader: Record&lt;string, string&gt; = {};<br><br>  if (accessToken) {<br>    authHeader.user_id = `${accessToken}`;<br>  }<br><br>  let headers: Record&lt;string, any&gt; = {<br>    ...authHeader,<br>    ...options?.headers,<br>  };<br><br>  const skipDefaultHeaders = options?.body instanceof FormData;<br><br>  return baseFetch &lt; T &gt; (endpoint, headers, options, skipDefaultHeaders);<br>};</pre><p><a href="https://bobbyhadz.com/blog/error-multipart-boundary-not-found-in-express-js">https://bobbyhadz.com/blog/error-multipart-boundary-not-found-in-express-js</a></p><p><a href="https://velog.io/@cxxxtxxyxx/Multipart-Boundary-not-found-Error">https://velog.io/@cxxxtxxyxx/Multipart-Boundary-not-found-Error</a></p><p><strong>## 5. 참고자료</strong></p><p><a href="https://react.dev/learn/responding-to-events#capture-phase-events">https://react.dev/learn/responding-to-events#capture-phase-events</a></p><p><a href="https://iamiet.tistory.com/entry/toast-ui-editor-v3-%EC%9D%B4%EB%AF%B8%EC%A7%80-%EC%97%85%EB%A1%9C%EB%93%9C-%EC%B5%9C%EC%A0%81%ED%99%94%EC%BB%A4%EC%8A%A4%ED%84%B0%EB%A7%88%EC%9D%B4%EC%A7%95%ED%95%98%EA%B8%B0">https://iamiet.tistory.com/entry/toast-ui-editor-v3-%EC%9D%B4%EB%AF%B8%EC%A7%80-%EC%97%85%EB%A1%9C%EB%93%9C-%EC%B5%9C%EC%A0%81%ED%99%94%EC%BB%A4%EC%8A%A4%ED%84%B0%EB%A7%88%EC%9D%B4%EC%A7%95%ED%95%98%EA%B8%B0</a></p><p><a href="https://leego.tistory.com/entry/Toast-UI-Editor-%EC%9D%B4%EB%AF%B8%EC%A7%80-%EC%B2%A8%EB%B6%80%ED%95%98%EA%B8%B0">https://leego.tistory.com/entry/Toast-UI-Editor-%EC%9D%B4%EB%AF%B8%EC%A7%80-%EC%B2%A8%EB%B6%80%ED%95%98%EA%B8%B0</a></p><p><a href="https://nhn.github.io/tui.editor/latest/ToastUIEditorCore">https://nhn.github.io/tui.editor/latest/ToastUIEditorCore</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6381c79f4e23" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Code Splitting 및 정적 리소스 최적화를 통한 초기 로딩속도 개선]]></title>
            <link>https://medium.com/@teawon.jeong.dev/%EC%B4%88%EA%B8%B0-%EB%A1%9C%EB%94%A9%EC%86%8D%EB%8F%84-%EB%B0%8F-%EC%82%AC%EC%9A%A9%EC%9E%90-%EA%B2%BD%ED%97%98-%EA%B0%9C%EC%84%A0%EC%8B%9C%ED%82%A4%EA%B8%B0-e8f357ef04c0?source=rss-d580fa80743e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8f357ef04c0</guid>
            <category><![CDATA[code-splitting]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Teawon]]></dc:creator>
            <pubDate>Sat, 25 Nov 2023 13:25:03 GMT</pubDate>
            <atom:updated>2023-11-26T15:12:36.066Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>1. 개요</strong></p><p>아래 영상은, 현재 진행중인 프로젝트의 메인페이지에 접근했을때 표현되는 UI입니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*JgaoP9fNU__7CVhn" /></figure><blockquote><em>실제 로딩시간을 표현하기 위한 “Click! &amp; Loading 텍스트 삽입” (영상편집)</em></blockquote><p>특히, 데이터를 가져오는 동안 시작 페이지가 정지해 있는 듯한 인상을 주어 사용자들이 혼란을 느낄 수 있으며 이러한 문제는 사용자 경험(UX)에 부정적인 영향을 미칠 수 있습니다.</p><p>핵심 페이지에서의 첫 인상은 사용자의 프로젝트 인식에 결정적인 역할을 합니다. 페이지가 로딩 중에 버벅이거나 멈춘 것처럼 보이는 것은 기술적인 문제가 있다는 인상을 줄 수 있고 이는 문제 해결의 필요성을이 강조되었습니다.</p><p>따라서 이 글에서는 문제를 파악하고 사용자 UI를 개선시키기 위해 적용한 방법들에 대해 정리해보려고 합니다.</p><p><strong>2. 로딩 UI</strong></p><p>프로젝트의 시작 페이지에서 메인 페이지로 이동하는 과정은 사용자에게 중요한 전환점입니다.</p><p>이때 데이터 로딩을 기다리는 동안 메인 페이지의 정지한 듯한 상태는 사용자에게 혼란과 불편함을 줄 수 있기때문에 적절한 로딩 UI를 띄워야 합니다.</p><p>적절한 로딩 스피너의 사용은 사용자에게 로딩 중임을 분명하게 전달함으로써, 백그라운드에서 진행되는 데이터 로딩 과정을 인지하게 하고, 이를 기다릴 수 있도록 안내합니다.</p><p><strong>### 2.1 로딩 스피너 구현</strong></p><p>Next에서는 `loading.js` 폴더를 사용해 쉽게 로딩상태에 대한 UI를 표현할 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/0*G58Zi8F4izvWMJ75" /></figure><p><a href="https://nextjs.org/docs/app/building-your-application/routing/loading-ui-and-streaming">https://nextjs.org/docs/app/building-your-application/routing/loading-ui-and-streaming</a></p><p>따라서 같은 방식으로 loading.tsx 파일을 구성합니다.</p><pre>import MoonLoadSpinner from &quot;@/components/MoonLoadSpinner&quot;;<br><br>export default function Loading() {<br>  return &lt;MoonLoadSpinner /&gt;;<br>}</pre><p>또한 스피너 컴포넌트는 아래와 같이 Lottie를 사용해 구현했습니다.</p><pre>&quot;use client&quot;;<br>import { getLottieOptions } from &quot;@/utils/lottie&quot;;<br>import Lottie from &quot;react-lottie&quot;;<br>import styles from &quot;./MoonLoadSpinner.module.scss&quot;;<br><br>const MoonLoadSpinner = () =&gt; {<br>  return (<br>    &lt;&gt;<br>      &lt;div className={styles.wrapper}&gt;<br>        &lt;Lottie<br>          options={getLottieOptions(&quot;/lotties/moon.json&quot;)}<br>          height={300}<br>          width={300}<br>        /&gt;<br>      &lt;/div&gt;<br>    &lt;/&gt;<br>  );<br>};<br><br>export default MoonLoadSpinner;</pre><p><strong>2.2 트러블 슈팅</strong></p><p>사실 위 코드는 실제 의도한대로 돌아가지 않았습니다.</p><p>왜냐하면 메인페이지의 데이터는 SSR을 적용하고 있었으나 `MoonLoadSpinner`는 클라이언트 컴포넌트(“use client”)로 구현되어있었기 때문에</p><p>SSR 환경에서 서버는 데이터를 처리하고 페이지를 렌더링하는 동안 클라이언트 측 컴포넌트인 MoonLoadSpinner는 활성화되지 않았습니다.</p><p>즉, 서버에서 데이터를 로드하는 동안 클라이언트 기반의 로딩 UI는 전혀 표시되지 않는 문제가 발생한거죠.</p><p><strong>로딩에 사용되는 컴포넌트는, 서버 컴포넌트로 구현</strong>해야했습니다</p><p>그러나 Lottie를 사용했을 때 아래의 에러가 발생했으며 어쩔 수 없이 다른 방식으로 스피너를 구현하며 우회하는 방식으로 처리했습니다.🥲</p><pre>Unhandled Runtime Error<br>Error: useRef only works in Client Components. Add the &quot;use client&quot;<br><br>directive at the top of the file to use it. Read more ...<br><br>// 내부에서 useRef를 사용하고 있다🥲</pre><p><strong>## 3. 성능 개선</strong></p><p><strong>## 3.1 지연 로딩</strong></p><p>성능 개선을 위한 첫 단계로, 웹사이트의 성능 분석이 필수적입니다. 이를 위해 저는 Google의 Lighthouse 도구를 사용하여 웹사이트의 성능을 평가하고, 주요 문제점들을 식별했습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0c1Ft5TelvJRRVbS" /></figure><blockquote><em>[Lighthouse — Performance]<br></em>메인 페이지에 접속했을때의 성능 측정 결과</blockquote><p>메인 페이지의 로딩 성능을 측정한 결과, map과 modal 컴포넌트에서 데이터를 로드하는 데 상당한 시간이 소요되고 있음을 발견했습니다.</p><p>map(메인) 페이지에서는 노드 연결관계를 표현하기 위해 `react-force-graph` 라이브러리를 사용하고 있었고, modal은 사용자가 노드를 클릭했을 때 활성화되는 컴포넌트로, `ag-grid` 및 `toast-ui`가 사용중이였습니다.</p><p>사실 Modal은 사용자가 “클릭” 한 후에 표현되는 요소이기때문에 당장은 화면상에 표현하지 않는데, 불필요하게 첫 렌더링에 영향을 미치고 있던거죠.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jjvPybnkgWEv1WW4" /></figure><blockquote>특정 별자리 정보를 클릭했을때 글 작성 용도로 사용하던 `toast-ui`</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BYEx_hZclOepicC4" /></figure><blockquote>특정 별자리 정보를 클릭 후 게시글 목록에 들어갔을 때 사용하던 `ag-grid`</blockquote><p>따라서 모달 컴포넌트는 굳이 빠르게 로드될 필요가 없으며 초기 렌더링 성능에 부정적인 영향을 미쳤기때문에 맵 정보가 모두 로드되고 사용자의 설정이 완료된 이후에만 모달창 관련 요소를 로드하도록 코드를 재구성했습니다</p><pre>// 수정 전<br>import NodeModal from &quot;./components/Modal&quot;;<br><br>// {...}<br><br>  return (<br>    &lt;div&gt;<br>    { ... }<br>      {nodeInfo &amp;&amp; (<br>        &lt;&gt;<br>          &lt;NodeModal<br>            isOpen={modalIsOpen}<br>            onRequestClose={() =&gt; setModalIsOpen(false)}<br>            updateNodeInfo={handleNodeInfoUpdate}<br>          /&gt;<br>        &lt;/&gt;<br>      )}<br>    &lt;/div&gt;</pre><blockquote><em>데이터가 있다면 모달 컴포넌트도 함께 렌더링했다. (필요 이상의 리소스가 초기 로딩 시 사용)</em></blockquote><pre>// 수정 후<br>const NodeModalLazy = lazy(() =&gt; import(&quot;./components/Modal&quot;));<br><br>// {...}<br><br> return (<br>    &lt;div&gt;<br>    {...}<br>      {nodeData &amp;&amp; isInitialSetupDone &amp;&amp; (<br>        &lt;Suspense fallback={&lt;Loading /&gt;}&gt;<br>          &lt;NodeModalLazy<br>            isOpen={modalIsOpen}<br>            onRequestClose={() =&gt; setModalIsOpen(false)}<br>            updateNodeInfo={handleNodeInfoUpdate}<br>          /&gt;<br>        &lt;/Suspense&gt;<br>      )}<br>    &lt;/div&gt;<br>  );<br><br>  // isInitialSetupDone - 노드 관계에 대한 초기 설정 상태</pre><blockquote><em>React.lazy와 Suspense를 활용하여 모달 컴포넌트를 지연 로딩</em></blockquote><blockquote><em>데이터를 받아오고, 노드간의 연결관계에 대한 설정과 렌더링이 끝나면 이어서 바로 Modal컴포넌트를 렌더링</em></blockquote><p>그 결과 적절한 타이밍에 로드되도록 함으로써 초기 렌더링 속도를 개선시킬 수 있었습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hT2D0prQ3-sac_89" /></figure><blockquote>398ms에서 198ms로 TBT(Total Blocking Time) 분리</blockquote><p><strong>3.2 정적 리소스 최적화</strong></p><p>또한 Lighthouse의 페이지 기능을 통해 분석해본 결과 프로젝트에서 사용 중인 폰트와 배경 이미지의 네트워크 페이로드가 상당하다는 점을 확인했습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Gmzy3A2KHepzUn-0" /></figure><p>따라서, 배경이미지 및 로고와 폰트의 확장자를 바꾸고 촤적화 작업을 진행했습니다.</p><p>이미지의 경우 <a href="https://teawon.github.io/next/next-optimization-mindspace/squoosh.app">squoosh.app</a> 사이트를 통해, webp확장자로 수정하였습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*vd30Fue1egtkW1r3" /></figure><blockquote>webp 확장자의 경우 높은 압축률과 품질유지 특징을 가진다(이전과 이후의 차이가 눈에 두드러지지 않음)</blockquote><blockquote>1.2MB에서, 26Kb로 약 95%가량 압축</blockquote><p>폰트의 경우 woff2 확장자를 통해 최적화를 진행했습니다.</p><blockquote>WOFF2는 웹 폰트의 표준 포맷 중 하나로, 뛰어난 압축 효율을 제공</blockquote><blockquote>878KB에서, 388KB로 약 55%가량 압축</blockquote><p><strong>3.2.1 Next Image</strong></p><p>사실 위의 번거로움 없이, Next에서는 이미지 최적화를 위한 Image 컴포넌트를 제공합니다.</p><p>실제 png기반의 커다란 이미지를 사용해도, 자동으로 WebP 및 AVIF와 같은 최신 이미지 형식으로 변환주기때문에 개발자가 번거롭게 각 이미지를 변환할 필요가 없어지는거죠.</p><pre>// example<br>import Image from &quot;next/image&quot;;<br><br>export default function Page() {<br>  return (<br>    &lt;Image<br>      src=&quot;/profile.png&quot;<br>      width={500}<br>      height={500}<br>      alt=&quot;Picture of the author&quot;<br>    /&gt;<br>  );<br>}</pre><pre>// global.scss<br>body {<br>  ....<br>  background-image: url(https://medium.com/&quot;/images/BackGround.png&quot;);<br><br>}</pre><blockquote>기존의 배경 이미지 적용 코드</blockquote><p>그러나 기존 배경이미지의 경우 css를 활용해 적용하고 있었습니다. 단순히 배경이미지의 포멧을 변경해도 괜찮지만</p><p>뷰포트에 따라 적절한 이미지를 자동으로 선택해주는 강력한 이점을 가진 Next의 Image를 활용하기로 결정했습니다.</p><pre>//layout.tsx<br><br>import styles from &quot;./main.module.scss&quot;;<br><br>{...}<br><br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;link rel=&quot;icon&quot; href=&quot;/favicon.ico&quot; /&gt;<br>  &lt;/head&gt;<br>  &lt;body className={inter.className}&gt;<br>    &lt;Image<br>      className={styles.background}<br>      src=&quot;/images/background.png&quot;<br>      alt=&quot;background&quot;<br>      fill<br>    /&gt;<br>    {...}<br>  &lt;/body&gt;<br>&lt;/html&gt;<br><br><br>// main.module.scss<br><br>.background {<br>  z-index: -100;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/0*34FiXKGRcxXg00Vq" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/0*alPkxpa3AVB4-k9r" /></figure><blockquote>데스크탑과 모바일 환경에서의 뷰포트에 따라 실제 다른 크기의 이미지를 받아온다</blockquote><blockquote>png파일을 사용했음에도 자동으로 webp기반의 최적화된 이미지를 사용한다</blockquote><p><strong>3.2.2 Next Font</strong></p><p>Next에서는 font에 대한 최적화 기능도 지원합니다.</p><p>@next/font은 아래의 특징을 가지고 있습니다.</p><p>1. 자동 자체 호스팅과 캐싱: 자동으로 폰트 파일을 자체 호스팅하며, 캐싱과 사전 로드를 지원합니다. 이는 폰트 로딩 속도를 개선합니다.</p><p>2. 폰트 자동 최적화: 다양한 최적화 기법을 통해 폰트의 로딩 시간을 최소화합니다.</p><p>3. 빌드시 다운로드: 특히 Google 폰트를 사용하는 경우, 빌드 시점에 폰트를 다운로드하여 별도의 외부 요청을 보내지 않습니다.</p><p>4. 레이아웃 이동 방지: 폰트 로딩으로 인한 페이지 레이아웃의 변동을 방지합니다.</p><p>이러한 기능을 활용하여 기존에 global CSS에서 적용하던 방식 대신 Google 폰트를 사용하여 폰트 로딩 방식을 개선했습니다.</p><pre>//layout.tsx<br><br>import { Akshar } from &quot;next/font/google&quot;;<br><br>const akshar = Akshar({ preload: false }); // 한글의 경우 subset지원 안한다고합니다.<br>...<br><br><br>return (<br>    &lt;html className={inter.className} lang=&quot;en&quot;&gt;<br>        {...}<br>    &lt;/html&gt;<br>  );</pre><p>결과적으로 구글폰트로 변경하며 기본 사양에 차이는 있겠지만 54ms에서 8ms로 읽어오는데 많은 시간이 개선되었습니다</p><p><strong>## 4. 결과</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*wHIpPsvz9tPmOYt0" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*df9dZ3j7kGy2JJsa" /></figure><blockquote>이전 / 이후</blockquote><p><strong>5. 참고자료</strong></p><p><a href="https://nextjs.org/docs/pages/building-your-application/rendering/server-side-rendering">https://nextjs.org/docs/pages/building-your-application/rendering/server-side-rendering</a></p><p><a href="https://nextjs.org/docs/app/building-your-application/optimizing/images">https://nextjs.org/docs/app/building-your-application/optimizing/images</a></p><p><a href="https://nextjs.org/docs/pages/api-reference/components/image">https://nextjs.org/docs/pages/api-reference/components/image</a></p><p><a href="https://nextjs.org/blog/next-13#nextimage](https://nextjs.org/blog/next-13#nextimage">https://nextjs.org/blog/next-13#nextimage](https://nextjs.org/blog/next-13#nextimage</a></p><p><a href="https://nextjs.org/docs/pages/building-your-application/optimizing/fonts">https://nextjs.org/docs/pages/building-your-application/optimizing/fonts</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8f357ef04c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Next13, middleware 기반의 페이지 접근제한]]></title>
            <link>https://medium.com/@teawon.jeong.dev/next13-middleware-%EA%B8%B0%EB%B0%98%EC%9D%98-%ED%8E%98%EC%9D%B4%EC%A7%80-%EC%A0%91%EA%B7%BC%EC%A0%9C%ED%95%9C-63a580b6b32c?source=rss-d580fa80743e------2</link>
            <guid isPermaLink="false">https://medium.com/p/63a580b6b32c</guid>
            <dc:creator><![CDATA[Teawon]]></dc:creator>
            <pubDate>Sat, 25 Nov 2023 13:11:04 GMT</pubDate>
            <atom:updated>2023-11-25T13:11:04.834Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>1. 개요</strong></p><p>프로젝트를 진행하면 때때로 서비스에 따라 로그인 상태에 따라 페이지 접근을 제한하거나, 특정 페이지로 리다이렉트 해야하는 경우가 있습니다.</p><p>예를 들면, 현재 작업 중인 프로젝트에서는 다음과 같은 서비스 플로우를 가지고있습니다.</p><p>1. 로그인 상태일때, “/signin” , “signup” 페이지에 접속 시 메인 페이지로 강제 이동시킨다.</p><p>2. 로그인 상태가 아니라면, “/map” 페이지에 접속 시 로그인 페이지로 강제 이동시킨다.</p><p>이 글에서는 React에서 사용한 방식에서 Next로의 마이그레이션 과정에서 이러한 기능을 어떻게 구현했는지, 그리고 구현 과정에서 부딪힌 문제와 해결 방법에 대해 공유하려고 합니다.</p><p><strong>2. React</strong></p><p>React 프로젝트에서는 react-router를 사용해 사용자의 로그인 상태에 따른 페이지 접근 제어를 구현하였습니다.</p><pre><br>```javascript<br>function App() {<br>  return (<br>    &lt;Router&gt;<br>      &lt;Routes&gt;<br>        &lt;Route path=&quot;/&quot; element={&lt;MainPage /&gt;} /&gt;<br><br>        &lt;Route element={&lt;AuthRoute needLogin={true} /&gt;}&gt;<br>          &lt;Route path=&quot;/map&quot; element={&lt;NodeMap /&gt;} /&gt;<br>        &lt;/Route&gt;<br><br>        &lt;Route element={&lt;AuthRoute needLogin={false} /&gt;}&gt;<br>          &lt;Route path=&quot;/signin&quot; element={&lt;SignInPage /&gt;} /&gt;<br>          &lt;Route path=&quot;/signup&quot; element={&lt;SignUpPage /&gt;} /&gt;<br>        &lt;/Route&gt;<br>      &lt;/Routes&gt;<br>    &lt;/Router&gt;<br>  );<br>}<br><br>const AuthRoute = ({ needLogin }: AuthRouteProps) =&gt; {<br>  const navigate = useNavigate();<br>  const isLoggedIn = useRecoilValue(isLoggedInAtom);<br><br>  useEffect(() =&gt; {<br>    const LoginRoute = () =&gt; {<br>      if (!isLoggedIn) {<br>        navigate(&quot;/signin&quot;);<br>        window.alert(&quot;로그인이 필요합니다&quot;);<br>      }<br>    };<br><br>    const NotLoginRoute = () =&gt; {<br>      if (isLoggedIn) {<br>        navigate(&quot;/&quot;);<br>      }<br>    };<br><br>    if (needLogin) {<br>      LoginRoute();<br>    } else {<br>      NotLoginRoute();<br>    }<br>  }, [needLogin, isLoggedIn, navigate]);<br><br>  return &lt;Outlet /&gt;;<br>};<br>```</pre><p>해당 로직은 useEffect 내에서 수행되며, 로그인 상태가 변할 때 마다 반응하여 적절한 리다이렉트를 수행하도록 처리했습니다.</p><p><strong>3. Next</strong></p><p><strong>3.1 시행 착오</strong></p><p>처음에는 Client-Side Rendering (CSR) 단계에서 로컬 스토리지의 값을 확인하여 라우팅을 처리하려고 시도했습니다.</p><p>별도의 클라이언트 컴포넌트를 만들고, 공통 layout을 감싸는 구조인거죠.</p><pre>// bad code<br><br>export default function RootLayout({<br>  children,<br>}: {<br>  children: React.ReactNode,<br>}) {<br>  return (<br>    &lt;html lang=&quot;en&quot;&gt;<br>      &lt;head&gt;<br>        &lt;link rel=&quot;icon&quot; href=&quot;/favicon.ico&quot; /&gt;<br>      &lt;/head&gt;<br>      &lt;body className={inter.className}&gt;<br>        &lt;Recoil&gt;<br>          &lt;ReactQuery&gt;<br>            &lt;AuthProvider&gt;<br>              &lt;LayoutProvider&gt;{children}&lt;/LayoutProvider&gt;<br>            &lt;/AuthProvider&gt;<br>          &lt;/ReactQuery&gt;<br>        &lt;/Recoil&gt;<br>      &lt;/body&gt;<br>    &lt;/html&gt;<br>  );<br>}</pre><pre>// bad code<br><br>&quot;use client&quot;;<br><br>const protectedRoutes = [&quot;/map&quot;];<br>const publicRoutes = [&quot;/signin&quot;, &quot;/signup&quot;];<br><br>function isProtectedRoute(pathname: string) {<br>  return protectedRoutes.includes(pathname);<br>}<br><br>function isPublicRoute(pathname: string) {<br>  return publicRoutes.includes(pathname);<br>}<br><br>export default function AuthProvider({<br>  children,<br>}: {<br>  children: React.ReactNode,<br>}) {<br>  const router = useRouter();<br>  const pathname = usePathname();<br>  const isLoggedIn = useRecoilValue(isLoggedInAtom);<br><br>  useEffect(() =&gt; {<br>    if (isLoggedIn &amp;&amp; isPublicRoute(pathname)) {<br>      router.replace(&quot;/&quot;);<br>    } else if (!isLoggedIn &amp;&amp; isProtectedRoute(pathname)) {<br>      router.replace(&quot;/signin&quot;);<br>    }<br>  }, [isLoggedIn, pathname]);<br><br>  return &lt;&gt;{children}&lt;/&gt;;<br>}</pre><p>그러나 이 방법으로 처리를 하게된다면, 페이지의 강제 리다이렉트처리가 페이지에 실제 접근 후 이동하게되니 화면상에도 실제 url이 변경되는게 사용자에게도 직접 노출되는 문제가 있었습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*C80J4vk2N8wDQ9ag" /></figure><blockquote><em>map페이지에 들어가기 전에 이동하는게 아니라, 이동 후 이동한다.</em></blockquote><blockquote><em>map페이지에서 호출하는 api(임시로 찍은 콘솔)도 전부 실행, 리소스 낭비가 발생</em></blockquote><p>즉, <strong>**서버 사이드 렌더링 (SSR) 시점에 로그인 상태를 판별하고 이에 따라 적절한 페이지 렌더링 또는 리다이렉트 처리**</strong>를 해야 했습니다.</p><p>서버 사이드에서의 렌더링 단계에서 로그인 상태를 확인하면, 클라이언트에서 페이지를 받기 전에 이미 필요한 처리가 완료되기 때문에 사용자에게는 중간 페이지 전환이나 불필요한 API 호출이 눈에 띄지 않게 되겠죠.</p><p><strong>3.2 middleware</strong></p><p>여기서 저는 Next13의 middleware를 사용했습니다.</p><p>middleware란 요청이 완료되기 전에 코드를 실행할 수 있게 해주는 기능으로 들어오는 요청을 기반으로 응답을 수정하거나, 리다이렉트, 요청 또는 응답 헤더 수정, 직접 응답을 제공할 수 있습니다.</p><p><a href="https://nextjs.org/docs/app/building-your-application/routing/middleware">공식 문서</a></p><ol><li>config</li></ol><pre>   export const config = {<br>     matcher: [<br>       &quot;/((?!api|_next/static|_next/image|favicon.ico|fonts|images).*)&quot;,<br>     ],<br>   };</pre><p>middleware는 기본적으로 프로젝트의 모든 라우트에 적용됩니다. 따라서 필요한 경로만 특정하여 적용하기 위해 정규식을 사용했습니다.</p><p>위의 설정은 api, \_next/static, \_next/image, favicon.ico, fonts, images를 포함하지 않는 모든 경로에 미들웨어가 적용되도록 지정하였습니다.</p><p>2. url 설정 처리</p><pre>   const url = request.nextUrl.clone();<br>   url.pathname = &quot;/signin&quot;;<br>   return NextResponse.redirect(url);<br><br>   // return NextResponse.redirect(&quot;/signin&quot;); 이전 코드</pre><p>Next.js 13 버전부터는 상대 URL을 직접 전달하는 것이 허용되지 않습니다.</p><p>따라서 요청의 URL을 복제한 후 해당 URL의 경로를 변경하여 절대 URL을 생성하였습니다.</p><p><a href="https://nextjs.org/docs/messages/middleware-relative-urls">공식 문서</a></p><p>3. localstore대신 쿠키 활용</p><pre>const token = getTokenFromCookies(request);<br><br>   function getTokenFromCookies(request: NextRequest) {<br>     const cookiesHeader = request.headers.get(&quot;cookie&quot;);<br>     if (!cookiesHeader) return null;<br><br>     const cookiesArray: [string, string][] = cookiesHeader<br>       .split(&quot;; &quot;)<br>       .map((cookie) =&gt; {<br>         const [key, value] = cookie.split(&quot;=&quot;);<br>         return [key, value];<br>       });<br><br>     const cookies = new Map(cookiesArray);<br>     return cookies.get(&quot;accessToken&quot;);<br>   }</pre><p>middleware 환경에서는 클라이언트 사이드의 localstorage에 직접 접근할 수 없습니다. 따라서 사용자 인증 정보를 저장하는 방식을 localstorage에서 쿠키로 변경하였습니다.</p><p><strong>3.3 수정 및 결과</strong></p><pre>import { NextResponse } from &quot;next/server&quot;;<br>import type { NextRequest } from &quot;next/server&quot;;<br><br>export const config = {<br>  matcher: [&quot;/((?!api|_next/static|_next/image|favicon.ico|fonts|images).*)&quot;],<br>};<br><br>const protectedRoutes = [&quot;/map&quot;]; // 로그인이 필요한 페이지 목록<br>const publicRoutes = [&quot;/signin&quot;, &quot;/signup&quot;]; // 로그인이 되면 접근할 수 없는 페이지 목록<br><br>export function middleware(request: NextRequest) {<br>  const token = getTokenFromCookies(request);<br>  const currentPath = request.nextUrl.pathname;<br><br>  if (!token &amp;&amp; protectedRoutes.includes(currentPath)) {<br>    const url = request.nextUrl.clone();<br>    url.pathname = &quot;/signin&quot;;<br>    return NextResponse.redirect(url);<br>  }<br><br>  if (token &amp;&amp; publicRoutes.includes(currentPath)) {<br>    const url = request.nextUrl.clone();<br>    url.pathname = &quot;/&quot;;<br>    return NextResponse.redirect(url);<br>  }<br><br>  return NextResponse.next();<br>}<br><br>function getTokenFromCookies(request: NextRequest) {<br>  const cookiesHeader = request.headers.get(&quot;cookie&quot;);<br>  if (!cookiesHeader) return null;<br><br>  const cookiesArray: [string, string][] = cookiesHeader<br>    .split(&quot;; &quot;)<br>    .map((cookie) =&gt; {<br>      const [key, value] = cookie.split(&quot;=&quot;);<br>      return [key, value];<br>    });<br><br>  const cookies = new Map(cookiesArray);<br>  return cookies.get(&quot;accessToken&quot;);<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iyaEH_EUf_gYKinv" /></figure><blockquote><em>결과적으로, 기존에 비해 불필요한 리소스의 낭비를 크게 줄이면서, 서버 사이드에서 페이지 라우팅 처리를 효과적으로 수행</em></blockquote><p><strong>4. 기타(Cookie)</strong></p><p>그런데, 토큰 정보를 LocalStorage가 아닌 cookie로 저장해도 괜찮을까요?</p><p>사실 습관처럼 항상 토큰정보는 LocalStorage에 저장하고 있었기 때문에 별도의 문제점은 없는지 궁금했습니다.</p><p>아래는 두 저장소의 특징을 찾아 표로 나타낸 것 입니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*64jfEPMBXaYbr25TYBM4lQ.png" /></figure><p>여기서, 실제 사용중인 토큰의 길이를 계산해보니 전체 1,343자로, ASCII기준 약 1.3KB를 차지하고 있었기때문에 사용하는데 큰 문제는 없다고 판단했습니다.</p><p>(유저 뿐 아니라 회사및 기타 복합적인 정보를 많이 담고 있는 서비스였기때문에, 현 프로젝트에서는 더 적은 길이를 가지게되겠네요)</p><p>또한 보안적인 이슈에서 쿠키를 사용했을때 XSS공격에서 안정적이고 사용하는데 문제가 없다고 생각해 괜찮은 수정방안이라고 결정 지었습니다.</p><blockquote><em>추가로, AccessToken은 메모리에 저장하고 RefreshToken은 쿠키에 저장하는 방식을 사용하면 JWT 토큰의 크기 제한 문제와 공격자에 의한 데이터 탈취 위험을 최소화 할 수 있다고 한다.</em></blockquote><blockquote>왜냐하면, CSRF에 의해 RefreshToken이 사용되어도 실제로 필요한 AccessToken정보는 알 수 없기 때문</blockquote><blockquote>새로고침 등의 휘발성에 대해서는 쿠키의 RefreshToken을 사용해 다시 AccessToken을 발급받으면 된다</blockquote><p><strong>6. 트러블슈팅</strong></p><p>그렇게 잘 되는 줄 알았으나, 한 가지 문제가 있었습니다.</p><p>사용자가 페이지를 새로고침했을 때 Next.js의 middleware가 동일한 페이지에 대해 재호출되지 않는 문제가 있었거든요.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*ZKLgc8DQRTouNvMK" /></figure><blockquote><em>/ 페이지와 /signin 페이지를 왔다갔다 했는데 middleware가 동작하지 않는다</em></blockquote><blockquote>새로고침을 한 시점에서, 각 페이지가 한번씩만 호출된다 (캐싱문제..?)</blockquote><blockquote>그러나, 만약 10~20초가 지나면 정상적으로 동작한다 (각 페이지에서 계속 호출)</blockquote><p>따라서 로그인과 로그아웃을 했을때 middleware가 실행되지 않아 페이지 라우팅이 일어나지 않는 문제를 해결해야만 했습니다.</p><p><strong>6.1 해결</strong></p><p>이 문제의 원인은 명확하게 파악하지 못했지만, middleware의 캐시를 지우는 방법에 대해서도 현상이 유지되었기때문에</p><p>아래의 코드를 통해 로그인, 로그아웃 시점에 페이지를 새로고침하도록 처리했습니다🥲 (임시방편..)</p><pre>// middleware.ts<br><br>//  { ... }<br>const nextResponse = NextResponse.next();<br>nextResponse.headers.set(&quot;x-middleware-cache&quot;, &quot;no-cache&quot;);<br>console.log(&quot;middleware.ts: nextResponse&quot;);<br>return nextResponse;<br><br>// not working</pre><pre>// when login Success<br>const handleLoginSuccess = (token: string) =&gt; {<br>  Cookies.set(&quot;accessToken&quot;, token, { expires: 1 });<br>  setLoggedIn(true);<br>  router.push(&quot;/&quot;);<br>  router.refresh();<br>};<br><br>// when logout success<br>const logout = () =&gt; {<br>  setLoggedIn(false);<br>  queryClient.clear();<br>  router.push(&quot;/&quot;);<br>  router.refresh();<br>  Cooki</pre><p><a href="https://github.com/vercel/next.js/discussions/43675">참고자료</a></p><p><strong>6. 참고자료</strong></p><p>https://nextjs.org/docs/app/building-your-application/routing/middleware</p><p><a href="https://medium.com/@zachshallbetter/protecting-routes-in-next-js-with-app-router-53c3409c0655">Protecting Routes in Next.js 13</a></p><p>https://medium.com/@zachshallbetter/protecting-routes-in-next-js-with-app-router-53c3409c0655</p><p><a href="https://hshine1226.medium.com/localstorage-vs-cookies-jwt-%ED%86%A0%ED%81%B0%EC%9D%84-%EC%95%88%EC%A0%84%ED%95%98%EA%B2%8C-%EC%A0%80%EC%9E%A5%ED%95%98%EA%B8%B0-%EC%9C%84%ED%95%B4-%EC%95%8C%EC%95%84%EC%95%BC%ED%95%A0-%EB%AA%A8%EB%93%A0%EA%B2%83-4fb7fb41327c">LocalStorage vs. Cookies: JWT 토큰을 안전하게 저장하기 위해 알아야할 모든것</a></p><p>https://jjunn93.com/entry/JWT-%EC%A0%80%EC%9E%A5-localStorage-vs-Cookie</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63a580b6b32c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>