What is the difference between localStorage, sessionStorage, session and cookies? Ask Question

What is the difference between localStorage, sessionStorage, session and cookies? Ask Question

What are the technical pros and cons of localStorage, sessionStorage, session and cookies, and when would I use one over the other?

ベストアンサー1

This is an extremely broad scope question, and a lot of the pros/cons will be contextual to the situation.

In all cases, these storage mechanisms will be specific to an individual browser on an individual computer/device. Any requirement to store data on an ongoing basis across sessions will need to involve your application server side - most likely using a database, but possibly XML or a text/CSV file.

localStorage, sessionStorage, and cookies are all client storage solutions. Session data is held on the server where it remains under your direct control.

localStorage and sessionStorage

localStorage and sessionStorage are relatively new APIs (meaning, not all legacy browsers will support them) and are near identical (both in APIs and capabilities) with the sole exception of persistence. sessionStorage (as the name suggests) is only available for the duration of the browser session (and is deleted when the tab or window is closed) - it does, however, survive page reloads (source DOM Storage guide - Mozilla Developer Network).

Clearly, if the data you are storing needs to be available on an ongoing basis then localStorage is preferable to sessionStorage - although you should note both can be cleared by the user so you should not rely on the continuing existence of data in either case.

localStorage and sessionStorage are perfect for persisting non-sensitive data needed within client scripts between pages (for example: preferences, scores in games). The data stored in localStorage and sessionStorage can easily be read or changed from within the client/browser so should not be relied upon for storage of sensitive or security-related data within applications.

Cookies

This is also true for cookies, these can be trivially tampered with by the user, and data can also be read from them in plain text - so if you are wanting to store sensitive data then the session is really your only option. If you are not using SSL, cookie information can also be intercepted in transit, especially on an open wifi.

On the positive side cookies can have a degree of protection applied from security risks like Cross-Site Scripting (XSS)/Script injection by setting an HTTP only flag which means modern (supporting) browsers will prevent access to the cookies and values from JavaScript (this will also prevent your own, legitimate, JavaScript from accessing them). This is especially important with authentication cookies, which are used to store a token containing details of the user who is logged on - if you have a copy of that cookie then for all intents and purposes you become that user as far as the web application is concerned, and have the same access to data and functionality the user has.

クッキーは認証目的とユーザー データの永続化のために使用されるため、ページに有効なすべてのクッキーは、同じドメインへのすべてのリクエストに対してブラウザーからサーバーに送信されます。これには、元のページ リクエスト、後続の Ajax リクエスト、すべての画像、スタイルシート、スクリプト、フォントが含まれます。このため、大量の情報を保存するためにクッキーを使用しないでください。ブラウザーによって、クッキーに保存できる情報のサイズに制限が課される場合もあります。通常、クッキーは、認証、セッション、広告追跡用の識別トークンを保存するために使用されます。トークンは通常、それ自体は人間が判読できる情報ではなく、アプリケーションまたはデータベースにリンクされた暗号化された識別子です。

localStorage と sessionStorage と Cookies

機能面では、Cookie、sessionStorage、localStorage では文字列のみを保存できます。設定時にプリミティブ値を暗黙的に変換することは可能ですが (読み取り後にそれらの型として使用するために、これらを変換し直す必要があります)、オブジェクトや配列は変換できません (API を使用して JSON シリアル化して保存することは可能です)。セッション ストレージでは、通常、サーバー サイド言語/フレームワークでサポートされているプリミティブまたはオブジェクトを保存できます。

クライアント側とサーバー側

HTTP はステートレス プロトコルであるため、Web アプリケーションは Web サイトに戻ったときに、以前の訪問からユーザーを識別する方法がありません。セッション データは通常、Cookie トークンを使用して、繰り返しの訪問でユーザーを識別します (まれに URL パラメーターが同じ目的で使用されることもあります)。データには通常、スライド式の有効期限があり (ユーザーが訪問するたびに更新されます)、サーバー/フレームワークに応じて、データはプロセス内 (つまり、Web サーバーがクラッシュしたり再起動したりするとデータが失われる) に保存されるか、外部の状態サーバーまたはデータベースに保存されます。これは、Web ファーム (特定の Web サイトに複数のサーバーがある) を使用する場合にも必要です。

セッション データはアプリケーション (サーバー側) によって完全に制御されるため、本質的に機密性や安全性が求められるあらゆるデータの保存に最適な場所です。

サーバー側データの明らかな欠点は、スケーラビリティです。セッション期間中、各ユーザーにサーバー リソースが必要となり、クライアント側で必要なデータは各リクエストで送信する必要があります。サーバーはユーザーが別のサイトに移動したか、ブラウザーを閉じたかを知る方法がないため、放棄されたセッションによってすべてのサーバー リソースが消費されるのを避けるために、セッション データは一定時間後に期限切れにする必要があります。したがって、セッション データを使用する場合は、特に長いフォームのあるページでは、データが期限切れになって失われる可能性があることに注意する必要があります。ユーザーが Cookie を削除したり、ブラウザー/デバイスを切り替えたりした場合も、データは失われます。

一部の Web フレームワーク/開発者は、セッションの有効期限切れを回避するために、非表示の HTML 入力を使用してフォームの 1 つのページから別のページにデータを保持します。

localStorage、sessionStorage、および Cookie はすべて「同一オリジン」ルールの対象であり、つまりブラウザは、最初に情報を設定したドメイン以外のデータへのアクセスを防止する必要があります。

クライアントストレージテクノロジーの詳細については、以下を参照してください。HTML 5 に飛び込む

おすすめ記事