Gridsome server-side rendering encounters issues with Auth0 authentication when the window object is not defined

After successfully following the Auth0 Vuejs tutorial with Gridsome during development, I encountered a problem when trying to build using gridsome build. The build failed because window was undefined in a server context.

I discovered some issues in the Auth0-js library stating that Auth0 should only be used on the client side. However, due to Gridsome's structure, I struggled to find a way to exclusively load Auth0-js on the client side.

In Gridsome, the main.js file is where plugins are added and authentication routing is defined.

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

  })

Attempting to follow a Gatsby.js Auth0 implementation tutorial, I tried excluding auth0-js from webpack loading with null-loader.

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',
        },
      ],
    },

I am seeking suggestions on how to properly include and load Auth0 exclusively on the client side within the Gridsome framework.

Answer №1

Encountering a similar issue while integrating Firebase Authentication with Gridsome inspired me to find a workaround.

It appears that the code within the created() lifecycle hook is triggered during the Gridsome build process (server environment), whereas the mounted() lifecycle hook functions solely in the browser!

To tackle this, I consolidated all client-side specific code within the mounted lifecycle hook.

mounted() {
  // Integrate 'auth0-js' here
  ...
}

In my scenario (working with Firebase Auth) this approach proved successful:

Within the Default Layout component:

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 => {
      // The loaded libraries are now accessible! 😍!
    });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Simulating npm package with varied outputs

In my testing process, I am attempting to simulate the behavior of an npm package. Specifically, I want to create a scenario where the package returns a Promise that resolves to true in one test and rejects with an error in another. To achieve this, I hav ...

After switching from jQuery to pure JavaScript, the code is now up and

After initially coding in jQuery + AJAX, I attempted to rewrite it in vanilla JavaScript. However, the code is not functioning as expected now. Can someone help me identify the mistake causing nothing to display when I run it through the server? I have che ...

Display title upon hovering over image linked to mysql with php

Is there a way to display the image title when hovering over images connected to MySQL using PHP? Below is the code I have been using: <div class="galleryko"> <?php $data = mysql_query("SELECT * FROM tbl_gallery_featured")?> <div clas ...

Transfer a term to a different division - JavaScript Object Model

I am trying to achieve a specific task where I need to move one term under another in SharePoint. However, despite my efforts using JSOM and SharePoint 2013, I have not been able to find a direct method for moving terms. The code snippet I have used below ...

Utilize utility functions within the onCreated lifecycle event in Meteor

Here is my current setup: Template.myTemplate.helpers({ reactiveVar: new ReactiveVar }); How can I initialize reactiveVar within the onCreated function? Template.restaurantEdit.onCreated(function() { // I want to initialize helpers.reactiveVar here ...

Despite being present in the node_modules folder, the ag-grid-vue module appears to be missing

Currently, I am diligently following the Vue.js AgGrid getting started tutorial step by step: https://www.ag-grid.com/vuejs-grid/ However, upon adding the <script> section and saving my progress, an error promptly appears: ERROR Failed to compile ...

Encountering trouble installing Angular CLI on MacOS High Sierra version 10.13.2

I am encountering an issue while trying to install Angular CLI. I have successfully installed the latest NodeJs version 8.9.4 and npm version 5.6.0. However, when I attempt to run the command npm install -g @angular/cli, I receive the following error messa ...

Extracting public data from social media profiles as displayed in Smartr

Is there any pre-existing API or reference material available for achieving this task? I am interested in accessing public social data without the need for users to manually link their accounts to our site. ...

Utilizing a JavaScript variable in Jquery for managing an mp3 playlist

I am working on implementing an album feature for the jPlayer that is already in use. Here is the current static code: $(document).ready(function(){ new jPlayerPlaylist({ jPlayer: "#jquery_jplayer_1", cssSele ...

How to Use Jquery to Perform Subtraction on Elements

Hello everyone! I am currently working on creating a nutrition label similar to this one: Example I have set up my database and now I am focusing on getting it to work with one element before moving on to the rest. Here is what my database looks like: in ...

Show only child elements of a specific type within the parent div

Looking to identify divs with the class 'test' that contain only buttons in their child nodes. This is the HTML code that needs to be filtered. <div class="test"> <div> <button> <span>Button 1</span></butto ...

What is the best way to highlight specific text in React components that is passed from an object?

This is the page HTML content where an object is created. A portion of the description needs to be emphasized: const agencyProps = { title: "Managed agency selection", paragraph: "Strengten your onboarding process", videoImage: { ...

Do I have to include reject() in the executor when using promises in express.js?

If we choose not to handle rejection, is it necessary to include the reject parameter in the promise executor? For example: new Promise((res) => { res(a); }) ...

Issues encountered while sending HTML Form data to MySQL with Node JS

I have been experimenting with a basic html form to mysql using nodejs, but unfortunately it is not functioning as expected. The HTML file is named index.html and the Node.js file is called test.js. Below you can find my code: My HTML <!DOCTYPE html&g ...

Guide on initializing a Redux toolkit state with an array of objects or local storage using TypeScript

Currently, I am attempting to set an initial state (items) to an array of objects or retrieve the same from localStorage. However, I am encountering the following error. Type 'number' is not assignable to type '{ id: string; price: number; ...

Create a unique filter in an ng-repeat directive that allows users to personalize the data displayed

Is there a way to create a custom filter that hides the inventory column for Color Pencil Special on October 2nd, 2017 in the view? The inventory for Color Pencil Special is dependent on the inventory of regular Color Pencils, which are stored somewhere e ...

The jQuery function $.fn.myfunction appears to be malfunctioning

Here's the code I'm working with: [[A]] // jquery.fn.code (function( $ ){ $.fn.flash = function(duration) { this.animate({opacity:0},duration); this.animate({opacity:0},duration); }; })( jQuery ); 1. $(document).ready ...

Use Angular and JavaScript to fetch HTML from a mySQL database and dynamically render it on a webpage

I'm currently utilizing Angular for the front end and Node for the back end. The data is retrieved from a MySql database where it's manually stored in text format with HTML tags. For example: <ul> <li>item1</li> <li> ...

Determining the class condition using AngularJS ng-class

I am working with an HTML element that contains AngularJS directives: <div class="progress"> <span ng-repeat="timeRangeObject in timeRangeObjects" style="width: {{timeRangeObject.percentage}}%" ...

How do I add a "Switch to Desktop Site" link on a mobile site that redirects to the desktop version without redirecting back to the mobile version once it loads?

After creating a custom mobile skin for a website, I faced an issue with looping back to the mobile version when trying to add a "view desktop version" link. The code snippet below detects the screen size and redirects accordingly: <script type="text/j ...