I'm looking to persist all cookies in localStorage. When the page is loaded the cookies should be inflated from the data in localStorage. Whenever they change, or possibly just on page close, localStorage should be updated with the cookie data.
I'm in an environment where cookies do not persist between restarts and you're expected to use localStorage. The problem is that the server framework I'm using sets all the cookies independently of my code.
Thanks for any help navigating this -- I don't know my way around cookie behavior that well.
The localStorage API operates on a simple set/get/clear set of methods that allow you to interact with a key-value store. To store all the cookies for the current page under the key "cookies" you could write:
localStorage.setItem("cookies", document.cookie);
and later recover them by:
document.cookie = localStorage.getItem("cookies");
Related
Is there any rule regarding when to use local storage or not to store state information if I have redux?
For example if I have some online form, then
Q1. should I have its state (currently filled values) persisted to localstorage say when user closes tab or browser, so that I can reload the state in redux from localstorage when user revisits the webpage? Is there any well know / documented security consideration for storing redux state in local storage?
Q2. Or should I always send last saved redux state from the server (and not save and load from localstorage) when user visits the website first time after opening the browser. If that is the case
Q3. If the answer to Q2 is YES, then what about JWT? Should we store JWT in localstorage avoiding forcing user to re-login?
Q1
In terms of OAuth Best Current Practice I would avoid storing anything like this in local storage:
Credit card numbers
Passwords
Access tokens
Personally identifiable information, eg name, email
Use browser storage for simple data such as the application path before an OAuth redirect, or simple boolean preferences. Prefer session storage over local storage, unless you need settings across multiple browser tabs.
Q2
Using the server is safest for anything sensitive, so it is worth investing in an API driven save and load option.
Q3
Avoid JWTs in local storage, since there are more attack vectors that could result in stolen data. If you are migrating from this model then start by storing a refresh token in an encrypted HTTP Only SameSite=strict cookie, and store access tokens only in memory.
This will enable you to avoid logins on page reloads or when the user opens a new browser tab, and is easy to implement by routing token requests via a utility API. You could then go further to take access tokens out of the browser completely. See the SPA Best Practices article for further related details.
It depends.
Q1. If it's non-updating data and you don't need to make request to backend for it. You can use localstorage.
Security Issue with localstorage is that user can access it and alter or delete the data. In that case you again need to hit your api for data.
Q2. If the data is updating (eg - posts,likes in blog app). Then you need to make a request to server to fetch the latest data.
Q3. Yes, mostly jwt is stored in localStorage which avoid user to re-login. If the user try to alter the jwt, the backend has methods to check it. read How jwt works
I am new to Express JS and frontend. I am developing an app which is using req.session for maintaining the user session and local storage for storing some other temporary info.
I have seen various articles for differences between the above but I am still unclear which is used when and how long does each persists.
According to me:
1.req.session: The server maintains this session. This gets cleared when user clears cookies.
2.cookies: Cookies are sent to server to maintain authentication
3.local storage: This persists till user deletes the cookies?
session storage: This is maintained by browser and persists for one tab.
All are different type of storage mechanisms commonly use in web application development.
But The matter is choosing the correct one.
In Short
Cookie Storage
Cookie is a browser storage mechanism, But can access from server-side through request. Developers use cookies to store data which should be accessible from server and client.
Example: Authentication Tokens, Analytical Data
Session
Session storage is a server-side storage mechanism which can be only accessed by server. So we cannot access from browser directly. Use sessions to store confidential information.
Data in session will be destroyed when the session is closed.
Local Storage
Local Storage is like Cookie BUT we cannot access from server, we can store much more data than cookies and it doesn't expire unless we clear.
Cookies - 4 KB &
Local Storage - 5 MB
Session Storage
Session Storage is similar to Local Storage. But the only difference is, Local Storage doesn't expire But Session storage will be destroyed when page session ends. Session storage keeps different session per page (tabs)
I'll go through each of your points and discuss them...
1) req.session: The server maintains this session. This gets cleared when user clears cookies.
If you're keeping this in a persistent store (disk-backed data store), you can keep this state for as long as you want. The server will lose track of the client that it corresponds to when the user clears their cookies. Depending upon how you manage your persistent user storage, you may be able to rebuild a previous session object when the user logs back in again (allowing you to use their userid to find their lasting state in your database, create a new session cookie, build a new session object from that and reconnect that browser with a new session object).
2) cookies: Cookies are sent to server to maintain authentication
That's an over simplification of the utility of cookies. Cookies allow a server to set some state in the user's browser that will be presented back to the server with each request from that specific browser. Cookies are often used for keeping track of an authenticated client and often used for keeping a key to a server-side session object. There are thousands of other things cookies can be used for too (user site preferences, tracking ids, other user state, etc...).
3) local storage: This persists till user deletes the cookies?
Browser local storage has no connection at all with cookies. It is a separate local data store in the browser that is accessible only to client-side Javascript in a web page. Deleting cookies has nothing to do with deleting local storage. They are separate items that can be separately retained or deleted. The server has no access at all to local storage. In addition, local storage is segmented so that the local storage values form one web site cannot be accessed by Javascript in pages from another site.
4) session storage: This is maintained by browser and persists for one tab.
It's not quite clear what you mean by "session storage". There are "session cookies" which are purposely designated upon creation to only persist while a given browser is running. If the browser exists and then some time later is restarted, any session cookies will be gone. Their purpose is generally for short term cookies, not meant to persist beyond what the user is currently doing.
One other possible thing you might have meant by session storage is long term, persistent storage on the server (typically in a database on disk) for various user properties or state that you want to last a long time. Imagine the user populates a shopping cart and you want them to be able to keep that shopping cart indefinitely as they move from device to device and as they add/remove things from it over a significant amount of time. For these types of things, you won't typically rely on a session object to keep track of these, but will use a database as the main source of that data. It's possible some subset of data currently being worked on might be cached in a server-side session object, but that would only be for expediency, not as the long term storage for it.
Or perhaps you meant Window.sessionStorage in the browser. That works like localStorage, but only persists for the duration of the browser being open (similar lifetime to session cookies) and unlike localStorage, each tab or window has its own sessionStorage. Like localStorage, each origin has its own sessionStorage some a page from one origin can't access the sessionStorage for a page from a different origin, even if they were both loaded into the same window/tab.
In order to help you more specifically with your application, we would have to understand each piece of state you wanted to keep track of and what it was used for. Only then could we suggest what mechanism might be best for storing it.
req.session
When a user visits the site, it creates a new session object for the user and assigns them a cookie.
Whenever the user request from the same client again, the cookie is checked, sent to the server for processing and the session information stored is updated.
The difference between Cookies, Local Storage(LS) and Session Storage(SS) is as follows.
Cookies is processed server side, while LS and SS data is never sent to server. They are stored locally.
Storage capacity of a Cookie is max 4 KB, while for LS and SS is more than 5 MB.
Cookies mostly store only the session id. While LS and SS can store more information like user information or page browsing history.
SS gets cleared when a user closes tab(session ends). While Cookies can be deleted by clearing cookies and LS can be cleared by deleting Browser cache.
I will update the answer if I remembered anything else.
I have a page which alters the dom based on user interaction. However, the user might click on a link, which will navigate to an external site. If the user clicks the back button, my page is shown again, but the dom changes do not persist.
What is the best way to keep track of the user interactions so I can rebuild the page on their return?
To maintain state and rebuild the page, I need to keep track of 7-10 variables.
Some ideas I had:
server-side session - would require a callback to the server every time a variable changes value?
client-side cookies - what if the user disables cookies?
hidden form fields - most (all?) browsers locally cache form data, so hitting the back button should retain?
In most cases I'd say the best way to do this, is to represent the page state in the URL.
Here's why:
Because a URL is such a simple concept, this method works regardless of what browser or what privacy settings (e.g. allow cookies and local storage) are used.
If User A would send the URL to User B who would like to see the page in the same state, this would still work. This wouldn't be the case for any of your considered methods.
If the variables you want to keep track of are related to a specific user (or session), it would be wiser to track these in some sort of session. This could be both server- or client-side.
Local or session storage (HTML5 Local storage vs. Session storage) are possible solutions, but have some limitations.
Doesn't work in every browser or browser settings (HTML5 local storage isn't supported in older browsers and I know for instance that running Safari in private mode doesn't allow local storage)
If you would send the link to another user he wouldn't see the page in the same state because he hasn't visited the page before, and his local or session storage hasn't been filled with the correct values.
Try the Session variable:
sessionStorage.setItem('key', { "data": "mad data here" });
then to recall it:
var data = sessionStorage.getItem('key');
You could use jQuery as such upon loading the page:
document.load(function() {
var data = sessionStorage.getItem('key');
if (data) {
data.doStuff();
}
}
So we have a web application that is accessed through a link from an email. When the user clicks on the link, we call a web service to pull the necessary data to the client. This data is then stored in the client's localstorage for the span of the user's session and cleared after.
The problem here is that if a user clicks on the link twice and logs out of one of the sessions, the local storage is cleared for both of the sessions.
So I've been thinking about solving this issue and here are my possible solutions:
Reusing the same tab for the external links of the same domain. But its not possible as of now.
Append the session Id to the keys of the localstorage and clear only them at logout. But in this case if someone does not logout properly, the local storage items will still persist and we don't want that.
So I'd like to know if there is any way to keep the local storage session specific or else if I should be skipping localstorage entirely. Thanks!
Use sessionStorage instead of localStorage. sessionStorage is specific to tab and those will be cleared on that tab. But sessionStorage is specific to one session that is from the point window opened to the close of that window.
I am setting a session cookie in one page using
setCookie("cookietime","1000");
And resetting it to "" on going back to previous page
setCookie("cookietime","");
When I go back I am showing an alert after seeting the cookie to "". it is showing "" in alert.
But in the next page it still shows "1000".
Is the cookie page specific
Cookies are stored client side and are computer+browser specific not page specific! I guess you are using document.cookie which should persist through the session - they persist even when the page is refreshed. Using window.name will only persist through the same browser window but will clear on page refresh. HTML5 localStorage may be a suitable alternative.
Relates question: Persist javascript variables across pages?
Session cookies are temporary cookie files that will be removed when you close your browser.
Persistent cookies remain on your browser until it expires or until you erase them.
Neither are page specific.
Note that session cookies in Firefox will be restored after a browser restart when you use the session restore feature, which can cause some inconsistencies.