0

I've started learning Node.js in the past few weeks, and I've finished a course of it. Sadly, the course didn't cover everything, this is why I came here.

So, the course covers the handling of JWT in the server side, but it didn't mention anything on the client side js, because they've used Postman. I understand everything, expect the fact that how can I store these tokens on the client, and how to send them with requests. I read things like the client side js stores it in a cookie or the localstorage. Okay, so if i were to store it in the localstorage, then I'd need to send it with every request, wouldn't I? If so, then it wouldn't be too efficent in my opinion. What if the client types an URL like www.example.com/somepage, and it requires authentication? In this example, he'd need to set it manually. Is there a way to automatically set the header after login?

Every tutorial or topic that i found about this doing it with postman.

Please don't sue me if this doesn't make any sense, I just want to clear things, because I'm confused a little bit.

Have a nice day!

kisroby
  • 3
  • 1

4 Answers4

0

1) You should use cookie or localStorage to store JWT token.

2) pass that JWT token in headers via Authorizartion so:

Authorization: Bearer {JWT_TOKEN}

3) put it in headers of all your get,post,put, delete requests

parthjani7
  • 56
  • 5
0

Yes, You have to write http interceptors in client side, to handle JWT token in every request after login, It is the efficient way to do it

Please read through this https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Intercept_HTTP_requests

yaswanthkoneri
  • 408
  • 4
  • 16
0

You can save it in localStorage via localStorage.set("keyName", keyValue);. Retrieving it can be done via localStorage.get("keyName");

When sending it to the Server, you can either send it as a parameter in a PUT Request or you set it as a custom header. That depends on the libraries you use.

Gh05d
  • 7,923
  • 7
  • 33
  • 64
0

What if the client types an URL like www.example.com/somepage, and it requires authentication?

For this purpose, you can just write Express middleware to handle this.

You write the middleware in one file, import it where needed, and simply call it for each route that required authentication.

app.get('/some-protected-route', auth, (req, res) => {

// do something

} )

SA answer here: How to setup an authentication middleware in Express.js

Lots more tutorials, explanations etc in various other places too.

kkenney
  • 26
  • 1
  • Sorry if my question was equivocal. I know what middleware and I know this type of implementaion on the server side. So, here the auth middleware is checking the jwt if its valid, but here the jwt already passed to the server from the client. What I meant is how can I implement the automatic setting of the jwt in the client side. – kisroby Apr 15 '20 at 19:21