如何在Nuxt Auth中设置基于window.location.hostname的localStorage前缀?
问题场景
想要给Nuxt Auth的localStorage认证令牌添加当前域名作为前缀,目标格式为[mysite.local]auth._token.local,尝试在nuxt.config.js中直接配置:
auth: { localStorage: { prefix: '[' + window.location.hostname + ']' }, }
启动Nuxt时触发致命错误:
FATAL window is not defined 10:33:30
at nuxt.config.js:237:21
at jiti (node_modules/jiti/dist/jiti.js:1:196506)
at Object.loadNuxtConfig (node_modules/@nuxt/config/dist/config.js:1082:15)
at loadNuxtConfig (node_modules/@nuxt/cli/dist/cli-index.js:338:32)
at NuxtCommand.getNuxtConfig (node_modules/@nuxt/cli/dist/cli-index.js:463:26)
at Object._listenDev (node_modules/@nuxt/cli/dist/cli-dev.js:75:30)
at Object.startDev (node_modules/@nuxt/cli/dist/cli-dev.js:58:25)
at Object.run (node_modules/@nuxt/cli/dist/cli-dev.js:52:16)
at NuxtCommand.run (node_modules/@nuxt/cli/dist/cli-index.js:413:22)╭───────────────────────────────────────────╮
│ │
│ ✖ Nuxt Fatal Error │
│ │
│ ReferenceError: window is not defined │
│ │
错误原因
nuxt.config.js是在服务端启动阶段解析的,此时浏览器的window对象尚未创建,直接引用会触发未定义错误。
解决方案
方案1:利用prefix的函数特性(适用于支持该特性的Nuxt Auth版本)
部分Nuxt Auth版本允许localStorage.prefix设为函数,函数会在客户端运行时执行,此时能正常访问window对象:
auth: { localStorage: { prefix: () => `[${window.location.hostname}]` }, }
方案2:通过客户端插件动态修改配置
如果版本不支持函数配置,可通过客户端插件实现:
- 在项目
plugins目录下创建auth-config.js文件:
export default function ({ $auth }) { // 仅在客户端环境执行 if (process.client) { $auth.$storage.options.prefix = `[${window.location.hostname}]` } }
- 在
nuxt.config.js中注册该插件,并指定仅在客户端运行:
plugins: [ // 其他已注册插件... { src: '~/plugins/auth-config.js', mode: 'client' } ],
验证
启动项目并完成登录后,打开浏览器开发者工具查看localStorage,即可看到认证令牌键已变为[当前域名]auth._token.local格式。
内容的提问来源于stack exchange,提问作者VIktor

