Display and use data from JWT token in Next.js

Viewed 661

I build an application in Next.js. I use JWT token for authentication from my symfony lexic jwt api. Here is piece of my code:

   const [user, setUser] = useState([]);
   const [isLoading, setIsLoading] = useState(false);
   const [loggedIn, setLoggedIn] = useState(false);

 function login_check() {
  let data = { username, password };
  setIsLoading(true);
  let result = fetch("https://myfetchapi", {
    method: "POST",
    headers: {
    "Content-Type": "application/json",
    Accept: "application/json",
  },
  body: JSON.stringify(data),
})
  .then((response) => response.json())

  .then((data) => {
    if (data.error) {
      setError("Invalid credentials");
    }
    if (data && !data.error) {
      setUser(data.token);
      setLoggedIn(true);
      Cookies.set("user-info", JSON.stringify(data.token));

      router.push("/");
    }
    console.log(data.token);
  })

Everything works fine. But Token includes user ID i would like to get and use for booking. When I set an additional function while i'm logged in (so there is token in cookies) I receive decoded data in console, no problem.

 user ? console.log(jwt_decode(user)) : console.log("login");

The problem is, when I logout, I get a big full screen error "invalide token" instead of the string in console. It seems, that this function is not conditional and it tries to decode nonexisted token. I use import jwt_decode from "jwt-decode".

How can I get data from decoded jwt token and use it further?

Thanks everyone!

0 Answers
Related