React Redux Login Authentication Flow with JWT Access, Refresh Tokens, Cookies

  Рет қаралды 229,865

Dave Gray

Dave Gray

Күн бұрын

Web Dev Roadmap for Beginners (Free!): bit.ly/DaveGrayWebDevRoadmap
Learn React Redux Login Authentication Flow with JWT Access, Refresh Tokens, Cookies and more. This tutorial sets up a React Redux login and auth flow that uses JWT access and refresh tokens, secure cookies and an RTK Query base query reauthentication wrapper.
💖 Support me on Patreon ➜ / davegray
⭐ Become a full-stack web dev with Zero To Mastery Courses:
- Advanced React & Redux: bit.ly/AdvReactDev
- Jr to Senior Web Dev Roadmap: bit.ly/WebDevRoadmap-JrtoSr
- Master FAANG Coding Interviews: bit.ly/FAANGInterview
🚩 Subscribe ➜ bit.ly/3nGHmNn
🚀 Modern Redux full course - 4 hours: • React Redux Full Cours...
👀 React Login tutorial series playlist: • React Login, Registrat...
🔗 Completed Source Code: github.com/gitdagray/redux_jw...
🔗 Backend Node.js REST API Source Code: github.com/gitdagray/nodejs_j...
📬 Course Updates ➜ courses.davegray.codes/
React Redux Login Authentication Flow and JWT Access, Refresh Tokens, Cookies
(00:00) Intro
(00:46) Welcome
(01:36) Starter Code and Dependencies
(02:30) Begin Redux: authSlice
(05:50) baseQuery
(09:06) baseQuery with re-authorization wrapper
(14:57) apiSlice
(15:51) Extend the apiSlice to auth
(17:27) Configure the Redux store
(19:46) Begin React: index.js
(22:33) Layout component
(23:28) Public component
(24:11) Redux: Export useLoginMutation
(24:54) Login component
(31:48) RequireAuth component
(34:33) Welcome component
(37:12) App.js routing
(40:56) Node.js Backend Review
(43:20) Test the Login flow
(44:16) Redux: Extend the apiSlice to users
(47:20) React: UsersList component
(49:16) Update App.js routing
(49:57) JWT Auth Flow and RTK Query Cache
☕ Buy Me A Coffee: www.buymeacoffee.com/davegray
🔗 Node JS Full Course (with source code) for building the backend REST API that will receive your form submissions: • Node.js Full Course fo...
🔗 React Router Version 6 in 20 minutes: • React Router v6 in 20 ...
📚 Modern Redux Authentication References:
🔗 Redux Toolkit Authentication: redux-toolkit.js.org/rtk-quer...
🔗 baseQuery function arguments: redux-toolkit.js.org/rtk-quer...
🔗 Automatic re-authorization by extending fetchBaseQuery: redux-toolkit.js.org/rtk-quer...
📚 General Redux Toolkit References:
🔗 Official Site for Redux Toolkit: redux-toolkit.js.org/
🔗 Redux Devtools: github.com/reduxjs/redux-devt...
📚 JWT References:
Intro to JSON Web Tokens: jwt.io/introduction
All You Need to Know About Storing JWT in the Frontend: dev.to/cotter/localstorage-vs...
Cross-Site Scripting (XSS): owasp.org/www-community/attac...
Cross-Site Request Forgery (CSRF): owasp.org/www-community/attac...
📚 Accessible Form References:
WebAIM.org - Advanced Forms: webaim.org/techniques/forms/a...
WebAIM.org - Form Validation: webaim.org/techniques/formval...
MDN - Aria Attributes:
aria-invalid: developer.mozilla.org/en-US/d...
aria-describedby: developer.mozilla.org/en-US/d...
aria-live: developer.mozilla.org/en-US/d...
aria-label: developer.mozilla.org/en-US/d...
🔗 ES7 React JS Snippets Extension for VS Code:
marketplace.visualstudio.com/...
🔗 React Dev Tools Extension for Chrome:
chrome.google.com/webstore/de...
✅ Follow Me:
Github: github.com/gitdagray
Twitter: / yesdavidgray
LinkedIn: / davidagray
Blog: yesdavidgray.com
Reddit: / daveoneleven
Was this tutorial about Redux Login Authentication with JWT Access and Refresh Tokens helpful? If so, please share. Let me know your thoughts in the comments.
#redux #login #authentication

Пікірлер: 456
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
In this advanced tutorial, we'll take a look at a login authentication flow in React and Redux that uses JWT tokens and cookies. The key is to understand how to intercept a failed request, refresh your access token by sending your refresh token, and then sending your original request again with the new access token. This can be achieved with Axios interceptors, but with modern Redux, we apply RTK Query and build a base query wrapper function instead. If you are just starting with Redux, I recommend going to my Redux full course first: kzfaq.info/get/bejne/hNeql7l_l9rdpoU.html
@dimitarkrastev6085
@dimitarkrastev6085 Жыл бұрын
By far the best tutorial on the subject I have found. Every other tutorial creates something simple and practically non-applicable to any real world scenario like "incrementCounter". Good luck infering how to apply the "counter" redux example for a login for example... Getting a real life problem like this and fully implementing it end-to-end using the subject of the tutorial is just invaluable. Great video, thank you very much.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Glad it was helpful!
@dev-suresh
@dev-suresh 3 ай бұрын
Thanks for the value Dave. This video is not for complete beginners but definitely for beginners having done some good work excelling their skills.
@TwistedFate123
@TwistedFate123 Жыл бұрын
Dude you deserve more visibility on this platform!! Your explanations just simply works and easily understood!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Thank you for the kind words! 🙏
@jordanryanethanowona2974
@jordanryanethanowona2974 Жыл бұрын
@@DaveGrayTeachesCode Hi dave, thans for this great tutorial. everything works fine for me until the end when i had to add the users endpoint. i dont know if am missing something or if the framework has evolved but my users endpoint is never even called. i took a look at your code and it looks ok on my side.
@Yogesh2Love
@Yogesh2Love 2 жыл бұрын
You are making tutorial on what exactly we need to do in working conditions that's a big help Dave.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
You're welcome, Yogesh! 🙏🙏
@electro1146
@electro1146 Ай бұрын
Dave, your content is fantastic and it's great that you dive deep into stuff that others normally don't. However, it would be helpful if you provide links to documentation that we could use as reference.
@muhammadzeeshan07
@muhammadzeeshan07 6 ай бұрын
Excellent method of explanation, everything just went straightly into my brain, not over it🙃, Thanks a lot Dave for all of your content
@codegien
@codegien Жыл бұрын
I honestly would have given up on coding long ago but you keep me inspired. Thank you
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Glad I could help!
@dindoleonard
@dindoleonard 2 жыл бұрын
Every tutorial you create is gold! Thank you. Will send another coffee. 💪
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thank you, Leonardo! 🙏☕
@Yash-jp6xh
@Yash-jp6xh 3 ай бұрын
Absolutely loved this tutorial... helped me built up Login and setup authentication for my chat application.
@mamlzy
@mamlzy 2 жыл бұрын
work as expected! thank you so much fo this Auth & RTK Query tutorial, cant find like this in other youtube channel so far. Can't wait to see u discuss about Next.js SSR with RTK Query (CRUD example). I really appreciate your effort..
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
You're welcome!
@VinayakSoni98
@VinayakSoni98 6 ай бұрын
always helpful. when i dont find a particular section of a code/ logic i always check your videos and always mostly i find that you have covered that topic. was so confused that how to get user token from user slice to createApi i found it @9:18 always you videos are helpful.
@sumitkachare6628
@sumitkachare6628 2 жыл бұрын
Hi Dave really thanks for this series , there is always something new to learn from your videos. Thanks a lot.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
You're welcome, Sumit! 💯🙏
@patrick_kabwe
@patrick_kabwe 2 жыл бұрын
Just what i needed. Thank Dave you have been of help for the past 3 month
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
You're welcome, Patrick! 💯🚀
@TemitopeJoshua10
@TemitopeJoshua10 Жыл бұрын
Dave, thanks for helping me out, I love your channel from Nigeria 🇳🇬.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
You're welcome and hello to Nigeria!
@kishoreandra
@kishoreandra 2 жыл бұрын
Amazing Dave .... These videos are found no where with such quality I bet 💯
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Glad you like them! 🙏🚀
@kishoreandra
@kishoreandra 2 жыл бұрын
@@DaveGrayTeachesCode absolutely ... Would love to see more of it 😉 🙏🤞
@ManishMulchandani-rx2pk
@ManishMulchandani-rx2pk Ай бұрын
Big salute and thanks for sharing this vid. You've gained a loyal subscriber.
@codernerd7076
@codernerd7076 2 жыл бұрын
I was waiting for this video thank you so much!
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
You're welcome! Yes, many requests for this Login Authentication flow with Redux 💯
@TSpods
@TSpods Жыл бұрын
hello dave you are the best teacher in the world, all the tutorials you do helped me a world
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Thank you for the kind words!
@amaraag9435
@amaraag9435 10 ай бұрын
Hi Dave? I think your tutorials may be best tutorial right now. I have one question. I noticed you used setAll method for save data in store in 7th video. In this video you used independent reducer for save auth data in store. Which is better technique save data in store after fetch data?
@enzocodes
@enzocodes 8 ай бұрын
Hello Dave! First of all congratulations and thank you for making this awesome tutorial. I have a question, if we don't want the user to log in every time the page is refreshed.. do you recommend adding a method in the private route to authenticate a user with the refresh token in the cookies? That way we would have the token, or how would you persist a session? Thank you! Greetings from Argentina
@mumarqayyum9286
@mumarqayyum9286 Жыл бұрын
Everything is incredible explained. As a newbie to react and redux toolkit, i wish it has persiststate on reload using redux toolkit
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
I think you could apply a persist login strategy like the one I show here: kzfaq.info/get/bejne/aJ17mLyckpvaeqs.html ..but modify it from RTK Query.
@rajukadel1007
@rajukadel1007 Жыл бұрын
Waiting for your more videos....Super generous man---> Mr.Dave Gray !!!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Thank you!
@michaelangermeyer2118
@michaelangermeyer2118 10 ай бұрын
Really good Tutorials! They all helped me very much on creating software. What would be a good way to implement a persistent login with React Redux?
@NguyenTuan-pu7ye
@NguyenTuan-pu7ye 10 ай бұрын
this is amazing content sir, it helps me a lot. But i have a question when i send a login request to server, i will receive the response object containing accestoken and refreshtoken so where i store the refreshtoken and in baseQueryWithReauth, how can i pass refresh token argument in order to send it to server that will create new token again. Thank you.
@kirillzlobin7135
@kirillzlobin7135 Ай бұрын
1:22 Congratulations on being recognized by the Redux official team!!! This is amazingly cool
@DaveGrayTeachesCode
@DaveGrayTeachesCode Ай бұрын
Thanks!
@narekdanielyan8810
@narekdanielyan8810 8 ай бұрын
Hi Dave, thanks for this great tutorial. Ihave one queation, what if we are logged in and reloading oage, how to trigger refreshtoken ?
@therevenant9296
@therevenant9296 4 ай бұрын
Great tutorial! Thanks dave! There is just one thing revolving in my mind, as I save my refresh token in cookies, it logs me out. The refresh token is already in my cookie. How do I persist the login even when the reload happens?
@altered.thought
@altered.thought Жыл бұрын
I'm refreshing on my MERN stack and this content is premium. 💯
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Great to hear!
@VladyslavChapiuk
@VladyslavChapiuk 6 ай бұрын
Hello and thank you for the nice example. I even did the page refresh with it. The only issue I have is it detects that user was hacked if I have two separate queries at a time. So one of the query uses the new refresh token and runs successfully. But another one tries to get refresh token and does not find the user anymore. I think it is race conditions or something. Can you help with that?
@yurabobrov6717
@yurabobrov6717 Жыл бұрын
Top content! Highly recommended for everyone who wants to familiarize with RTK query.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Thank you, Yura! 🙏💯
@regilearn2138
@regilearn2138 2 жыл бұрын
Hi Dave really appreciate this. And would like to suggest add email and SMS verification part also,
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thank you for the request!
@vitaliibudkin8210
@vitaliibudkin8210 Жыл бұрын
Hi, Dave! Could you please tell me what's the best solution if I need to save two user accounts in my App and I need to quickly switch between this two accounts? I use JWT Access with refresh tokens and cookies now. Is there any way to save two different cookies for more that one user on the same PC?
@ghassanclassic7689
@ghassanclassic7689 Жыл бұрын
Great tutorial Dave 🎉 Thank you very much 🙏
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
You're welcome!
@okonkwo.ify18
@okonkwo.ify18 2 жыл бұрын
And that’s y I always recommend your channel to people
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thank you, Ifeanyi! 🙏
@LoFiRadio-tp5tj
@LoFiRadio-tp5tj 8 ай бұрын
Thanx Dave! But you don't throw any refresh token to the server. Can you explaun how I can call base query with the new token, not just with the new url? Please, I'm struggling a few ours because I can throw any props to the base query! Thanx man, you doing a great job!
@dharmeshgohil9375
@dharmeshgohil9375 2 жыл бұрын
Waited for this video, awesome👌👌👌
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thank you, Dharmesh! Many requests for this login auth flow with Redux! 🚀
@MohamedIbrahim-ig1dk
@MohamedIbrahim-ig1dk 2 жыл бұрын
Hi Dave, your work is really great for showing every single option available, and it is best material I saw for learning react! Quick question though, would you able to do a video about Persistent login with redux rtk query, as the other one in the series was built over axios and I am confused how to do it on top of this example here. Thanks in advance :)
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thanks for the kind words and request! Once you apply what is in this tutorial, not much else changes. Your persistent login approach should essentially remain the same as what I covered here: kzfaq.info/get/bejne/aJ17mLyckpvaeqs.html
@andreaso.1549
@andreaso.1549 Жыл бұрын
Hi Mohamed, I was gonna ask the same question. However, Dave's reply made me stubborn. I now have persistent login with refresh/access tokens using RTK in my app. I wrote a short article about it on LinkedIn: bit.ly/3Cbl1kV In the article there is also a link to the gist with the code. Feel free to ask any questions.
@kikodzn1851
@kikodzn1851 Жыл бұрын
At login page you should also use a ref for username and password once they are required only in the submit
@kirillzlobin7135
@kirillzlobin7135 4 ай бұрын
17:35 - Theoretically we could specify endpoints in our apiSlice, correct? So in this line: export const authApiSlice = apiSlice.injectEndpoints({... we kind of inherit the settings from specified in apiSlice, correct?
@vishwasmakwana125
@vishwasmakwana125 Жыл бұрын
Hi Dave , Your content is awesome , I just want to know one thing for backend in this tutorial are you providing any starter code ? That I can use it directly and follow along to focus on UI side
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
There is source code provided for this tutorial in a Github link in the description. I can't remember if there is "starter code" or just completed code. Likewise, the Node.js backend REST API code is also provided at the link for the Node.js course in the description.
@gracemakena2078
@gracemakena2078 8 ай бұрын
i'm using flask and i have followed your steps....but my tokens are null waht should i do?
@celestialmage7739
@celestialmage7739 Жыл бұрын
Thank you so much for this Dave :)
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
You're welcome!
@diasaijanov8675
@diasaijanov8675 11 ай бұрын
hey Dave. What is preflight request? Do you have video explanation?
@azuma12
@azuma12 2 ай бұрын
So I am trying to just register and login user and I wanna keep my user logged in so like where from I start? Like in series
@user-gn1jl9sg8h
@user-gn1jl9sg8h 2 ай бұрын
I HAVE A QUESTION HELP HELP !!!! const useRefreshToken = () => { const { setAuth } = useAuth(); const refresh = async () => { const response = await axios.get('/refresh', { withCredentials: true }); setAuth(prev => { console.log(JSON.stringify(prev)); console.log(response.data.accessToken); return { ...prev, accessToken: response.data.accessToken } }); return response.data.accessToken; } return refresh; }; We have a function refresh, where we get a new accessToken, but how ? How does the server know which user is requesting a new token, because we do not indicate any additional parameters anywhere. We will receive a random number for any request "/refresh"
@jefcodejp5364
@jefcodejp5364 9 ай бұрын
Hi Dave. Can you show how this flow is acheived with react query?
@famfy
@famfy Жыл бұрын
Dave you are one my favourite teachers! Great job on very important topics! Thank you! Do you think creating tutorial for Nextjs probably again with Authorization and Authentification?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Thank you! Yes, Next.js is on my list to cover right after Typescript!
@user-jq6ng3rb4c
@user-jq6ng3rb4c 2 ай бұрын
where does refresh token come from inside of baseQueryWithReauth?
@nepalrameshwor1540
@nepalrameshwor1540 9 ай бұрын
user's token gets reset or lost after refresh the page when using redux store. So, what is the best way to store token and other information of user so that after refresh no data is lost or reset?
@ER-oj8mo
@ER-oj8mo 2 жыл бұрын
Hey Dave! Thanks for the video, I just built the same thing except using Axios interceptors, might give this a shot. I would love if you could take a look at a video detailing how to persist jwt token authentication over a refresh / separate tabs? Thanks again for the video!
@BaseQuatroB4
@BaseQuatroB4 2 жыл бұрын
This is useless without persisting the token safely.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Hi ER - glad to hear it - did you build your Axios version with my tutorial mentioned in the pre-requisites at the beginning of this video? ( kzfaq.info/get/bejne/pK9og7yLs6zYkZc.html ) ...you might notice one video in that series applies login persistence with JWTs. The same strategy could be applied here. Link: kzfaq.info/get/bejne/aJ17mLyckpvaeqs.html
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
@BaseQuatro that is harsh and unwarranted. In addition, the prerequisites I mentioned at the beginning of this video include a dedicated tutorial with the login persistence strategy: kzfaq.info/get/bejne/aJ17mLyckpvaeqs.html
@ER-oj8mo
@ER-oj8mo 2 жыл бұрын
@@DaveGrayTeachesCode I didn’t see it, thanks so much, I’ll absolutely watch it!
@ER-oj8mo
@ER-oj8mo 2 жыл бұрын
@@DaveGrayTeachesCode well - now i've done three different methods. Been a nervous wreck about authentication / removing friction from my users experience. RTK (this method) is definitely what I'm settling on.
@user-ym8qt7sr8x
@user-ym8qt7sr8x Жыл бұрын
Nice video Dave, thank you!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Very welcome!
@lailabouziani7704
@lailabouziani7704 6 ай бұрын
Thank you, great tutoriel ;)
@afdhaliapreto7703
@afdhaliapreto7703 7 ай бұрын
if you deeply understanding of redux toolkit query, it is more simple than using axios interceptors. otherwise we have fetch data API and state management all in one on RTKQ
@user-cz9zm2us1y
@user-cz9zm2us1y 11 ай бұрын
Hello, I have been following your tutorial series, and everything is going well so far. Thank you very much for sharing your knowledge. I have a question about this tutorial: you used Axios for the requests but now Redux for the rest of the project. Does that mean it's better to use Redux instead of Axios for the requests in the remaining parts of the project?
@dev-suresh
@dev-suresh 3 ай бұрын
For those wondering the same thing: RTK is built on the top of fetch request, just like axios. They both do the same thing - "fetch requests made easy". Here we are using RTK because when we have already used RTK for state management then why not create the complete auth process using RTK itself instead of relying on other dependencies. This is one reason why using RTK is the preferred approach here. Anyways, if you want to use AXIOS for requests you can do that but then you should stick with redux for state management only. Hope this helped.
@SuperCodepk
@SuperCodepk Жыл бұрын
You are doing great man 👏. Your content is helping me alot
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Glad to hear it!
@AbuTaher-vx2oe
@AbuTaher-vx2oe 6 ай бұрын
my question is not auth purpose. actually. im using wavesurfer for audio visualization on vite reactjs. before move another route need to wavesurfer destroy. but if i use return on useEffect it is not working. if destroy function use button onClick then it is working. but my main issue when user click on browser back/left arrow/button or browser forward/right arrow/button still need to destroy
@nitishchoudhary5285
@nitishchoudhary5285 5 ай бұрын
how to achive the same in typescript the apiSlice very bottom part
@thedigitalgurutech
@thedigitalgurutech Жыл бұрын
Do you have any tutorials using Strapi with React? Would love to see this redux/toolkit with Strapi if you're up for making that tutorial. Specifically, wanting to do include with Ecommerce/Strapi/Stripe tutorial I've built and been customizing. You're videos are phenomenal though - wish I would have discovered you months ago!!!
@wilsonibekason
@wilsonibekason 3 ай бұрын
Is there persistence in this one like in the react version
@AhmadSukkar
@AhmadSukkar Жыл бұрын
Really, thanks a lot for these videos 🙌
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
You're welcome!
@stephaneadjakotan750
@stephaneadjakotan750 Жыл бұрын
absolutely the best authentication course of all that I have seen on youtube, there is nothing to argue about. 🤔I have a small question since we did the login with an HTTP Post, wouldn't it be relevant to use the HTTP Post for the refresh-token?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
The refresh token is in a cookie which is automatically sent with every request as long as withCredentials is set to true. Javascript doesn't really touch it and the request type should not matter.
@santoshkumarmarar7048
@santoshkumarmarar7048 3 ай бұрын
Hello, then you for tutorials. When i am using this in real world with nextjs with rtk query i am getting problem i.e. what is user refresh redux state then token become null then how it set headers and do further work. can you please explain me.
@jamesnelson174
@jamesnelson174 Жыл бұрын
Hi Dave, great tutorials, and i appreciate your effort towards our growth. Quick one, How do I get Axios interceptors to work with the Rtk query with token
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
That's what this tutorial really does, but without axios. However, the docs do show how to add axios to your baseQuery if you want to use it: redux-toolkit.js.org/rtk-query/usage/customizing-queries#axios-basequery
@by6321
@by6321 Жыл бұрын
Dave you are lifesaver! God bless you man.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Glad I could help!
@by6321
@by6321 Жыл бұрын
@@DaveGrayTeachesCode I would like to use backend as PHP, I hope it will work for me.
@juneroyd.quinimon495
@juneroyd.quinimon495 2 жыл бұрын
Thanks for this sir Dave :)
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
You're welcome, Juneroy! 💯
@AfifAlfiano
@AfifAlfiano Жыл бұрын
Awesome, thank you dave
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Very welcome!
@ghkpr
@ghkpr Жыл бұрын
Thanks, great tutorial! createApi just blew my mind
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Thank you!
@root3044
@root3044 2 жыл бұрын
Thank you for your quality content! I would like to know if the manipulation of this project could be done without too much difference by making a back-end in Ruby On Rails? Take care of yourself !
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Great question! RonR is something I do not have experience with. The logical flow of the JWT auth should stay the same, so this frontend code should not change much if at all.
@jimkarakaxas9909
@jimkarakaxas9909 Жыл бұрын
Hey Dave! Thanks for your really great content. Always learning so many new topics from your videos. I would like to ask you one question regarding the request that you are refresing your access token. So where do you enter the refresh token in the request? Because now in the request we are just configuring the new url which is "/refresh" and passing also the 'api', and the 'extraOptions', but where do you specify the refresh token for the request?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
The refresh token is in an httpOnly secure cookie. The cookie is sent with the request, but you cannot access the token with JavaScript on the frontend. That's what makes it more secure 😀
@jimkarakaxas9909
@jimkarakaxas9909 Жыл бұрын
@@DaveGrayTeachesCode Thank you so much for your answer! Now everything is crystal clear:)
@MrSaydo17
@MrSaydo17 2 жыл бұрын
Thanks for the video! You mentioned not using map for lists. Can you expand on that?
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Sorry if that wasn't clear. Nothing wrong with map. I mentioned using the map iterator as the item key. With larger lists it is known to cause a problem, but even if I give an example with 3 items, I am guaranteed to get a comment saying I shouldn't use it. With a larger list, use a package like uuid to generate the list item keys.
@wbielicz
@wbielicz Жыл бұрын
Great tutorial Dave! Really helped me understand this difficult topic. However, why does my redux state only update whenever I log out and back in even tho the fetchBaseQuery function successfully called the api the second time and updated my mongodb while logged but, my redux state behind the scenes?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
That's difficult for me to say without knowing how you set up your Redux or RTK Query. This tutorial just goes over the auth part.
@marcel5235
@marcel5235 7 ай бұрын
would you make video about react-query / swr and http only cookie refresh jwt? I think that this could be in React the most common usage ( if you dont use next or redux ), Btw: thanks for this video - it makes me think about secure app more and gives me some ideas
@adityojuliantriwm8442
@adityojuliantriwm8442 Жыл бұрын
Hello, Dave! I feel really grateful for finding your content cause it always helps me learn right when I need it. Thank you for your incredible and helpful content! I got a quick question regarding the redux slice and it would be very appreciated if you could provide me with inspiration. I'm working on my project and I've implemented all of my redux slice functions (except for refresh JWT functionality) using the asyncThunk method (calling corresponding service functions and reaching the API endpoint using Axios). I've been wondering if I could implement baseQuery and inject all of my implemented slice functions as you've done in the video. Thanks in advance! :)
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
You're welcome! And yes, you can integrate Axios and baseQuery. Here is the docs link showing how: redux-toolkit.js.org/rtk-query/usage/customizing-queries#axios-basequery
@adityojuliantriwm8442
@adityojuliantriwm8442 Жыл бұрын
@@DaveGrayTeachesCode Thank you so much for your help in guiding me to the right steps. Another question if you'd let me, is it safe to put the handleRefreshToken function on the nodejs as one of the middleware before reaching the final endpoint function? Thank you!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
@@adityojuliantriwm8442 you could, but it seems like the controller is where you would handle this functionality.
@sergeyplotnikov5031
@sergeyplotnikov5031 Жыл бұрын
Thank you very much Dave!!!!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
You're welcome, Sergey!
@nolanroth6246
@nolanroth6246 Жыл бұрын
Hi Dave! I ran into a CORS issue, which I mitigated by removing "credentials: "includes" from fetchBaseQuery, as was suggested by another comment. This solved my CORS issue with "/auth" at login, but now "/refresh" fails as the cookie is not being sent. Do I need to find a way to dynamically include the credentials for all routes except "/auth"?
@nolanroth6246
@nolanroth6246 Жыл бұрын
I figured out the issue, the cookie was not being stored in the browser, which must have been caused by not setting "secure: true" for res.cookie on the backend. Adding this fixed the issue.
@stickshift583
@stickshift583 Жыл бұрын
Hi dave, setting credentials: 'include' in the apiSlice gives me Cors error although I configure the cors options same as yours. If I delete this credentials line I can login successfully. And although I see my token in welcome page, I am getting null with getState().auth.token . Thanks for the content!
@dadaabiola2474
@dadaabiola2474 2 жыл бұрын
The Security Guy! 🤗
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thank you 💯 but I'm no security expert.. maybe good at building login auth flow. 🙏
@lioraviv2359
@lioraviv2359 Жыл бұрын
Hey Dave, thanks for the tutorial! In the end of the video when you tested things out you got sent back to the login page after the token timed out, shouldn't the program request a new token then send the request with the new token instead like you showed at the start of the tutorial?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
I think I remember also showing where you can use the refresh token to get a new access token, too? However, what you are describing is when the refresh token has expired - and you need to let it expire at some point. When that happens, you will not be issued a new access token and instead, you will be logged out.
@faheemhaider211
@faheemhaider211 Жыл бұрын
Thanks a lot for another great learning video. One query, Can we integrate thunk in the above example?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
You're welcome! Of course! There is usually more than one way to achieve the same thing. The docs have some good examples of using axios, too.
@ABUTAHER-wg7gz
@ABUTAHER-wg7gz Жыл бұрын
hello could you help me to inform about kid of jwks-rsa
@tongtony3880
@tongtony3880 Жыл бұрын
Will FetchBaseQuery not get token in apiSlice.js when i login in the login page? FetchBaseQuery getState() will get backend program cookie? Thank you very much
@ankitkumarjat9886
@ankitkumarjat9886 2 жыл бұрын
Thanks for such a great video. I have one question How we can use axios with rtk query? I need it for upload progress during file uploaded.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Yes, you can 💯 Here is a link to the docs on this: redux-toolkit.js.org/rtk-query/usage/customizing-queries#axios-basequery
@majdiswais
@majdiswais 6 ай бұрын
This is really very informative, thanks Dave! Quick questions, for the purpose of storing the authentication information (access token) do you prefer Redux or Context API?
@DaveGrayTeachesCode
@DaveGrayTeachesCode 6 ай бұрын
I always keep things as simple as possible. I prefer Context unless state gets so complicated I need something like Redux.
@dmytroostretsov6367
@dmytroostretsov6367 2 жыл бұрын
Hi Dave, I saw your awesome video about React Redux Login Authentication Flow with JWT Access. I really appreciate it, Thank you! Now I try to understand react, so could you please tell me a few words about how you get previous route info from the 'navigate state'? I mean this part of your code: So how do you read 'from' and 'location' in the login component? Thanks a lot.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
You can look back to the login component code to see how I'm looking for that. Near the top of the component where const from = ... Also, it is a bit of a dive into the React Router v6 docs, but start here: reactrouter.com/docs/en/v6/hooks/use-navigate
@ekay
@ekay Жыл бұрын
Very good and clear tutorial even for me as a beginner. I was just wondering is the approach to using the persistent login feature with redux is the same as in the previous tutorial?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Same approach / concept, but it does require some changes (not identical code). I will be doing this in my current MERN Stack series so you can see the exact code I use: kzfaq.info/sun/PL0Zuz27SZ-6P4dQUsoDatjEGpmBpcOW8V ...this series is not complete yet, but auth will be covered in it.
@ekay
@ekay Жыл бұрын
@@DaveGrayTeachesCode I didn't know about the playlist. I will try it, thanks!
@jardelduarte7987
@jardelduarte7987 2 жыл бұрын
great job, i init a project with a redux and before include redux-persist... my pages dont reset skills in reducers, u have a tutorial of the redux auth with a persist? And again, congrats!
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thank you, Jardel. After looking at redux-persist (www.npmjs.com/package/redux-persist) it looks like it would work, but be careful to not store the JWT with it as it uses localStorage, files, or non-httpOnly cookies. A process you might consider is shared here: kzfaq.info/get/bejne/aJ17mLyckpvaeqs.html ..it only requires a username in localStorage and a previously received secure httpOnly cookie with refresh token. This video is from my React login series listed in the prerequisites for this video near the beginning.
@davithchhung7577
@davithchhung7577 2 жыл бұрын
Thanks you for the video!
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
You're welcome, Davith!
@tahirdibirov1430
@tahirdibirov1430 Жыл бұрын
Did you use FSD Architecture here?
@gerardolongobardi3055
@gerardolongobardi3055 Жыл бұрын
Hi Dave. This is a great tutorial. Thanks!! I have a question. Once you save the accessToken in redux state, despite it gets expired, the expired token stays saved in that state and the RequireAuth component will still get that the access token exists, that token from selector is true. How can you delete with logout the accesstoken when it gets expired???
@yubrajkhatri3519
@yubrajkhatri3519 2 ай бұрын
Exactly i a came with same problem
@smokencode
@smokencode Жыл бұрын
Thanks Dave, your videos helped me a lot, specially when I start working with Redux, but help me until today! I have one question about the authentication process. If I reload the page, I loose the credentials and back to the login page, is supposed to be like this according the videos instructions, I missed something, or I need to implement some extra configuration to hold the tokens in the browser? Thanks Again and Best Regards !
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Your backend code needs to send you an httpOnly secure cookie with a refresh token in it. JavaScript cannot see that httpOnly cookie, but your baseQuery should be sending it if you have enabled credentials in the query options. You can see this in my source code from the link in the description. If you are not familiar with the cookie I'm talking about, my React auth series will help you - and you are asking about the Persist Login strategy: kzfaq.info/sun/PL0Zuz27SZ-6PRCpm9clX0WiBEMB70FWwd
@lagorra5000
@lagorra5000 2 жыл бұрын
I never been so lost tbh, nothing wrong with the tutorial off course. just realizing how much lack of knowledge I have! I need to step up, damn!
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
A little progress every day!
@lagorra5000
@lagorra5000 2 жыл бұрын
@@DaveGrayTeachesCode Thank you for these amazing tutorials Dave! I wanted to ask you, could you do a tutorial like this but with the aws-sdk for user authentication?
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
@@lagorra5000 thanks for the request! I could do an AWS tutorial, but it would be far different from this. AWS has a different process.
@nanonkay5669
@nanonkay5669 2 жыл бұрын
Question: Why do we need to keep the access token in application state i.e. auth slice instead of just just keeping it in the API cache after the login request?
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
If you can make it work with the cache only, there's nothing wrong with that. That would essentially be like using RTK Query only. Global state may be useful if you need to reference the token to pull any other data from it that it may contain.
@mariacamilamontealegremerc5892
@mariacamilamontealegremerc5892 Жыл бұрын
Hi dave, thanks for the video, I think is really good. By the way, I think that youd didn't say what the credentials are to login and be able to see the user list on the UI . Could you please help me out with this question? Thank you very much!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
You need to create your own users and passwords for them. If you have created your own backend with Node.js, you will also have your own MongoDB account for your database. I show how to do all of that in my Node.js course here: kzfaq.info/get/bejne/nJh1pKh0zrqmfGw.html
@tharindux
@tharindux 3 ай бұрын
I'm stuck at authorization header. redux is not setting the header. How can i solve this. Is there anyone who had the same issue?
@muhammadosama6261
@muhammadosama6261 Жыл бұрын
@DaveGrayTeachesCode how to send POST request with body for refresh accessToken using baseQueryWithReauth ?
@IkonYTB
@IkonYTB 4 ай бұрын
const refreshResult = await baseQuery({ url: "/refresh", method: 'POST', body: JSON.stringify({ /* your data here */ })}, api, extraOptions); I think this does the job.
@marioperez1501
@marioperez1501 Жыл бұрын
Hey Dave! I've a question related to the refresh token and checking if the session is expired: I need to make the login persistent, so I need to check if there's a present refresh cookie just to obtain a new access token and grant the user the corresponding access. How can I do it?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Hi Mario - I have a separate video in this React Login series about persistent login which covers the strategy for using the cookie to remain logged in. Specifically for Redux & RTK Query, I'll be covering the implementation of this persistent login very soon in my new MERN Stack Project series: kzfaq.info/sun/PL0Zuz27SZ-6P4dQUsoDatjEGpmBpcOW8V
@20090abc
@20090abc Жыл бұрын
Hi Dave, I am beginner to rtk query and for example I have an endpoint GET TODOs. if I want to get filtered todos which are not done yet, I send query params to server and from there I get filtered data but my components still shows Cached data of all TODOs.how can I invalidate cache and only show todos which are returned from server. can you help me with that. or probably could you make a video where you show server side filtering and searching with rtk query. Thanks in advance.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Good questions - You should give this entire query a cache key like "LIST" or something similar and then invalidate that cache when you send a new query. That will remove what you had previously. If your backend provides filtered results when you send query parameters, great! Otherwise, you will need to receive the full list and filter it in the frontend code.
@daheepark2065
@daheepark2065 Жыл бұрын
Hello from Korea! Thanks for sharing great tutorials! It gave me a lot of help to understand Redux Toolkit and RTK query and your authentication tutorials helped me implementing authentication flow using React. After watching your tutorials, I have one question. At 28:48 in this video, you are using try-catch block with unwrap method. Is there any difference between using try-catch block with unwrap method and using isError and error property like using isLoading when handling errors?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Great question! It is personal preference and what works best for you in the situation you are in. I usually use the isLoading, isError, and similar values from a hook, but sometimes - such as in a login form - I prefer the unwrap() with try / catch.
@daheepark2065
@daheepark2065 Жыл бұрын
@@DaveGrayTeachesCode Thank you for your quick reply! Have a nice day!
@AdityaDey424
@AdityaDey424 Жыл бұрын
19:32 what does production mean ? Or why do we even add 'devTools' in store.js ?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Your environment = Production or Development. You need to learn about how React uses this. devTools = Redux has its own devTools. This is covered in my Redux course.
RTK Query или альтернативный Redux по работе с API
31:55
Михаил Непомнящий
Рет қаралды 96 М.
孩子多的烦恼?#火影忍者 #家庭 #佐助
00:31
火影忍者一家
Рет қаралды 52 МЛН
Playing hide and seek with my dog 🐶
00:25
Zach King
Рет қаралды 30 МЛН
Best Practices for React Data Security, Logins, Passwords, JWTs
21:10
React Persistent User Login Authentication with JWT Tokens
37:27
Redux Toolkit Authentication: The Ultimate Guide for Beginners
22:28
Monsterlessons Academy
Рет қаралды 3,6 М.
MERN Crash Course | JWT Authentication, Redux Toolkit, Deployment & More
3:38:00
孩子多的烦恼?#火影忍者 #家庭 #佐助
00:31
火影忍者一家
Рет қаралды 52 МЛН