You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nuxt集成Strapi注册后JWT Cookie刷新页面丢失问题求助

解决方案:NuxtStrapi认证后Cookie丢失问题

问题根源

  1. 手动设置Cookie时错误地将响应式ref对象直接赋值,而非实际的token值
  2. 未利用NuxtStrapi插件自带的Cookie管理能力,手动设置与插件自动处理产生冲突
  3. 配置文件中未正确配置Cookie的过期属性

修复步骤

1. 调整Nuxt配置文件(nuxt.config.ts)

直接在Strapi模块配置中定义Cookie参数,插件会自动处理Cookie的生成与维护:

export default {
    modules: ['@nuxtjs/strapi'],
    strapi: {
      url: process.env.STRAPI_URL || 'http://localhost:1337',
      prefix: '/api',
      version: 'v4',
      cookie: {
        maxAge: 60 * 60 * 10, // 10小时,单位为秒
        secure: process.env.NODE_ENV === 'production', // 生产环境启用HTTPS安全传输
        sameSite: 'lax' // 兼容跨站请求场景
      },
      cookieName: 'strapi_jwt',
    },
}

2. 简化注册组件脚本

移除手动设置Cookie的代码,依赖插件自动完成token存储:

<script setup>
import { createAvatar } from '@dicebear/core';
import { lorelei } from '@dicebear/collection';

const username = ref('');
const email = ref('');
const password = ref('');
const avatarUrl = ref('');
const formSubmitted = ref(false);

const { register } = useStrapiAuth();

const handleSubmit = async () => {
  try {
    await register({
      username: username.value,
      email: email.value,
      password: password.value,
    });
    
    const avatar = createAvatar(lorelei, {
          size: 128,
        }).toDataUriSync();       
        avatarUrl.value = avatar;
        formSubmitted.value = true;
  } catch (e) {
    console.log(e);
  }
};
</script>

关键说明

  • NuxtStrapi插件在register成功后,会自动将返回的JWT Token存入配置的Cookie中,无需手动干预
  • 配置文件中的cookie参数会直接应用到生成的Cookie上,确保过期时间、安全属性等符合需求
  • 生产环境必须开启secure属性,避免Cookie在HTTP环境中被窃取

内容的提问来源于stack exchange,提问作者RENAUD

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 06:43:15