How to Store an Auth Token in Local Storage in React
Great job in getting that user stored and redux. What I want to show you in this video is how to set the token that we're also getting back from our response into the local storage, so we can use it on routes that require us to pass in a token.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

So let's real quick just going to our reducer here and put console.log(action.payload), so we can see that token one more time because right now we don't have it storing into redux, which we don't want to do and we don't have it in our local storage. So there's no way to view it unless we log in.

Alright, so type in that log into our authReducer.js, and let's go to the browser and let's create a new account.

large

Go to localhost:3000 or whatever port you are running it on, and go to a non-member register here and let's register for another account. Make sure it has an e-mail that you haven't used yet. It can be whatever, and hit create account. We get back the token and user object restoring the users. We don't need to worry about that. We just need to focus on the token.

large

If you open up a new tab and you go to your server. So go to localhost:3090/newsletters. You're going to get an unauthorized message back, and that's because this route requires that we pass a JWT auth token to it.

large

Now the only way to do this or the way it's programmed is to pass it in as a header. Now there's two ways I can show you this by writing out the request or by showing you that postman. I'm not going to have a code out the entire thing right now because we're not focusing on getting the news letters yet. We're just focusing on the token.

So I'm going to open up postman, which I just tried, and if you go to localhost:3090/newsletters in here, and you hit send. You're going to get the unauthorized, but if you pass in this token that you're receiving as a header, you'll get back the newsletters.

large

Now on your server that you're running, you're not going to have any newsletters unless you went ahead and made one after messing around with the API of it. In all likelihood if you didn't do anything or if you've just been following along, you're not going to have any in your database.

So I'm going to go ahead and show you that I have one in there. I was messing around with it, and I have one in there. If you have postman open, you can follow along. You don't have to do this, but it's mostly just to show you that we need to store this token somewhere.

You'll see that if I go to I go to headers, and I type a new key authorisation and I pass in this token that we got back and then I hit send. We get back the existing newsletters.

large

Right now there's just one that I made, and you're not going to have any, but you should not get the unauthorized message back. You might get an error or an empty array, but you're not going to get the unauthorized if you're doing this yourself with the JWT Don't get me you got back. That's why we need to store it.

large

Again, you don't have to be doing this in postman, it's just to show you why we need it. We're going to touch on it later on. I just want you to understand that we have to store it in our local storage for authenticated requests.

So let's go ahead and do that now by going into our code, and getting rid of this console.log and then we're going to store it in something called local storage.

large

So let's go to let's go to auth.js in our actions folder, and right before our dispatch, we're going to store it and local storage.

auth.js

export function signUp(fields, success) {
    return function(dispatch) {
        axios.post(`${ROOT_URL}/signUp`, fields)
            .then(response => {
                const { token } = response.data;
                localStorage.setItem('token', token);
                dispatch({
                    type: STORE_USER,
                    payload: response.data
                })
                success()
            })
            .catch(err => {
                if(err) { console.log(err) }
            })
    }
}

So that should set it. Let's go ahead and go to our browser, and we're going to have to create another account. I'll show you how we can just delete all the accounts once we're done with all this because it's going to fill up our database pretty quick. So full name, that can just be a name, unit number, just put in all these details, and let's create an account.

We don't have a printing, but to show you where this local storage is in the browser. It is in our tab here under application. So I was looking for local storage. Anyway, it's under application, and you'll see that we have a token.

large

Now I have a bunch of different things in here from other applications. I'm going to clear it all, and create one more account so you can see that a little more clearly.

OK, so I'm going to go down here. I'm going to go back to create an account. I'm going to create an account, and I got an error because I used the same email. So I'm just going to put in some unique characters there. Hit create account. You shouldn't get an error, but you should see your local stores now you have a token. That's our token.

Now we can access that token in our code whenever we need it by saying:

auth.js

export function signUp(fields, success) {
    return function(dispatch) {
        axios.post(`${ROOT_URL}/signUp`, fields)
            .then(response => {
                const { token } = response.data;
                localStorage.setItem('token', token);
                localStorage.getItem('token');
                dispatch({
                    type: STORE_USER,
                    payload: response.data
                })
                success()
            })
            .catch(err => {
                if(err) { console.log(err) }
            })
    }
}

Then we can pass it in as a header like I'm doing in postman here to get back our newsletters or something when we're signed in. So it's another security step on the front end that we can use to make sure that the person is actually authenticated.

Obviously, we're authenticating them with our response already, but that's not always entirely secure. We want to make sure that we have something in local storage like a token because local storage can't be modified by outside applications. It's on our machine, and it can't be touched by anyone but us.

Let's go ahead and move on to the next video where we will implement the signin ability, and we have plenty of accounts at this point, so we can use those to try and sign in. So what we're going to do is build out the action and reducer, and just get the entire feature in there and store the token as well. Because we're going to get a token back here. We're also going to get back a user object once we log in.

It's going to be very similar to this except for with a different post, so we're going to be using the same action once we get a response back and all that junk. Let's go ahead and commit our code.

Let's go in and say git status, and we only changed one thing. If you type in git diff, You'll see where our changes are. We only added in the token and the local storage item. Then to get out of this you just have to hit :q, and then hit return. That will take you out of that.

Now what we have to do is git status, git add ., git commit -m "set token in local storage". See you in the next video.

Resources