Nuxt.js插件中无法通过context访问$auth对象的技术问询
$auth in Your Nuxt Axios Interceptor Plugin Looks like you're hitting a common timing/access issue with the @nuxtjs/auth module in your axios interceptor. Let's walk through why context.$auth is coming up undefined and how to fix it so you can call $auth.logout() when handling 401/403 errors.
The Root Cause
While the auth docs state $auth is globally injectable, there are two likely reasons you're seeing undefined:
- Plugin Execution Timing: Your axios interceptor might be running before the auth module finishes initializing the
$authinstance, especially in server-side contexts. - Context Structure: In some cases,
$authis attached to the app object (context.app.$auth) rather than directly exposed in the top-level context.
Fixes to Try
1. Access $auth from context.app (with Fallback)
Modify your interceptor to grab the auth instance from context.app as a backup. This ensures you're accessing the globally injected instance no matter the context structure:
export default function (context) { const { $axios, route, redirect, $auth } = context // Fallback to app.$auth if direct context access fails const authInstance = $auth || context.app.$auth $axios.interceptors.response.use( function (response) { return response }, function (error) { const code = parseInt(error.response && error.response.status) const thisRoutePath = route.path if ([401, 403].includes(code)) { // Guard against undefined to avoid runtime errors if (authInstance) { authInstance.logout() } if (thisRoutePath !== '/') { redirect('/?login') } } return Promise.reject(error) } ) }
2. Restrict the Plugin to Client-Side Execution
Auth state management is primarily a client-side concern, and server-side execution of your interceptor might not need auth handling anyway. Update your nuxt.config.js to run the plugin only on the client, which guarantees the auth module has fully initialized before the plugin runs:
plugins: [ { src: '@/plugins/axios-interceptor.js', mode: 'client' } ],
3. Confirm Auth Middleware is Active
You already have the auth middleware enabled in your router config, which helps ensure $auth is initialized before route navigation. This should work hand-in-hand with the above fixes to make the auth instance available when your interceptor runs.
Why This Works
- The
context.app.$authfallback covers cases where the auth instance isn't directly in the top-level context. - Running the plugin client-side avoids server-side initialization race conditions where
$authmight not be ready yet. - The guard check for
authInstanceprevents unexpected runtime errors if the auth instance is unavailable for any reason.
内容的提问来源于stack exchange,提问作者isoittech

