Blocking access to specific pages using Axios interceptors is a powerful feature to enhance security and

I am implementing a feature to prevent unauthorized users from accessing personal account pages. Currently, Axios interceptors monitor error responses with a status of 401, indicating that a user is not authorized to view certain pages. If this status is detected, the user is automatically redirected to the login page using the following code:

axiosInstance.interceptors.response.use(null, (error) => {
  if (error.response.status === 401) {
    if (router.history.current.fullPath.includes('profile')) {
      router.replace({
        path: '/login',
      });
    }
    this.$cookie.delete('token');
  }
  if (error.response.status === 404) {
    router.push({ name: 'error' });
  }
  if (error.response.status === 500) {
    router.push({ name: 'server_error' });
  }
  return Promise.reject(error);
});

While this functionality works as intended, I have noticed some odd behavior in the interface. When an unauthorized user attempts to access a restricted page, they briefly see the page before being redirected to the login page. Is there a way to skip this brief visibility and go straight to the login page without revealing the blocked page?

Answer №1

In my opinion, a great solution would be to implement navigation guards. You can learn more about them here.

Here's an example:

const router = new VueRouter({
  routes: [
    {
      path: '/bar',
      component: Bar,
      beforeEnter: (to, from, next) => {
        if (!isLoggedIn()) {
          next({
            path: '/login'
          })
        } else {
          next()
        }
      }
    }
  ]
})

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

Utilize the drag-and-drop feature on an HTML5 canvas

When I drag an HTML element and drop it onto a canvas, the object is supposed to appear at the same location on the canvas where it was dropped. However, it is showing up at a different location instead. You can view my code for reference. Script functio ...

Eliminate all attributes from an array with the exception of one specific attribute

I'm dealing with an array var employee = [{"firstName": "something", "LastName":"something", "addresss":"something"},{"firstName": "something", "LastName":"something", "addresss":"something"},{"firstName": "something", "LastName":"something", "addres ...

Encountering the error "Object is not a function" while utilizing supertest/superagent within a forEach iteration

My current challenge involves using supertest to test multiple URLs while following the same set of rules. var urls = [ "https://www.example.com", "https://www.example2.com" ]; urls.forEach(function (url) { console.log('begin'); ...

Data stored in mongodb becomes corrupted when converted to binary format

After uploading a photo, it is converted to base64. When I send it to MongoDB using Mongoose, it saves as Binary. However, when I retrieve the same picture from the database, it returns as a Buffer array. Converting it back to base64 results in a completel ...

What is the best approach to unit testing this React Component?

I have created a component that acts as a wrapper for another component. My question is, how should I approach unit testing for this component? Besides checking the state and method calls to ensure they update the state correctly. Other than rendering pro ...

Neglecting to review the CSS - embracing ejs layouts in Express

I am encountering an issue with the express ejs layouts where only the mainPage is able to read the CSS, while the other pages are unable to do so (even though the HTML reads it). Additionally, if I want to use another layout such as "layout2.ejs", what s ...

Transform the JSON object into a TypeScript array

Currently working on a project that requires converting a JSON object into a TypeScript array. The structure of the JSON is as follows: { "uiMessages" : { "ui.downtime.search.title" : "Search Message", "ui.user.editroles.sodviolation.entries" : ...

Error: The AjaxMethod "Class" is not defined

I have an older asp.net project that utilizes Ajax.AjaxMethod() to invoke server-side code from Javascript. It used to function properly, but now it has suddenly ceased to work. Here is the C# code behind: public partial class Signup : System.Web.UI.Page ...

Versel TurboRepo is facing an issue during the installation of the expo router, causing a conflict

Utilizing TurboRepo for building a monorepo and experimenting with the react-native-web example to kickstart a full expo react-native-web implementation. I'm facing difficulties installing expo-router correctly within the native project. Despite thor ...

Organizing React State Arrays

I am struggling to organize an array of objects stored in a React hook state. After sorting, this array is passed to a FlatList component. const { notifications } = useContext(MainContext); const [sortedNotifications, setSortedNotifications] = useState([]) ...

Determining the file path relative to the project/src directory in Node.js

Currently, in my node.js project I am utilizing log4js and aiming to include the file name where the log record was added. However, when using __filename, it provides me with the absolute path. var logger = log4js.getLogger(__filename) This results in lo ...

Using the Google Identity Services JavaScript SDK in conjunction with Vue and TypeScript: A comprehensive guide

I am currently working on authorizing Google APIs using the new Google Identity Services JavaScript SDK in my Vue / Quasar / TypeScript application. Following the guidelines provided here, I have included the Google 3P Authorization JavaScript Library in ...

JavaScript's jQuery selector retrieves a child element from one location and adds it to a different

Why does the Jquery children selector select the img element, extract it, remove it, and then append it to another div element? Shouldn't it create a copy of the element being appended? var $anchors = $("#imageGallery a"); var $overlay = $('&l ...

What is preventing me from renaming a file in PHP when passed through jQuery?

Hello to all users! I've encountered an issue where I can't seem to change the file name in PHP that is being passed from jQuery: Here is the JavaScript code where I pass the file to the PHP handler: var url = '/temp.php'; var xhr = ...

tips on waiting for the outcome of an http request (synchronous http request, utilizing http request as a promise)

My TypeScript service loads base data through HTTP requests from a server. The requests are for various data, arranged in order from independent data to data that depends on other data. Due to the asynchronous nature of HTTP requests, there is no guarant ...

If the element is checked and equal to a specific value, take action

I am trying to hide one of the 3 radio buttons on my page. Although they all have the same class, each button has a different value. I attempted to write code to achieve this, but unfortunately, it is hiding all radio buttons instead of just one. Could s ...

React: Transforming mongoDB date format into a more user-friendly date display

An entry saved in MongoDB contains a property called "createdAt" with a timestamp. Take a look at the example below: createdAt: 2021-10-26T12:24:33.433+00:00 If we consider this date to be today, how can I achieve the following outcomes?: Show this date ...

This function named error is implemented in native code

My website is built in C# using asp.net. When the Onchange() event is triggered on the Dropdownlist, I call this jQuery function which displays an error: function error(){[native code]} <script type="text/javascript"> function GetDescription ...

Managing the Loading Sequence of CSS Files in Nuxt and Vuetify

I am facing an issue in my Nuxt/Vuetify application where I cannot seem to load my custom CSS file after Vuetify's CSS. Despite attempting to change the order in the CSS array like so: css: [ '~/assets/style/main.scss', '~/asse ...

When using Javascript to append content to the body, it may not be displayed as HTML on

My current project involves creating an HTML document through JavaScript templates. In the code snippet below, I have a const button which serves as my template. By using the replace method, I am able to update the content within the button template from c ...