The Journey of #100DaysOfCode (@Ayman_Dandan)

๐ƒ๐š๐ฒ ๐Ÿ–๐Ÿ” 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.

โ†’ ๐—•๐—ฒ๐—ป๐—ฒ๐—ณ๐—ถ๐˜๐˜€ ๐—ผ๐—ณ ๐—จ๐˜€๐—ถ๐—ป๐—ด ๐—›๐—ง๐—ง๐—ฃ-๐—ข๐—ป๐—น๐˜† ๐—–๐—ผ๐—ผ๐—ธ๐—ถ๐—ฒ๐˜€ ๐—ผ๐—ป ๐˜๐—ต๐—ฒ ๐—™๐—ฟ๐—ผ๐—ป๐˜๐—ฒ๐—ป๐—ฑ

  1. ๐€๐ฎ๐ญ๐จ๐ฆ๐š๐ญ๐ข๐œ ๐Œ๐š๐ง๐š๐ ๐ž๐ฆ๐ž๐ง๐ญ: Cookies are automatically included with every request to your server, so you donโ€™t need to manually add the token to headers.
  2. ๐’๐ž๐œ๐ฎ๐ซ๐ข๐ญ๐ฒ: 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 ๐ฌ๐ž๐œ๐ฎ๐ซ๐ž, ๐ฌ๐ž๐š๐ฆ๐ฅ๐ž๐ฌ๐ฌ ๐š๐ฎ๐ญ๐ก๐ž๐ง๐ญ๐ข๐œ๐š๐ญ๐ข๐จ๐ง!

2 Likes