未定义Grid0服务器端渲染中断与窗口的Auth0身份验证

时间:2019-05-25 18:08:18

标签: javascript vue.js auth0 ssr gridsome

我已经按照Gridsome的教程实现了auth0 Vuejs,并且在开发中效果很好。 但是,当我运行gridsome build时,构建失败,因为在服务器上下文中未定义window

我在Auth0-js库中发现了一些问题,这些问题声称Auth0只应在客户端使用,但是由于Gridsome的工作方式,我似乎无法找到一种仅加载Auth0的方法-js在客户端。

Gridsome具有main.js,可在其中添加插件,并在其中定义身份验证的路由。

Main.js

import AuthServicePlugin from '~/plugins/auth0.plugin'
import auth from '~/auth/auth.service'

export default function (Vue, { router, head, isClient }) {
  ...
  Vue.use(AuthServicePlugin)
  //Handle Authentication
  router.beforeEach((to, from, next) => {
    if (to.path === "/auth/logout" || to.path === "/auth/callback" || auth.isAuthenticated()) {
      return next();
    }

    // Specify the current path as the customState parameter, meaning it
    // will be returned to the application after auth
      auth.login({ target: to.path });

  })

基于Gatsbyb.js auth0实施教程,我尝试从null-loader的webpack加载中排除auth0-js

gridsome.config.js

configureWebpack: {
    /*
     * During the build step, `auth0-js` will break because it relies on
     * browser-specific APIs. Fortunately, we don’t need it during the build.
     * Using Webpack’s null loader, we’re able to effectively ignore `auth0-js`
     * during the build. (See `src/utils/auth.js` to see how we prevent this
     * from breaking the app.)
    */
    module: {
      rules: [
        {
          test: /auth0-js/,
          use: 'null-loader',
        },
      ],
    },

我很想了解有关如何仅在具有Gridsome的客户端上下文中包含和加载Auth0的想法

1 个答案:

答案 0 :(得分:1)

在Gridsome中使用 Firebase身份验证时,我遇到了同样的问题。

created()生命周期挂钩中的代码似乎在Gridsome构建过程(服务器环境)中执行,但是mounted()生命周期挂钩中的代码仅在浏览器中执行!

解决方案是将仅应在客户端中运行的所有代码放入mounted生命周期挂钩中。

mounted() {
  // load the `auth0-js` here
  ...
}

在我的实例中(使用Firebase Auth),这是解决方案:

在“默认布局”组件中:

const app = import("firebase/app");
    const auth = import("firebase/auth");
    const database = import("firebase/firestore");
    const storage = import("firebase/storage");

    Promise.all([app, auth, database, storage]).then(values => {
      // now we can access the loaded libraries ?!
    });
}