๐๐๐ฒ ๐๐ of #100DaysOfCode
- ๐จ๐๐๐๐๐๐๐๐ ๐ป๐๐๐๐๐ ๐๐ ๐ฏ๐ป๐ป๐ท-๐ถ๐๐๐ ๐ช๐๐๐๐๐๐ (๐ญ๐๐๐๐๐๐๐ ) -
Now that you know how to generate and store ๐๐๐๐๐ฌ๐ฌ ๐ญ๐จ๐ค๐๐ง๐ฌ ๐๐ง๐ ๐ซ๐๐๐ซ๐๐ฌ๐ก ๐ญ๐จ๐ค๐๐ง๐ฌ using ๐๐๐๐-๐จ๐ง๐ฅ๐ฒ ๐๐จ๐จ๐ค๐ข๐๐ฌ, letโs see how to access and use these tokens on the frontend.
โ ๐๐๐๐ผ๐บ๐ฎ๐๐ถ๐ฐ ๐ง๐ฟ๐ฎ๐ป๐๐บ๐ถ๐๐๐ถ๐ผ๐ป ๐ผ๐ณ ๐๐ผ๐ผ๐ธ๐ถ๐ฒ๐
One of the key advantages of using ๐๐๐๐-๐จ๐ง๐ฅ๐ฒ ๐๐จ๐จ๐ค๐ข๐๐ฌ is that the browser automatically sends them with every request to your backend. You donโt need to manually attach the token to your headers like you would if you were storing the token in localStorage.
In the attached snippet, ๐ฐ๐ข๐ญ๐ก๐๐ซ๐๐๐๐ง๐ญ๐ข๐๐ฅ๐ฌ: ๐ญ๐ซ๐ฎ๐ is crucial here. It ensures that cookies are included with the request.
โ ๐ ๐ฎ๐ธ๐ถ๐ป๐ด ๐ฎ ๐ง๐ผ๐ธ๐ฒ๐ป ๐ฅ๐ฒ๐ณ๐ฟ๐ฒ๐๐ต ๐ฅ๐ฒ๐พ๐๐ฒ๐๐
If the access token expires, your frontend can send a request to the ๐ซ๐๐๐ซ๐๐ฌ๐ก ๐ญ๐จ๐ค๐๐ง ๐๐ง๐๐ฉ๐จ๐ข๐ง๐ญ to get a new access token. Since the refresh token is stored in an HTTP-only cookie, the browser will automatically send it along with the request.
โ ๐๐ฒ๐ป๐ฒ๐ณ๐ถ๐๐ ๐ผ๐ณ ๐จ๐๐ถ๐ป๐ด ๐๐ง๐ง๐ฃ-๐ข๐ป๐น๐ ๐๐ผ๐ผ๐ธ๐ถ๐ฒ๐ ๐ผ๐ป ๐๐ต๐ฒ ๐๐ฟ๐ผ๐ป๐๐ฒ๐ป๐ฑ
- ๐๐ฎ๐ญ๐จ๐ฆ๐๐ญ๐ข๐ ๐๐๐ง๐๐ ๐๐ฆ๐๐ง๐ญ: Cookies are automatically included with every request to your server, so you donโt need to manually add the token to headers.
- ๐๐๐๐ฎ๐ซ๐ข๐ญ๐ฒ: Since the tokens are stored in ๐๐๐๐-๐จ๐ง๐ฅ๐ฒ ๐๐จ๐จ๐ค๐ข๐๐ฌ, they canโt be accessed or modified by client-side JavaScript, making them more secure than tokens stored in
localStorage.
By using ๐๐๐๐-๐จ๐ง๐ฅ๐ฒ ๐๐จ๐จ๐ค๐ข๐๐ฌ for tokens, your frontend can focus on making API requests without worrying about managing tokens manually, while keeping your authentication system more secure.
Now your app is ready to handle ๐ฌ๐๐๐ฎ๐ซ๐, ๐ฌ๐๐๐ฆ๐ฅ๐๐ฌ๐ฌ ๐๐ฎ๐ญ๐ก๐๐ง๐ญ๐ข๐๐๐ญ๐ข๐จ๐ง!
