Thomas Allen
Thomas Allen

Reputation: 811

How to get User information from JWT cookie in NextJS / ReactJS

I am learning about Next.JS and React and was wondering if it is possible to get user details from the cookie storing the JWT.

I have managed to set the JWT as the cookie and can log it successfully and have also managed to decode it but can't find anything on how to get username, id, etc from it. Here's what I have so far:

import React from "react";
import App from "../components/App.js";
import cookie from "react-cookies";
import jwt_decode from "jwt-decode";

export default class Dashboard extends React.Component {
 static async getInitialProps() {
  const token = cookie.load("jwt");
  return { token };
 }

constructor(props) {
  super(props);
  this.state = props.token;
 }

render() {
  const current_user = jwt_decode(this.props.token, { header: true });

return (
  <App>
    <p>Username: {current_user.username}</p>
  </App>
  );
  }
}

Ideally, i'd like to be able to set the cookie value to a user variable and extract properties from it, e.g. current_user.username. Unless i've got it completely wrong and have missed out something really important! Any help would be massively appreciated!

Upvotes: 14

Views: 26085

Answers (2)

Md.Shakil Shaikh
Md.Shakil Shaikh

Reputation: 351

You can use npm package. Simply run npm install jwt-decode in the cmd and use the following code:

import jwt_decode from "jwt-decode"; 
  
const token = "eyJ0eXAiO.../// jwt token";
const decoded = jwt_decode(token);

Upvotes: 1

Harish Soni
Harish Soni

Reputation: 1896

You can use this parseJwt function to extract the user data:

function parseJwt(token) {
    if (!token) { return; }
    const base64Url = token.split('.')[1];
    const base64 = base64Url.replace('-', '+').replace('_', '/');
    return JSON.parse(window.atob(base64));
}

console.log(parseJwt('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'))

It will extract the data inside a jwt token and will return an object

Upvotes: 32

Related Questions