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!
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With