---
title: "Discussion on \"React & JWT Authentication - the right way!\" | Hashnode"
description: "Discussion on \"React & JWT Authentication - the right way!\". In this series of posts, we create a secured end-to-end JWT-based authentication mechanism using NodeJS, Express, PassportJS, and React.\nIn this series I cover:\n\nPart 1:  Background and Backend using NodeJS \nPart 2: React & JWT Authentication (This p..."
url: "https://hashnode.com/posts/react-and-jwt-authentication-the-right-way/5f7332311d7a870a345b9db2"
---

[Feed](https://hashnode.com/feed) /

Discussion

# [React & JWT Authentication - the right way!](https://blog.galmalachi.com/react-and-jwt-authentication-the-right-way?utm_source=hashnode&utm_medium=feed)

In this series of posts, we create a secured end-to-end JWT-based authentication mechanism using NodeJS, Express, PassportJS, and React. In this series I cover: Part 1: Background and Backend using NodeJS Part 2: React & JWT Authentication (This p...

Sep 29, 2020 · 18 min read · blog.galmalachi.com  
Updated Dec 21, 2020  
Read the article

-   [#reactjs](https://hashnode.com/tag/reactjs)
-   [#authentication](https://hashnode.com/tag/authentication)
-   [#jwt](https://hashnode.com/tag/jwt)
-   [#security](https://hashnode.com/tag/security)

## Written by

[Gal Malachi](https://hashnode.com/@galm)

@galm · Tel Aviv, Israel

  
[View profile](https://hashnode.com/@galm)

Developer

Fast learner, innovative, curious, highly motivated with a 'can-do' approach. I enjoy challenges and I thrive where there are technical questions that need to be answered.

## Responses 4

Markdown supported · ⌘↵ to post

[Jairo Pakes](https://hashnode.com/@jpakes)

[Apr 26, 2024](https://hashnode.com/posts/react-and-jwt-authentication-the-right-way/5f7332311d7a870a345b9db2/comment/662ba4ccb7a64b789cdda22b)

Thanks, Gal. 4 years already and still great content. I'm a new to React and probably missing some basic knowledge, but what is the AuthEvents in your code?

[Martin Filteau, Eng., PMP](https://hashnode.com/@mfilteau)

[Nov 12, 2020](https://hashnode.com/posts/react-and-jwt-authentication-the-right-way/5f7332311d7a870a345b9db2/comment/5fad8694fa438d6532c7e735)

Assuming that the user has logged previously and that we have a valid refresh-token stored in a cookie, when we start the application again, user will be null until the token is refreshed.

Since user is null, any protected route will be redirected to login.

How do you usually wait for the first refresh to complete so the user is not redirected to login?

[Martin Filteau, Eng., PMP](https://hashnode.com/@mfilteau)

[Nov 12, 2020](https://hashnode.com/posts/react-and-jwt-authentication-the-right-way/5f7332311d7a870a345b9db2/comment/5fad8694fa438d6532c7e735#reply-5fad9827fa438d6532c7e824)

I figured it out. I've added a state 'waitingForToken' that is initially true.

```
    const [user, setUser] = useState(null);
    const [waitingForToken, setWaitingForToken] = useState(true);
    const refreshToken = useCallback(refresh, []);
```

In refresh(), I set the state to false.

```
    async function refresh() {
        try {
            const {
                data: { user, ...rest },
            } = await axios.post('refresh-token', {}, { withCredentials: true });
            setUser(user);
            setToken(rest);
        }
        finally {
            setWaitingForToken(false);
        }
    }
```

And export it:

```
    return {
        user,
        waitingForToken,
        setUser,
```

Then in my App:

```
const App = () => {
    const { waitingForToken } = AuthContainer.useContainer();
    return (waitingForToken ? <div/> :
        <Switch>
            <Route path="/login" component={Login} />
            <ProtectedRoute exact={true} path="/" component={Dashboard} />
            <ProtectedRoute path="/settings" component={Settings} />
            <ProtectedRoute component={Dashboard} />
        </Switch>                
    );
```

Hope this can help someone!

[Gal Malachi](https://hashnode.com/@galm)

[Nov 13, 2020](https://hashnode.com/posts/react-and-jwt-authentication-the-right-way/5f7332311d7a870a345b9db2/comment/5fad8694fa438d6532c7e735#reply-5fae3a27fa438d6532c7ed53)

Great addition, thanks [Martin Filteau, Eng., PMP](https://hashnode.com/@mfilteau) 💪🏽

[rasd](https://hashnode.com/@rasd)

[Sep 30, 2020](https://hashnode.com/posts/react-and-jwt-authentication-the-right-way/5f7332311d7a870a345b9db2/comment/5f744280e46f1616184269a2)

What happens when the token should be refreshed and you have multiple requests that are being sent at that time? Won't all the request get 401?

[Gal Malachi](https://hashnode.com/@galm)

[Sep 30, 2020](https://hashnode.com/posts/react-and-jwt-authentication-the-right-way/5f7332311d7a870a345b9db2/comment/5f744280e46f1616184269a2#reply-5f74458b5defaf19d6aada50)

Yes, you are right. To prevent that we should send the refresh-token request few seconds before it expires. I will add that in.

[rasd](https://hashnode.com/@rasd)

[Sep 30, 2020](https://hashnode.com/posts/react-and-jwt-authentication-the-right-way/5f7332311d7a870a345b9db2/comment/5f744280e46f1616184269a2#reply-5f7451b2b9c62319b5670fe0)

[Gal Malachi](https://hashnode.com/@gal1419) I usually have a retry logic. So if it happens and a request is sent and has a 401 it will get the token and add it to retry list using the promise. If requests are being sent after sending the request to get the token but before setting it, I add it to the retry list. So using the request(the ones that should be sent) and response(the ones that got 401) interceptors I will add the request to the retry list and send them when the token has been refreshed using the promises(replace the old token). I use a timer to refresh the tokens but also have the retry logic attached to that. The oauth2 implementation I have worked with will not provide new tokens unless the old ones are expired, even if it would I think there are scenarios where the token would be invalid for current request. But even with this implementation I am unsure if this is a good solution, I feel there could be other scenarios in which the token would not be used/refreshed properly.

[Gal Malachi](https://hashnode.com/@galm)

[Sep 30, 2020](https://hashnode.com/posts/react-and-jwt-authentication-the-right-way/5f7332311d7a870a345b9db2/comment/5f744280e46f1616184269a2#reply-5f74624d5defaf19d6aadb95)

[rasd](https://hashnode.com/@rasd) sounds like a complete solution! I thought about setting a retry logic, but I didn’t want to complicate stuff since this post is very long as is. However, I do believe that calling the refresh endpoint few seconds before the token expires should cover 99% of the cases.

[Hod Benbinyamin](https://hashnode.com/@Hod)

[Sep 29, 2020](https://hashnode.com/posts/react-and-jwt-authentication-the-right-way/5f7332311d7a870a345b9db2/comment/5f7370031d7a870a345ba19e)

Thanks Gal for this interesting post. Much appreciated

[Gal Malachi](https://hashnode.com/@galm)

[Sep 29, 2020](https://hashnode.com/posts/react-and-jwt-authentication-the-right-way/5f7332311d7a870a345b9db2/comment/5f7370031d7a870a345ba19e#reply-5f73705a1d7a870a345ba1ad)

Thanks for the feedback, Hod! Glad you found it interesting!
