[Devlog] SSE로직 구현 중, EventSource에 headers담기

swing·2023년 5월 30일
1

[Devlog]

목록 보기
4/7

문제상황


  • 스크린샷
Argument of type '{ headers: { Authorization: string; }; withCredentials: true; }' 
is not assignable to parameter of type 'EventSourceInit'.
Object literal may only specify known properties, and 'headers' does not exist in type 'EventSourceInit'.ts(2345)
(property) Authorization: string

새로운 EventSource를 만들어 SSE API와 연결하는 로직을 구현하는 과정에서, 인증 토큰을 헤더에 담아 보내야 했다. 그 과정에서 EventSource의 Type에 headers가 존재하지 않았다.`

해결


이를 해결하고자 event-source-polyfill 라이브러리를 사용하여, XHR Header type을 수동적으로 주입시켜주었다.

import { EventSourcePolyfill, NativeEventSource } from "event-source-polyfill";
// ...
const EventSource = EventSourcePolyfill || NativeEventSource;
const SSE = new EventSource(
      `${process.env.REACT_APP_SERVER_URL}connect/${post.id}`,
      {
        headers: {
          Authorization: `Bearer ${getCookie("reqWithToken")}`,
        },
        withCredentials: true,
      }
    );

참고


[react] SSE headers에 토큰값이 담기지 않던 문제

event source 관련 멘토님의 답변

profile
if(기록📝) 성장🌱

0개의 댓글