The Nuxt.js authentication module remains in place and does not redirect users who are already logged

An authenticated user can still access the /login page. If I click on a link to the /login page, I am redirected to a different page successfully. However, if I manually type in /login in the URL, I am still taken to the login page even though I am already logged in. My goal is to redirect the user to the /retailer/account page before any components are displayed on the page when they are logged in and try to access the /login page manually.

I have tried using the beforeMount() function and the beforeCreate() function following the documentation for the auth: 'guest' middleware, but it does not seem to work as expected, as the loggedIn always returns false before the page is fully rendered.

Here is my setup:

nuxt.config.js :

export default {
  mode: 'universal',
  target: 'static',
  auth: {
    cookie: {
      prefix: 'auth_'
    },
    // Options
    redirect: {
      login: '/login',
      logout: '/login',
      callback: false,
      home: '/retailer/account'
    },
    strategies: {
      local: {
        endpoints: {
          login: {
            url: '/auth/login',
            method: 'post',
            propertyName: 'access_token',
            credentials: true
          },
          logout: {
            url: '/auth/logout',
            method: 'post'
          },
          user: {
            url: '/auth/me',
            method: 'post',
            propertyName: '',
            credentials: false
          }
        },
        token: {
          required: true,
          type: 'Bearer',
          global: true
        },
        autoFetchUser: true
      }
    },
    preserveState: true,
    watchLoggedIn: true
  },
  router: {
    middleware: [
      'auth'
    ]
  }
}

layouts/default.vue :

export default {
  auth: false
}

pages/retailer/account.vue :

export default {
  middleware: 'auth'
}

pages/login.vue :

export default {
  middleware: 'authenticated',
  auth: 'guest'
}

I have tried various middleware examples and implemented some basic redirection code, but the issue persists where app.$auth.loggedIn always returns false from the server-side, preventing me from being redirected.

middleware/authenticated.js

export default function ({ app, redirect }) {
  if (app.$auth.loggedIn) {
    return redirect(app.localePath({ name: 'index' }))
  }
}

After Vue hydrates the app, the loggedIn naturally becomes true.

If you have any ideas or guidance on what I could be doing wrong, I would greatly appreciate it!

Answer №1

The Nuxt authentication module includes a middleware called auth that redirects unauthenticated users to the login page and authenticated users to the home page.
It appears that the auth middleware is configured correctly in your nuxt.config.js file.
However, the issue lies in the fact that the auth middleware only functions on the server side for SSR, while you have set up to generate a static website.
You can resolve this by removing the line target: 'static', from your nuxt.config.js file.
Alternatively, you may find assistance for implementing authentication on a static site by following this issue: https://github.com/nuxt/nuxt.js/issues/3023

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 best way to update a value and trigger a re-render in ReactJS?

this.state={ value: 'v1', newValue: '', } componentDidMount = () => { let nV = this.state.value + 'received'; this.setState({ newValue: nV, }); } tabClick = (val) => { this.setState({ value: val, ...

Can a Firestore Realtime Query be reutilized after being in the background in order to cut down on expenses?

In my Vue PWA, I am utilizing the firebase-js-sdk to receive realtime updates from Firestore. When bringing the app back from being in the background, I rely on "vuex-persist" to maintain the app state. In addition to the app state, it is necessary for me ...

Showing text in a textarea while maintaining formatting (such as using <br>)

Can someone help me with formatting a block of text like this: hello <br> how is your day <br> 123 To look like this: hello how is your day 123 I also need to display it in a textarea field. I attempted to do so using the following code: $ ...

Navigate to a new tab with a parameter in AngularJS

Is there a way to open a new tab using state.go with parameters? This is the state configuration: .state("view", { url: "/view", templateUrl: 'app/components/view/view.html', controller: 'viewController', params: { ...

Implementing the MVC pattern in the app.js file for a Node.js and Express web application

After completing several tutorials on nodejs, mongodb, and express, I have gained a solid understanding of the basics such as: The main controller file being app.js. Third party modules stored in their designated node_modules directory. Template files pl ...

Fetching from the same origin results in a null comparison issue due to HTTP CORS restrictions

Encountering an issue where a simple same-origin fetch("fetch.xml") call fails, resulting in a console error message Access to fetch at 'http://127.0.0.1:8000/fetch.xml' from origin 'null' has been blocked by CORS policy: Th ...

Babel had a SyntaxError in test.jsx file at line 3, position 11 with an Unexpected token

Having trouble converting JSX to JS with Babel? If you're seeing an error like the one below, don't worry - we can help you fix it: The example code in test.jsx is causing a SyntaxError when transformed using babel test.jsx: SyntaxError: test ...

Converting a Curl command to a JavaScript POST request: best practices

Is it possible to convert the given curl code into a JavaScript post request that will function effectively in all browsers? curl https://connect.stripe.com/oauth/token \ -d client_secret=sk_test_f7PKXx5NRBFG5r41nTrPT7qB \ -d code="{AUTHORIZATIO ...

What is the process of converting an image taken with the 'react-camera-pro' into a byte array?

I am in the process of capturing an image using a camera through 'react-camera-pro' and I need to figure out how to convert the captured image into a byte array. Here is the snippet of code that I am working with: const camera = useRef(null); ...

Attach onClick event when employing a higher order component

Just getting started with React and I have a question. After following some blog posts, I was able to create a page using higher order components and componentDidMount to fetch data from an API and display it. Everything works smoothly and the code looks ...

How to handle a Node.js promise that times out if execution is not finished within a specified timeframe

return await new Promise(function (resolve, reject) { //some work goes here resolve(true) }); Using Delayed Timeout return await new Promise(function (resolve, reject) { //some work goes here setTimeout(function() { resolve(true); }, 5000); } ...

What causes the server to give an incorrect response despite receiving a correctly read request?

After setting up a new project folder and initializing NPM in the Node.js repl, I proceeded to install the Express package. In my JavaScript file, I included the following code: const express = require('express'); const app = express(); ...

Making sure to consistently utilize the service API each time the form control is reset within Angular 4

In the component below, an external API service is called within the ngOnInit function to retrieve an array of gifs stored in this.items. The issue arises when the applyGif function is triggered by a user clicking on an image. This function resets the For ...

A guide on displaying containers with jQuery and CSS

Looking to create a smiley survey using only Front-End technologies. Once a radio button is selected, the associated content should appear for comments. Currently, I have set up my CSS with display: none. I attempted to implement this functionality using ...

Update the content within every <td> element using AJAX/JQUERY on a table created from JSP

I have a database filled with descriptions and corresponding ID numbers. The table displays them like this: index.jsp <table> <tr> <td>Name:</td> <td>Id:</td> </tr> <c:forEach items ...

Comparing Angular extend to $provide.decorator: A breakdown

I find myself in a state of confusion. Can you please provide some clarity on the distinction between angular.extend() and $provide.decorator? When and why would one use the latter option? Does decorator serve a different purpose compared to extend? Desp ...

It is not possible to attach separate links to images in a JavaScript slider

I am struggling with linking individual images in a JavaScript slider for a client's website. The slider is fully functional and works well, but I can't seem to figure out how to link the images properly. When I remove items from <--ul class= ...

Node.js method convention - invoking self-defined functions

Consider a scenario where a Node module contains two functions, func1() and func2(). It is necessary for func1 to make a call to func2 during its execution. In order to test func2 independently, I have included both func1 and func2 in the exports by setti ...

jquery expanding the width of the final element

Is there a way to increase the width of the last 'th' in a string? I want it to be the current width plus 20px. Here is the code on Fiddle var header="<th id='tblHeader_1' style='width: 80px;'><span>Id</span&g ...

Exploring different ways to navigate JSON data dynamically and efficiently modify it

I have a JSON data structure resembling a map. var map = { level1 : { x : {name:'level1 x' , }, y : {name:'level1 y'} }, level2 : { x : {name:'level2 x&a ...