본문 바로가기

TIL/JavaScript

React access 토큰 디코딩

access 토큰 디코딩해서 userId 얻기

 

import base64 from 'base-64';

export const getUserId = (token) => {
    try {
        if (!token) {
            throw new Error('Token is undefined or empty');
        }

        const payload = token.substring(token.indexOf('.') + 1, token.lastIndexOf('.'));
        const decodingInfo = base64.decode(payload);
        const decodingInfoJson = JSON.parse(decodingInfo);
        return decodingInfoJson.user_id;
    } catch (error) {
        console.error('Failed to decode token:', error);
        return null;
    }
}

'TIL > JavaScript' 카테고리의 다른 글

React JWT로 로그인 구현  (0) 2024.06.05
Js 객체 <-> JSON 문자열 변환  (0) 2024.05.24
React Dynamic Route  (0) 2024.05.24
React Router Dom  (0) 2024.05.24
jQuery 기본 문법  (0) 2024.02.19