Skip to content

Commit 85f37a1

Browse files
committed
fix(auth): sync tokens between tabs
1 parent ff28a66 commit 85f37a1

File tree

1 file changed

+29
-1
lines changed

1 file changed

+29
-1
lines changed

src/services/auth/auth-provider.tsx

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,10 @@ import HTTP_CODES_ENUM from "../api/types/http-codes";
2323

2424
function AuthProvider(props: PropsWithChildren<{}>) {
2525
const AUTH_TOKEN_KEY = "auth-token-data";
26+
const [tabId] = useState(() => Math.random().toString(36).slice(2));
27+
const [broadcastChannel] = useState(
28+
() => new BroadcastChannel(AUTH_TOKEN_KEY)
29+
);
2630
const [isLoaded, setIsLoaded] = useState(false);
2731
const [user, setUser] = useState<User | null>(null);
2832
const tokensInfoRef = useRef<Tokens>({
@@ -43,6 +47,10 @@ function AuthProvider(props: PropsWithChildren<{}>) {
4347
const setTokensInfo = useCallback(
4448
(tokensInfo: TokensInfo) => {
4549
setTokensInfoRef(tokensInfo);
50+
broadcastChannel.postMessage({
51+
tabId,
52+
tokens: tokensInfo,
53+
});
4654

4755
if (tokensInfo) {
4856
Cookies.set(AUTH_TOKEN_KEY, JSON.stringify(tokensInfo));
@@ -51,7 +59,7 @@ function AuthProvider(props: PropsWithChildren<{}>) {
5159
setUser(null);
5260
}
5361
},
54-
[setTokensInfoRef]
62+
[setTokensInfoRef, broadcastChannel, tabId]
5563
);
5664

5765
const logOut = useCallback(async () => {
@@ -112,6 +120,26 @@ function AuthProvider(props: PropsWithChildren<{}>) {
112120
loadData();
113121
}, [loadData]);
114122

123+
useEffect(() => {
124+
const onMessage = (
125+
event: MessageEvent<{
126+
tabId: string;
127+
tokens: TokensInfo;
128+
}>
129+
) => {
130+
if (event.data.tabId === tabId) return;
131+
132+
if (!event.data.tokens) setUser(null);
133+
setTokensInfoRef(event.data.tokens);
134+
};
135+
136+
broadcastChannel.addEventListener("message", onMessage);
137+
138+
return () => {
139+
broadcastChannel.removeEventListener("message", onMessage);
140+
};
141+
}, [broadcastChannel, setTokensInfoRef, tabId]);
142+
115143
const contextValue = useMemo(
116144
() => ({
117145
isLoaded,

0 commit comments

Comments
 (0)