3๐
If you want to access this information inside your JavaScript code โ then there is no secure way for that, the hacker can simply put a breakpoint in your code and inspect the relevant variables.
If you only need this info in order to maintain a "session" with the server โ then you can use an encrypted session cookie, marked as HttpOnly and SameDomain. The cookie is called "session" because it automatically expires and disappears as soon as you close the browser. And it is encrypted (using a symmetric encryption like AES-256) so that only the server can decrypt it.
The cookie itself does not need to contain the password โ it is enough to contain these 4 pieces of information:
- user ID
- IP address of the browser (to prevent using the same cookie from different locations)
- timestamp of the last change of user data in DB (to invalidate the cookie as soon as the user changes his/her password or other sensitive data in their profile)
- timestamp when the data inside the cookie should expire (to prevent using too old cookies)
Usually the data in the cookie should be considered expired after 20-30 minutes but you may choose to allow the user to set this time as a preference (with a maximum of 60 minutes).
And this cookie should be updated/refreshed with new expiration every time your SPA makes an AJAX request to your backend API.