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
propertyNamedirectly insideendpoints.login, moving this to the dedicatedtoken.propertyfield makes it clearer and more reliable for nested response structures. Note that thepropertyvalue is relative to the top-leveldatafield in your API response, sodata.user.tokenbecomesuser.tokenin the config. - Token Type Specification: Explicitly setting
token.typetoTokenensures the auth module uses the correct format for the Authorization header. If your backend doesn't use the defaultBearertype, this step is critical—without it, the token won't be recognized or stored correctly. - User Data Extraction: Configuring
user.propertytousertells the module to pull the user object directly from thedatafield of the/userAPI response, ensuring user details are stored alongside the token.
内容的提问来源于stack exchange,提问作者Ehsan
相关产品推荐
相关产品推荐

