How to use JWT with React?

        const token = jwt.sign({_id:user._id},process.env.SECRET)

How can I send this back to React in response so that it can store it somewhere and send that in the request to the middleware so it can be verified?

When they sign in, you send it back to them (or whenever). They can store it in local storage and return it with requests that need auth (or for whatever).

1 Like

Thank you, I also wanted to do it that way but I’ve read that storing tokens in a local storage is not the best practice so I was a bit skeptical about that

Yeah, I’ve read that too. And in all fairness, I’m no expert. I just know what I’ve seen. Reading a little, it appears that there is no perfect solution, but there seems to be a preference for cookies over local storage for sensitive information. I work mainly on mobile so this isn’t even an option.

1 Like

Okay, thank you for the answer, I’ve implemented that solution and it works :slight_smile:

One caveat that I remember about JWTs is that they don’t automatically expire. Be sure to encode some expiration date in your JWT so that your b/e knows when to stop accepting that JWT. Alternatively, you could encode a creation date and have your server determine when to stop accepting it.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.