Pratham Dave
Pratham Dave

Reputation: 133

How to stay logged in after the browser is closed using javascript

I am creating a chat application and I don't know how I retain a user session when the browser is closed.

When the user logs in for the first time, the browser should remember the users' credentials (I am using local storage). But how do I retain the user credentials?

Upvotes: 1

Views: 1634

Answers (3)

Jamie
Jamie

Reputation: 91

You should indeed use cookies like Tim says, but don't just save the username in the cookie. Instead, set a randomly generated token and save that in a database. When you load the site, you get the token and verify with your server who is logged in and whether the token is valid.

While you're at it, also link the token to IP address and user agent, this makes it more secure.

Upvotes: 3

Tim Anthony
Tim Anthony

Reputation: 159

You really should use cookies for example.

With javascript you can set them via

document.cookie = "username=" + username;

for example. (It is more secure to not directly store the username in the cookie, for various security reasons, tho.)

Check this out from W3Schools: https://www.w3schools.com/js/js_cookies.asp

Upvotes: 3

takethefake
takethefake

Reputation: 805

the alternative to cookies is that you could write the session inside the local storage of the browser and initialize the application with the data from the local storage and check if they are still valid.

Upvotes: 0

Related Questions