Nuxt.js路由中使用localStorage及beforeEach校验token的问题求助
Hey there! The error you're hitting comes down to Nuxt.js being an isomorphic framework—it runs code both on the server (during SSR) and the client. localStorage is a browser-only API, so when your route guard code executes on the server, it can't find localStorage and throws that "not defined" error. Let's fix this properly:
Fix 1: Add a Client Environment Check
First, wrap your localStorage access with Nuxt's built-in process.client flag. This variable is true only when code runs in the browser, so it keeps you from accessing browser APIs on the server:
export default ({ app, store, redirect }) => { app.router.beforeEach((to, from, next) => { // Only touch localStorage when running in the browser if (process.client) { const token = localStorage.getItem("token"); // Use a Vuex mutation to update state (never modify state directly!) store.commit('setToken', token || ''); } // Adjust your auth logic here—example: redirect to login if no token for protected pages const isProtectedRoute = to.meta.requiresAuth; if (isProtectedRoute && !store.state.tokenim) { return redirect('/login'); } next(); }); };
Fix 2: Use Nuxt Middleware (Recommended)
Nuxt has a dedicated middleware system for route guards that fits better with its architecture than directly modifying app.router.beforeEach. Here's how to set it up the "Nuxt way":
- Create a middleware file at
middleware/auth.js:
export default function ({ app, store, redirect, route }) { // Fetch token from localStorage only on the client if (process.client) { const token = localStorage.getItem("token"); store.commit('setToken', token || ''); } // Check if the current route requires authentication if (route.meta.requiresAuth && !store.state.tokenim) { return redirect('/login'); } }
- Update your Vuex store to use mutations (direct state assignment breaks reactivity):
// store/index.js export const state = () => ({ tokenim: '' }); export const mutations = { setToken(state, token) { state.tokenim = token || ''; } };
- Apply the middleware globally or per-page:
- Global (all routes use the auth check):
// nuxt.config.js export default { router: { middleware: 'auth' } };
- Per-page (only specific pages get the check):
<!-- pages/protected-page.vue --> <template> <!-- Your page content here --> </template> <script> export default { middleware: 'auth' }; </script>
Quick Tips:
- Mark routes that need authentication with a
requiresAuth: truemeta field (you can add this innuxt.config.jsor individual page components). process.clientis Nuxt's official way to detect browser environments—avoid custom checks liketypeof window !== 'undefined'unless necessary.
内容的提问来源于stack exchange,提问作者FesaTR

