Is it a common issue for a Nuxt.js page using Keycloak.js authentication middleware to reload twice when the browser window is refreshed? Also, it seems that the N

My current setup involves implementing authentication with Keycloak in a Nuxt.js middleware using the code below:

import Keycloak from 'keycloak-js'

const keycloak = new Keycloak({
  url: 'http://localhost:8080/auth',
  realm: 'dev-employee',
  clientId: 'emp-ui'
})

export default function({ store, redirect }) {
  if (keycloak.authenticated) return true

  return keycloak
    .init({
      onLoad: 'login-required',
      checkLoginIframe: true,
      checkLoginIframeInterval: 5
    })
    .success(authenticated => {})
    .error(function() {
      alert('failed to initialize')
    })
}

In the nuxt.config.js file:

 router: {
    middleware: ['authentication']
  },

Upon loading the browser window, the page renders and attempts to authenticate, causing a reload. The desired behavior is for the page to wait and not render until the Keycloak authentication is successful.

Answer №1

To implement the middleware correctly, you need to ensure that you return a new Promise in the following manner:

export default function({ store, redirect }) {
  if (keycloak.authenticated) return true

  return new Promise((resolve, reject) => {
    keycloak
      .init({
        onLoad: 'login-required',
        checkLoginIframe: true,
        checkLoginIframeInterval: 5
      })
      .success(resolve)
      .error(reject)
  })
}

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

Can the concept of partial class be used in an AngularJS controller?

Is it possible to organize code into groups using partials in angularjs? The issue is that my controller has become too cluttered with a lot of code for different methods and functionalities, making it difficult to read. I want to maintain the same contro ...

Combining array values in Node.js/JavaScript by matching key values

Looking to merge two arrays by matching key values in JavaScript/Node.js. Check out the code snippet below: var userData=[{'email':'<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d8b998bfb5b9b1b4f6bbb7b5">[em ...

Keep the HTML structure of an element in the DOM while excluding it from an ng-repeat loop

I am currently working with the array badge = [{'name':'abc', 'flag': true}, {'name':'cde', 'flag': false}, {'name':'def', 'flag': true} ] After using it with ng-rep ...

Running SOAP services with Jasmine framework in Node.js: A step-by-step guide

I've been successfully using the jasmine-node framework for automating my API tests. I can easily run REST services and retrieve results using node-fetch or http modules. However, my project also requires testing SOAP services. Can anyone provide guid ...

Locate a specific element within an array and retrieve its corresponding index

Need help updating a boolean property for all objects in an array with the same user ID. I've outlined my MVC framework below in a concise manner. Model: var posts = [{id:1, user_id:1, is_following:true}, {id:2, user_id:1, is_cool:true}, ...

Concealing elements with duplicate attributes using jQuery

Is there a way to hide duplicate elements in a list based on a specific attribute value using jQuery? Here is an example list: <div data-title="big hero 6">title</div> <div data-title="big hero 6">title</div> <div data-title="a ...

What steps can be taken when troubleshooting a select menu that was not chosen?

I am encountering an issue with a select menu in my code. The code snippet for the v-select component looks like this: <v-select dense outlined item-text="name" item-value="id" :items="frequencies" v-model=" ...

The code is running just fine when tested locally, but it seems to encounter an issue when accessed remotely, yielding

Currently, I am in the process of developing a dual twin setup using a Raspberry Pi. The goal is to simulate a continuous transmission of body temperature data, which is then sent to a server that stores the information in a MongoDB database. Everything fu ...

When selecting an old list, only the most recently created ID is displayed, rather than the ID of the specific list being

I've set up a dashboard where I can create lists and have them displayed on the screen, but there seems to be an issue when trying to open any list as only the last created one opens. Can anyone point out what mistake I might be making? The technologi ...

Getting form field values with JQuery

I am currently facing an issue with a form field in HTML. Here is the code snippet: <form id="tasklist"> <input type="text" id="name" ...></input> ... additional form elements go here ... </form> Although I am trying to retrie ...

Pedaling back and forth along a sequence

Is there a way to implement forward and backward buttons for a clickable list without using arrays, as the list will be expanding over time? I have already achieved changing color of the listed items to red, but need a solution to navigate through the list ...

execute a series of asynchronous functions one after another

async function cancelUserSubscriptionHandler() { const unsubscribe = await fetch("/api/stripe-sessions/cancel-subscription", { method: "PATCH", body: JSON.stringify(), headers: { "Content-Type": "appli ...

Visualization of extensive datasets in JavaScript

I'm currently developing a dashboard in JS for displaying sales data plots to users. Can anyone recommend a JavaScript library that meets the following criteria: Capable of plotting a large number of points (ex: 100k or more) Interactive functional ...

Is there a specific minimum height that should be set for the equalHeight function to apply?

Despite trying everything, I can't seem to achieve the dreadful layout my designer has given me without using JavaScript! The issue lies with the positioning of the div #backgr-box, which needs to be absolutely positioned behind the #contenuto ( ...

What could be causing the error I'm encountering while running the 'net' module in Node.js?

I am currently working with .net modular and have opened TCP port 6112. var net = require('net'); var server = net.createServer(function (socket) { //'connection' listener }); server.listen(6112, function () { //'listening ...

Using DefaultSeo does not override NextSeo in every component

I am looking to dynamically change the Head tag using next-seo. While browser validation will show NEXTSeo for individual pages, Twitter, Firebase's card validation tool, and others will default to next-seo-config.js. Does anyone have a solution? S ...

Why does the styling of the inner Span adhere to the style of the outer Span?

How can I adjust the opacity of the color "blue" to 1 in the code snippet below? <!DOCTYPE html> <html> <body> <p>My mom's eyes are <span style="color:blue;font-weight:bold;opacity:0"> <span style="color:blue;fo ...

Implementing an active class in Vue.js for the router-link component

I am facing an issue with my sidebar item becoming inactive when I click on a sublink inside a component. How can I prevent the active class from switching off? Here is my sidebar: <router-link to='/sub/success_tools_subscriptions' ...

A visually stunning image showcase with dynamic resizing and strategically placed white spaces using the m

I'm attempting to create a responsive image gallery using the Masonry jQuery plugin, but despite reading numerous articles and forum posts on the topic, I can't seem to get it to work properly. The gallery is displaying many blank spaces. My app ...

The draggable=true attribute in EaselJS (MovieClip) canvas does not display a ghost image

I am currently working with a canvas element that contains animations powered by EaselJS. The canvas is wrapped in a parent div with draggable set to true. <div class="outer-parent" draggable="true"> <div class="inner-parent"> <canvas& ...