react, cookie, storage, font end,


DolorHunter DolorHunter Follow May 02, 2021 · 2 mins read

Share this


根据查找到的资料,能够存储此资料有三个地方:Cookies,SessionStorage 和 LocalStorage。其中最常存储数据的位置是Cookies,例如GitHub在Cookies中存储了用户名,Twitter存储了用户ID。

虽然我用的是React,但是在依赖上还是选择了 js-cookie/js-cookie 而不是 react-cookie,因为看起来更加的简洁。当然,cookie也不止这两个包,但是应该都是互相封装的(猜测原因是昨天每个cookie包都用不了,只能用document.cookie写,今天突然又能用了)。



js-cookie/js-cookie 文档中的基础示例:

import cookie from 'js-cookie';

cookie.set('foo', 'bar');

cookie.set('name', 'value', { expires: 7, path: '' });

cookie.get('name'); // => 'value'


cookie.remove('name', { path: '', domain: '' });

cookie 主要就三种用法,set/get/remove。其中,option内的参数有:

Expires date
Max-Age non-zero-digit
Domain domain-value
Path path-value
Secure true/false
HttpOnly true/false
SameSite Strict/Lax/None

其实我刚一开始用的是 LocalStorage 做uuid和username存储,跟(调用依赖下的)cookie使用上来说差不多,方法为 getItem/setItem/removeItem。但是爬帖子发现混用存储不太好,就改成了cookie,甚至把登录标记的id_token也从localStoage改成了cookie。

Cookies,SessionStorage 和 LocalStorage异同

Cookies and local storage serve different purposes. Cookies are primarily for reading server-side, local storage can only be read by the client-side. So the question is, in your app, who needs this data — the client or the server?

If it’s your client (your JavaScript), then by all means switch. You’re wasting bandwidth by sending all the data in each HTTP header.

If it’s your server, local storage isn’t so useful because you’d have to forward the data along somehow (with Ajax or hidden form fields or something). This might be okay if the server only needs a small subset of the total data for each request.

You’ll want to leave your session cookie as a cookie either way though.

As per the technical difference, and also my understanding:

  1. Apart from being an old way of saving data, Cookies give you a limit of 4096 bytes (4095, actually) — it’s per cookie. Local Storage is as big as 5MB per domain — SO Question also mentions it.

  2. localStorage is an implementation of the Storage Interface. It stores data with no expiration date, and gets cleared only through JavaScript, or clearing the Browser Cache / Locally Stored Data — unlike cookie expiry.

-StackOverflow - Local Storage vs Cookies

  • LocalStorage就是客户端本地的存储,只能由客户端利用js读取。
  • SessionStorage相对LocalStorage,在不同页面中数据不互通,关闭网页会话后自动清除。
  • Cookies主要用于在通信中携带信息,可能用于服务器的安全验证。但是会增加流量,并且是明文传输。



Join Newsletter
Get the latest news right in your inbox. We never spam!
Written by DolorHunter
Developer & Independenet Blogger