After updating next.config, the NextJS + NextAuth middleware doesn't seem to be triggered

I'm currently utilizing

<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b0ded5c8c49dd1c5c4d8f0849e81889e87">[email protected]</a>
&
<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="056b607d714534362b">[email protected]</a>
, and I am facing an issue with my middleware.ts file. Despite several changes I've made, it has stopped working abruptly. All attempts to call it have been unsuccessful.

middleware.ts

import { withAuth } from "next-auth/middleware";

export default withAuth({
  callbacks: {
    authorized({ req, token }) {
      const { pathname } = req.nextUrl;
      console.log(token, pathname); // this log never comes
      if (pathname.startsWith("/admin")) {
        return token?.roleLabel === "ADMIN" || token?.userRole === "admin";
      }
      // `/me` only requires the user to be logged in
      return !!token;
    },
  },
});

export const config = {
  matcher: ["/admin/:path*", "/c/:path*", "/me"],
};

next.config.js

const { i18n } = require("./next-i18next.config");
const { PHASE_DEVELOPMENT_SERVER } = require("next/constants");

module.exports = (phase) => {
  let extensions = ['page.tsx', 'page.ts', 'page.jsx', 'page.js', 'api.ts', 'api.js']
  if (phase === PHASE_DEVELOPMENT_SERVER) extensions.push('doc.tsx')
  return {
    i18n,
    pageExtensions: extensions,
    images: {
      domains: ['domain.com'],
    },
  }
};

Should I consider renaming my middleware.ts file to middleware.page.ts? I attempted this, but it did not resolve the issue. The file is currently located in my root folder, and moving it to pages/ directory did not yield any positive results.

Authentication is functioning correctly on the React side, but I am unable to intercept all protected pages with the middleware. Assistance would be greatly appreciated.

Answer №1

I have discovered the solution to my problem.

After experimenting with various approaches, I realized that the issue was caused by the custom page extensions defined in next.config.js.

It appears that the pageExtensions configuration considers middleware as pages, so by renaming it to middleware.page.ts or middleware.api.ts in my situation, I was able to resolve the bug. It may seem counterintuitive, but surprisingly, it worked. It's possible that I overlooked something during my previous testing.

Just a friendly reminder that the middleware file must be located in the root folder.

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

Having trouble opening the prompt window by clicking on the button

I have been given an assignment to check if a given number is an Armstrong number. However, I am facing an issue where the prompt window does not appear when I click the button. This issue only arises when the rest of the function is written out. If the ...

Reactify TypeScript: Accurate typings for onChange event

How can I resolve the issues with types for target: { value: any, name: any }? The errors I encounter include Duplicate identifier 'any'. and Binding element 'any' implicitly has an 'any' type.. Additionally, why does the erro ...

A guide on utilizing Material UI Fade for smoothly fading in a component when a text field is selected

I am facing an issue with a text field input and a helper component. My goal is to have the helper component fade in when a user focuses on the input field. The helper component is wrapped as follows: <Fade in={checked}> <DynamicHelperText lev ...

Begin the API server along with the React server for your React application

I'm currently working on my first React app, and I'm facing a challenge in getting both the API and the React server to start simultaneously. For client routes, I am using react-router. In a previous project, I utilized Express for setting up th ...

Exploring Transformation in Angular

I am looking to enhance my understanding of how ChangeDetection works, and I have a query in this regard. When using changeDetection: ChangeDetectionStrategy.OnPush, do I also need to check if currentValue exists in the ngOnChanges lifecycle hook, or is i ...

Interfacing Electron Frontend with Python Backend through seamless communication

Upon completing the development of a Python CLI app, it became apparent that creating an Electron frontend for better user interaction was necessary. What is the best way for the Electron app to communicate with the Python app when a user action occurs on ...

Modifying the hue of Material UI tab label

I attempted to modify the label color of a tab to black, but it seems to be stuck as white. Is this color hard-coded in material-ui? If not, how can I change it? Here's what I've tried: const customStyles = { tab: { padding: '2p ...

"Extra loader required to manage output from these loaders." error encountered in React and Typescript

After successfully writing package 1 in Typescript and running mocha tests, I confidently pushed the code to a git provider. I then proceeded to pull the code via npm into package 2. However, when attempting to run React with Typescript on package 2, I enc ...

Passing an event from a layout component to a page in NextJS: A step-by-step guide

I'm currently working on a multi-step form using react-hook-form within Next.js. The onSubmit() event is located in a component called from the layout, and I want to implement functionality that adds a spinner and disables the submit button when onSub ...

generate a fresh array with matching keys

Here is an example array: subjectWithTopics = [ {subjectName:"maths", topicName : "topic1 of maths " }, {subjectName:"maths", topicName : "topic2 of maths " }, {subjectName:"English", topicName : &quo ...

What is the best way to convert this into a distinct function using typescript?

Is there a way to create a single method in Protractor or Webdriver API that can get the browser width and height? const getWindowWidth = async () => { const size = await browser.manage().window().getSize(); return size.width; }; I need this metho ...

Import .vue single file component into PHP application

I've been struggling to integrate a .vue single file component into my php app without using the inline template method. Since I don't have a node main.js file to import Vue and require the components, I'm not sure how to properly register m ...

Issue with converting string to Date object using Safari browser

I need to generate a JavaScript date object from a specific string format. String format: yyyy,mm,dd Here is my code snippet: var oDate = new Date('2013,10,07'); console.log(oDate); While Chrome, IE, and FF display the correct date, Safari 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 ...

Listening to React events on multiple elements in an array

When my React render function is running, it ends up rendering a group of elements: data.map((element) => { return <Object onChange={this.onObjectChange} />; }); I'm wondering, what is the best approach to determine which specific object ...

What is the best approach to structure a React project in which a component's rendering changes with each instance?

I am facing a challenge with rendering a component that relies on multiple AJAX calls to complete. These AJAX responses return different data each time, and I want to implement a button that will trigger the re-rendering of this random component every time ...

Issues with Markdown text editor code, table, and list functionalities are causing malfunction

Looking for a solution to use markdown editor for writing blog posts? If you're facing issues with code blocks, list items, tables, etc., not working correctly after publishing your markdown-based posts, while other elements like images, links, and bo ...

The console experienced a forced reflow when a tooltip appeared on the slider handle while executing JavaScript

I am currently facing an issue with my web page that includes various elements along with the Ant.design slider. The values of the slider are being controlled through React states. However, I have noticed that when the slider tooltip is enabled, the respon ...

The 'type' property is not found on the 'never' type

There seems to be a typescript error showing up as Error: Property 'type' does not exist on type 'never' in the following code snippet: export const getSomething = (actionLog: [] | undefined) => { console.info(actionLog[length ...

Generate steps using Material UI/React Stepper to create organized pages (similar to Table Pagination)

As I venture into using Material UI along with React, my goal is to create organized "pages" consisting of steps in sets of four for a specific process. My initial attempt displayed all 10 steps on a single view, despite having the pagination correctly ca ...