leveraging a Nuxt plugin and saving it in middleware

My goal is to create a middleware that validates the authentication and entitlement of users. The authentication details are retrieved from my store:

//store/index.js
const state = () => ({
  auth: {
    isLoggedIn: false
    // more properties here
  }
});

While the entitlements come from a plugin:

//plugins/entitlement.js

  import axios from 'axios';
  export default (context, inject) => {
    const { env: { config: { entitlementUrl } }, store: { state: { auth: { access_token } } } } = context;
  const headers = { 
    Authorization: `Bearer ${access_token}`,
    'Content-Type': 'application/json' 
  };
  inject('entitlement', {
    isEntitled: (resourceId) => new Promise((resolve, reject) => {
      axios.get(`${entitlementUrl}/entitlements`, { headers, params: { resourceId } })
      .then(({ data }) => {
        resolve(data.Count > 0);
      })
      .catch((error) => {
        reject(error);
      });
    })
  };

I have implemented this middleware but it's not functioning as expected:

//middleware/isEntitled.js

export default function ({ app, store }) {
  if(store.state.auth.isLoggedIn){
    let isEntitled =  app.$entitlement.isEntitled('someId');
    console.log('Is user entitled? ', isEntitled)
  }
}

To integrate it into my configuration, I added the following:

//nuxt.config.js
  router: {
     middleware: 'isEntitled'
  },

However, when testing, I encounter an error stating isEntitled is undefined. My intention is to verify on each page whether the user is entitled or not. How can I rectify this issue?

Answer №1

When approaching the situation from the perspective of a plugin, you have the ability to take the following steps:

To begin, create a plugin:

export default ({app}) => {
    // Triggered every time the route changes (including during initialization)
    app.router.beforeEach((to, from, next) => {
        if(app.store.state.auth.isLoggedIn){
            let isEntitled =  app.$entitlement.isEntitled('someId');
            console.log('entitled? ', isEntitled)
        }
        return next();
    })
}

Next, integrate the created plugin into your nuxt.config.js file:

plugins: [
   '~/plugins/your-plugin.js',
],

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

What is the process for importing an external template into a Vue.js application?

I am new to vue js and I'm not sure if my question is correct. I would like to create the following structure for my Laravel 5.3 - Vue Js App. my-vue.js Vue.component('my-component', { template: 'template from Catgory.Vue ...

Exploring the World of Angularjs 2

Currently, I am diving into learning angularjs 2. I found a helpful git repository that I am following closely, which can be found here. The repository contains some interesting codes in the index.html file. <script src="node_modules/core-js/client/shi ...

Stay connected with AJAX's latest updates on Twitter with just 13 bytes

Twitter sends a POST request of only 13 bytes when someone follows an account. This small amount of information helps to reduce latency and server load, providing advantages for web developers. However, removing unnecessary cookies and extra information f ...

Guide to creating a production build for electron with react js and next framework

Currently, I am working with electron using react js and next. I am struggling to figure out how to create its production build. Can someone provide me with assistance along with a detailed step-by-step guide? app node_modules pages routes static packa ...

Assign external data to component prior to rendering

When using Vue Router with file based components, I encountered an issue with rendering data from an API in a component called CaseDetail.vue. This component receives a parameter (slug) which is used to fetch a JSON from the API using axios. To handle thi ...

Struggling to access the "this.array" variable within a TypeScript-powered Angular 4 application

I cannot access the this.array variable in my TypeScript-Angular 4 application. The error is being thrown at this.services.push because this.services is undefined. My code looks like this: export class ServersComponent implements OnInit { //Initializi ...

Angular ng-bind-html directive allows you to bind HTML content to an

I am attempting to utilize $interpolate and ng-bind-html in order to bind the data from my scope variable to an html string as outlined in this solution. However, I have encountered an issue where the ng-bind-html result does not update when the value of m ...

Discovering the generic type from an optional parameter within a constructor

Looking to implement an optional parameter within a constructor, where the type is automatically determined based on the property's type. However, when no argument is provided, TypeScript defaults to the type "unknown" rather than inferring it as "und ...

Server-side rendering or updating of React elements

One issue I am facing in my React app is that while all components can update themselves through the browser, a specific module called jenkins-api only functions when called server side. To retrieve the data and pass it into my template, I have utilized th ...

The Next.js page suddenly disappears after a moment

Out of the blue, my next.js page suddenly went blank for no apparent reason. I didn't make any changes, it just happened. I attempted to restart my dev server and even deleted the '.next' folder, but nothing seemed to fix the issue. Despite ...

I must create text that is transparent against a colorful gradient background

Hey there! I'm seeking help in figuring out how the text on this site is designed. You can take a look at it here. Essentially, what I'm aiming for is to have the text color match the gradient of the background color from the previous div, while ...

Using a directive to implement Angular Drag and Drop functionality between two tables with 1000 records

My code is functional, but there seems to be a delay in the appearance of the helper(clone) when dragging starts. I have two tables - one for the include list and another for the exclude list. Users can drag table rows from the include table to the exclud ...

The @Input() function is failing to display or fetch the latest value that was passed

I am currently working on an angular project, and I've encountered a situation where I'm attempting to send a value from a parent component to a child component using the @Input() decorator. Despite my efforts, the child component continues to di ...

"Authentic JavaScript Universal Time Coordinated (UTC) Date

I've been struggling to keep my dates in UTC within my JavaScript application. Surprisingly, the Date's getTimezoneOffset() method does not return a value of 0, which I expected it to do. This seems crucial for accurately converting dates between ...

Authenticating the identity of the client application - the client is currently within the browser

I have a PHP backend (although it's not really important) and a Javascript client that runs in the browser. Here is how the application operates: The user accesses a URL and receives raw templates for rendering data An Ajax GET query is sent to the ...

Showcase multiple examples of three.js on a single webpage

I need to showcase several 3D objects on my web app within different containers. Currently, I'm creating multiple three.js renderers, each for a separate container. However, I encountered an error message: "WARNING: Too many active WebGL contexts. Old ...

How to capture and log request and response data when using the HttpService in NestJS?

Is there a way to log requests, responses, and errors using the HttpService within the HttpModule? In the past, I have used Interceptors with AXIOS. While HttpService wraps axios, I'm having trouble adding interceptors. There doesn't seem to be ...

What is the best way to populate dropdown menus using JavaScript?

I'm facing an issue with my ajax request where I am unable to populate the options of a select tag. This problem is occurring in multiple blocks where the select tag serves the purpose of choosing a type of product. Here is how my select tag looks li ...

Can an additional height be added to the equalizer to increase its height?

Is it feasible to append an additional 35px to the height determined by Foundation Equalizer? For instance, if Equalizer computes a height of 350px, I would like to increase it by 35px. This means that the resultant style should be height: 385px; instead ...

To iterate through a multi-dimensional array

I am facing an issue with fetching data within an array in the code below var str = "Service1|USER_ID, Service1|PASSWORD" var str_array = str.split(','); console.log(str_array) for(var i = 0; i < str_array.length; i++) { str_array[i] = st ...