# WEEK 7 - ReactJS Continue And DEPLOYMENT ###### tags: `WEB` `JS` `DIGITALIZE` `FRONTEND` `REACTJS` ## JWT Decoding jwt-decode is a small browser library that helps decoding JWTs token which are Base64Url encoded. **NOTE:** This library doesn't validate the token, any well formed JWT can be decoded. You should validate the token in your server-side logic ### Instalation Run npm install jwt-decode or yarn add jwt-decode to install the library. ### Usage ``` import jwt_decode from "jwt-decode"; var token = "eyJ0eXAiO.../// jwt token"; var decoded = jwt_decode(token); console.log(decoded); /* prints: * { foo: "bar", * exp: 1393286893, * iat: 1393268893 } */ // decode header by passing in options (useful for when you need `kid` to verify a JWT): var decodedHeader = jwt_decode(token, { header: true }); console.log(decodedHeader); /* prints: * { typ: "JWT", * alg: "HS256" } */ ``` ### Implementation in Clinic App Let's make our application more secure and working in a proper way, curently we are checking the existing of the user data and token and depends on that we can authorize the user to visit protectecd route or not, but this is not secure, we must validate the token and check expire datetime before deciding to auhorize user or not, so we will use this package: `AuthContext`: ``` // token decoding and validation functions const isValidToken = (accessToken) => { if (!accessToken) { return false; } const decoded = jwtDecode(accessToken); const currentTime = Date.now() / 1000; return decoded.exp > currentTime; }; ``` Now we will use this function in useEffect while we fetching token from local storage: ``` if(data.token && isValidToken(data.token)) { console.log('token found and added as default') setIsUserAuth(true) setUserData(data) axios.defaults.headers.common.Authorization = `Bearer ${data.token}`; } ``` ## HOC (Higher-Order Component) HOC is an advanced technique for reusing component logic. It is a function that takes a component and returns a new component. According to the official website, it is not the feature(part) in React API, but a pattern that emerges from React compositional nature. They are similar to JavaScript functions used for adding additional functionalities to the existing component. SYNTAX ``` const NewComponent = higherOrderComponent(WrappedComponent); ``` https://reactjs.org/docs/higher-order-components.html ## Refs https://reactjs.org/docs/refs-and-the-dom.html ## More to know ### Packages - Styled components - React DnD - Material UI - React Hook Form - For Localization: https://react.i18next.com/ For State Management: - Redux ## Deployment ### Netlify