How can Next-auth handle redirection for 401 errors?

Currently, I am utilizing Next-auth in combination with rtk query. My goal is to configure the application so that whenever a request results in a 401 unauthorized error, the page will automatically redirect to the login page. How can this be achieved?

I attempted to include 'maxAge: 60' in the [...nextauth].js file and also utilized refetchInterval={30} along with refetchOnWindowFocus={true} in the component as potential solutions, but none of them seem to work as desired.

Answer №1

When utilizing rtk query, you have the ability to enhance your apiSlice baseQuery function to handle authentication errors and redirect accordingly. Here is a suggestion:

Begin by creating a base query that checks for specific error statuses such as 401:

// Attempt to execute the request, if it fails due to authorization issues, logout and redirect to login.
const baseQueryWithAuth: BaseQueryFn = async (args, api, extraOptions) => {
  const result = await baseQuery(args, api, extraOptions);
  if (result.error?.status === 403 || result.error?.status === 401) {
    // Unauthorized access, redirect to login page.
    // If JWT exists, update the access token here
    localStorage.removeItem(TOKEN_KEY_IN_LOCAL_STORAGE);
    Router.replace('/auth/login');
  }
  return result;
};

In the above code snippet, the removal of the token is referred to as a logout because the token is already invalid in the database, hence only deletion is necessary on the front-end without requiring an invalidate request.

The mentioned baseQuery can be implemented like so:

const baseUrl = `${process.env.NEXT_PUBLIC_API_PROTOCOL}://${process.env.NEXT_PUBLIC_API_HOST}/api`;
const TOKEN_KEY_IN_LOCAL_STORAGE = 'SavedToken';
const baseQuery = fetchBaseQuery({
  baseUrl,
  // credentials: 'include',
  prepareHeaders: (headers) => {
    // Retrieve the authentication token from local storage if available
    const token = localStorage.getItem(TOKEN_KEY_IN_LOCAL_STORAGE);
    if (token) {
      headers.set('Authorization', token);
    } else {
      Router.replace('/auth/login');
    }
    return headers;
  },
});

Once you have a functional base query with authentication support, you can proceed to create the main rtk query apiSlice for your project:

// Create API
export const apiSlice = createApi({
  baseQuery: baseQueryWithAuth,
  tagTypes: ['tag1', 'tag2', 'tag3'],
  endpoints: (_builder) => ({}),
});

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

Concerns with the performance of Leaflet's polyline

Currently using Leaflet version 1.0.3 and encountering an issue with GPS positions on my map. Within a for loop, I am creating circle markers for each GPS position: var position = new L.latLng(lat, lng); coordinates.push(position); L.circle([lat, lng], ...

Designing a custom HTML calendar

I am currently working on a school project where I am creating a calendar using HTML. So far, I have set up the basic structure of the page. What I want to achieve is a functional calendar where users can create appointments that will be displayed accordi ...

Make sure to properly check the size of the image before uploading it in express js

Below is the code I have written to verify if an image's size and width meet the specified criteria: im.identify(req.files.image,function (err,features) { //console.log(features); if(features.width<1000 ...

Is there a way to invert the orientation of an object within a canvas?

As I was experimenting with Javascript, I attempted to implement a feature where my 'Player' character would fall down after reaching a jumpDistance of 50. The idea was to simulate a small jump-like motion for the player. While the code may not ...

The Ajax response is not providing the expected HTML object in jQuery

When converting HTML data from a partial view to $(data), it's not returning the jQuery object I expected: console.log($(data)) -> [#document] Instead, it returns this: console.log($(data)) -> [#text, <meta charset=​"utf-8">​, #text ...

Code in JavaScript often includes the use of variables to store and manipulate data

Do these blocks of JavaScript code serve the same purpose? // First Code Sample var first = prompt("Enter the first number:"); var second = prompt("Enter the second number:"); var sum = Number(first) + Number(second); alert(sum); // Second Code Sample ...

I would love to hear your suggestions for a custom select element plugin in jQuery

After browsing multiple options online, I decided to turn to the expertise of the Stack Overflow community to ask for recommendations based on personal experience. I am specifically in search of a plugin that can substitute a select element with a custo ...

What do you call the syntax %< ... >%?

Observed zoomInAnimation : true, zoomOutScale : false, templateLegend : "<ul class=\"<%=type.toLowerCase()%>-legend\"><% for (var j=0; j<sections.length; j++){%><li><span style=\"background-color:<%=section ...

The utilization of 'fs' in the getInitialProps function is not permitted

Running into an issue while trying to access the contents of a parsed file within getInitialProps when my view loads. The error message "Module not found: Can't resolve 'fs'" is being displayed, and this has left me puzzled - especially cons ...

A textarea with a height of zero is still visible

My goal is to create collapsible widgets within a side panel on my webpage. Overall, the functionality works smoothly. I am able to adjust the height of child divs to 0px with a transition, causing them to disappear. However, I have run into an issue wher ...

Save the current date in the browser's localStorage

With jQuery Mobile 1.3, I successfully gathered and displayed values from input fields using localStorage through this function: <script type="text/javascript"> function datosCliente (info) { localStorage.setItem(info.name, info.valu ...

Uncovering the source of glitchy Angular Animations - could it be caused by CSS, code, or ng-directives? Plus, a bonus XKCD comic for some light-hearted humor

Just finished creating an XKCD app for a MEAN stack class I'm enrolled in, and I'm almost done with it. However, there's this annoying visual bug that's bothering me, especially with the angular animations. Here is the link to my deploy ...

Navigate forward to the next available input in a grid by using the tab key

My goal is to improve form entry efficiency by using the tab key to focus on the next empty input field within a grid component. If an input field already has a value, it will be skipped. For example, if the cursor is in input field 2 and field 3 is filled ...

Conceal particular table cells through jQuery

I am a beginner in the world of jQuery. My goal is to hide certain cells in a row when clicked, and have them displayed again when clicked once more. I've searched high and low for a solution, but all I find is how to hide entire rows. Here's an ...

Utilizing NextAuth to secure a protected API in Next.js

Struggling to build a NextJs Web application with NextAuth? I encountered an issue where the getSession function from NextAuth returns a null value when calling the API using getServerSideProps or getStaticProps. However, when I call the API inside a compo ...

Triggering multiple functions by clicking on the Icon

I'm trying to execute two different functions when the user clicks on the Icon, but I keep getting an error that says: Expected onClick listener to be a function, instead got a value of object type. Can someone please help me figure out what I am doin ...

New replacement for routerState.parent feature that has been deprecated in angular2

During my work with Angular 2 rc5, I encountered the following code snippet. this.router.routerState.parent(this.route).params.forEach((params: Params) => { url = params['url']; id = +params['id']; }); I had to resort to th ...

Display toolbar title on small screens in separate lines

Recently, I encountered an issue while using v-toolbar in my vue app. Despite my efforts, I couldn't find a way to split the title into multiple lines on small screens. Currently, it displays as "Secti...." on smaller devices. Can anyone assist me wit ...

Ways to provide input parameters to a method upon clicking an element without using the HTML onclick attribute

Is there a way to pass data between pages without redirecting to the next.php page every time a button is clicked? One suggestion is to remove the onclick attribute from the button: <button class="submit-btn"></button> and use this jQuery fu ...

Creating interactive routes and pages using Next.js and Prisma, embracing dynamic functionality

I have product information cards stored in my database, and I successfully display them on the user's page. Now, I want to add a "More Details" button on each card that will link to a new page (/pages/card/[id]). However, I'm unsure how to retrie ...