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

Nuxt auth-module中Token无法保存的问题及解决方案

Nuxt Auth Module: Token Not Saving After Login

Problem Description

I'm working on a project using Nuxt's auth-module, and ran into an issue where the authentication token wasn't being saved to the app after a successful login.

Here's the response structure from my login API:

{ 
  "data":{ 
    "user":{ 
      "bio": null,
      "createdAt": "2021-06-29T12:28:42.442Z",
      "email": "name@info.co",
      "id": 1,
      "image": null,
      "token": "token",
      "updatedAt": "2021-06-29T12:28:42.447Z",
      "username": "name" 
    } 
  } 
}

My initial auth configuration in nuxt.config.js looked like this:

auth: {
  strategies: {
    local: {
      endpoints: {
        login: { url: 'users/login', method: 'post', propertyName: 'data.user.token' },
        user: { url: 'me', method: 'get', propertyName: 'data' },
        logout: false
      }
    }
  }
},

Even with this setup, the token never got saved properly. I needed to figure out how to fix this.

Solution

After some troubleshooting, I restructured the auth configuration and resolved the token saving issue. Here's the updated working configuration:

auth: {
  strategies: {
    local: {
      token: {
        property: 'user.token', // Points to user.token within the API's data response
        type: 'Token' // Set this if your token type isn't the default Bearer
      },
      user: {
        property: 'user' // Extracts the user object from the /user API's data response
      },
      endpoints: {
        login: { url: '/users/login', method: 'post' },
        user: { url: '/user', method: 'get' },
        logout: false
      }
    }
  }
},

Key Changes Explained

  • Token Path Configuration: Instead of defining propertyName directly inside endpoints.login, moving this to the dedicated token.property field makes it clearer and more reliable for nested response structures. Note that the property value is relative to the top-level data field in your API response, so data.user.token becomes user.token in the config.
  • Token Type Specification: Explicitly setting token.type to Token ensures the auth module uses the correct format for the Authorization header. If your backend doesn't use the default Bearer type, this step is critical—without it, the token won't be recognized or stored correctly.
  • User Data Extraction: Configuring user.property to user tells the module to pull the user object directly from the data field of the /user API response, ensuring user details are stored alongside the token.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 21:12:27