Sule
Sule

Reputation: 1

Accessing the token on the front end

I am building a web app with nodejs. I am using express-jwt for authorization. Since I am relatively new in the web development field, I decided not to use frameworks for the front-end. I am building the frond-end using ejs templating.

How do I hook onto the token that is generated when the user logs in ?. I have been doing tests on Postman and everything works.

Any assistance or leads will be appreciated :)

Suleiman

Upvotes: 0

Views: 2236

Answers (2)

zakum1
zakum1

Reputation: 1112

You should also see this article about why storing tokens in local storage is not such a good idea. It contains some other suggestions on how to manage tokens on the client side.

Upvotes: 0

Rajan Sharma
Rajan Sharma

Reputation: 2273

Its very simple to deal with jwt tokens, you just need basic javascript in the frontend.Whenever the user logs in store the jwt token(that you will get from server) in the local storage of the browser.

localStorage.setItem('jwt', token);

Whenever you need the token for requesting a resource just fetch the token from the local storage and provide it to the backend server with the http request.

var myData = localStorage.getItem('jwt');

If the token gets expired you will receive authentication error from the server(need to program like that) remove the jwt token from the local storage and log out the user.

localStorage.clear();

At any point of time, you can access the token from the local storage to make a backend call. Similarly you can also store other information in the same fashion which would be helpful (like basic details of the user)

Upvotes: 1

Related Questions