Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 210
Thomas Allen Avatar asked Jan 04 '19 09:01

Thomas Allen


People also ask

How do I get the username from JWT token in react?

You can add data to a token using a rule. In a rule, you will add a custom claim. If you want the username of the user, it can be accessed via the user. username object in the rule.

How do I use JWT in Nextjs?

js Client App. The Next. js client (React) app contains two pages: /login - public login page with username and password fields, on submit the page sends a POST request to the API to authenticate user credentials, on success the API returns a JWT token to make authenticated requests to secure api routes.


1 Answers

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

like image 79
Harish Soni Avatar answered Sep 23 '22 17:09

Harish Soni