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的读取以及名称的不可控。

相关推荐
倾颜4 天前
不只是接个计算器:我是怎么把 Tool Calling 做成可扩展骨架的
langchain·llm·next.js
倾颜8 天前
我把本地 AI Chat 项目重构了一遍:用 LangChain.js + Ollama + Streamdown 搭了一个最小可扩展架构
langchain·llm·next.js
helloweilei8 天前
React.cache:让你的服务器组件告别“重复劳动”
next.js
helloweilei8 天前
next/dynamic和React.lazy的区别
前端·next.js
helloweilei12 天前
Next.js 中 SSR 与 RSC 的区别:别再傻傻分不清了!
next.js
Zacks_xdc13 天前
【全栈】Next.js + PostgreSQL + Vercel 实现完整登录系统(完整源码)
postgresql·全栈·next.js·登录鉴权·vercel
点正15 天前
详解TypeScript项目引用(Project References)中rootDir的坑:composite:true下为何不能指定rootDir
前端·next.js
小霖家的混江龙16 天前
仿淘宝 AI 推荐:用 Next.js 构建入门智能水果推荐 Demo
前端·人工智能·next.js
用户8815869109119 天前
2026 年,你还不懂 Nex...
next.js
城南陌上21 天前
Next.js 博客终极 SEO 优化指南:从 Sitemap 到动态 OG 图片(end)
next.js