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

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();
  });
};

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":

  1. 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');
  }
}
  1. 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 || '';
  }
};
  1. 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: true meta field (you can add this in nuxt.config.js or individual page components).
  • process.client is Nuxt's official way to detect browser environments—avoid custom checks like typeof window !== 'undefined' unless necessary.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 14:37:51