Nextjs实现Cookie、Localstorage、SessionStorage通用的方法

在使用Nextjs时,针对服务端和客户端实现统一调用本地存储信息,实现维护的统一管理,方便整个项目的维护拓展

js 复制代码
export type StorageType = 'local' | 'session' | 'cookie'

class UniversalStorage {
  private isServer = typeof window === 'undefined'

  /**
   * 设置存储
   * @param type 存储类型
   * @param key 键
   * @param value 值
   * @param days Cookie 特有的过期时间(天)
   */
  set(type: StorageType, key: string, value: any, days: number = 7): void {
    if (this.isServer) return

    const stringValue =typeof value === 'string' ? value : JSON.stringify(value)

    switch (type) {
      case 'local':
        window.localStorage.setItem(key, stringValue)
        break
      case 'session':
        window.sessionStorage.setItem(key, stringValue)
        break
      case 'cookie':
        const expires = new Date(Date.now() + days * 864e5).toUTCString()
        document.cookie = `${key}=${encodeURIComponent(stringValue)}; expires=${expires}; path=/; SameSite=Lax`
        break
    }
  }

  /**
   * 读取存储
   * @param type 存储类型
   * @param key 键
   */
  get<T>(type: StorageType, key: string): T | null {
    if (this.isServer) return null

    let val: string | null = null

    switch (type) {
      case 'local':
        val = window.localStorage.getItem(key)
        break
      case 'session':
        val = window.sessionStorage.getItem(key)
        break
      case 'cookie':
        const match = document.cookie.match(
          new RegExp('(^| )' + key + '=([^;]*)(;|$)'),
        )
        val = match ? decodeURIComponent(match[2]) : null
        break
    }

    try {
      return val ? JSON.parse(val) : null
    } catch (e) {
      return val as unknown as T // 如果不是 JSON 字符串则直接返回
    }
  }

  /**
   * 删除存储
   */
  remove(type: StorageType, key: string): void {
    if (this.isServer) return

    switch (type) {
      case 'local':
        window.localStorage.removeItem(key)
        break
      case 'session':
        window.sessionStorage.removeItem(key)
        break
      case 'cookie':
        document.cookie = `${key}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/`
        break
    }
  }
}

export const storage = new UniversalStorage()

调用方法示例:

js 复制代码
import { storage, StorageType } from './storageutil'

export const TokenStorage = {
  name: 'token',
  get: async function (type: StorageType = 'local') {
    return await storage.get(type, this.name)
  },
  set: function (value: string, type: StorageType = 'local') {
    storage.set(type, this.name, value)
  },
  remove: function (type: StorageType = 'local') {
    storage.remove(type, this.name)
  },
}

通过上面的方法实现调用本地缓存数据方法的统一,也保证了缓存名称的可维护性。避免在每个组件中散落着cookie、localStorage、sessionStorage的读取以及名称的不可控。

相关推荐
FungLeo1 天前
成为全栈·Next.js 网站前台篇·同源 BFF 代理:API、附件、Cookie 与跨站写入保护
react·csrf·next.js·bff·成为全栈·route handler
FungLeo2 天前
成为全栈·Next.js 网站前台篇·评论系统:叠楼、回复、删除与内容审核如何落到前台
react.js·内容审核·next.js·评论系统·树形数据·成为全栈
cindershade4 天前
一条请求的接力赛:用运行时责任重画 RSC 边界
性能优化·next.js
zach5 天前
前端落地实战:Next.js 项目 Nginx + PM2 生产部署全流程(附踩坑总结)
前端·pm2·next.js
zach5 天前
Vue/React SPA 打包部署后,子路由刷新 401 未登录问题彻底解决
前端·nginx·next.js
FungLeo7 天前
成为全栈·Next.js 网站前台篇·数据获取与缓存:60 秒再验证背后到底发生了什么
react·isr·next.js·成为全栈·react cache·opennext
名字还没想好☜15 天前
React 文件上传实战:预览 URL 回收、多文件逐个进度与拖拽放置区踩坑
前端·react·next.js
moMo1 个月前
NestJS 入门:用"模块化 + 装饰器"读懂大型后端框架
next.js
天道kabuto1 个月前
前端每日知识点:Next.js 渲染与缓存:从 Pages Router 到 Cache Components 的范式迁移
next.js
名字还没想好☜1 个月前
React 实现暗黑模式切换:localStorage 持久化、SSR 首屏闪烁与跟随系统主题
前端·javascript·react.js·ecmascript·react·next.js