The Nextjs middleware file seems to be idling without executing any code

Recently, I delved into NextJs and NextAuth while working on a page accessible to admins only. I came across the intriguing concept of a "middleware.ts" file, which is supposed to run a function for each specified route. However, I encountered an issue where my minimalistic console log in the file doesn't seem to display anything in the browser's inspect tool or the terminal.

import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";

export function middleware(request: NextRequest) {
  console.log("MIDDLEWARE EXECUTED FROM: ", request.url);

  return NextResponse.next();
}

export const config = {
  matcher: "/((?!api|_next/static|_next/image|favicon.ico).*)",
};

Additionally, the file is named middleware.ts and can be found in the root directory. I have been grappling with this issue for the past three days and would greatly appreciate any assistance.

Answer №1

Incorporating NextAuth into your project and looking to include middleware functions? Within the middleware.ts file, you can insert code similar to the following example:

import { withAuth } from "next-auth/middleware";
import { NextRequest, NextResponse } from "next/server";

function removeContentLengthIfTransferEncoding(req: NextRequest) {
  if (req.headers.get("transfer-encoding")) {
    req.headers.delete("content-length");
  }
}

export default withAuth(
  function middleware(req) {
    removeContentLengthIfTransferEncoding(req);

    const value = req.nextauth.token;
    if (!value && req.nextUrl.pathname.startsWith("/admin/")) {
      return NextResponse.rewrite(new URL("/login", req.url));
    }
  },
  {
    callbacks: {
      async authorized({ token }) {
        if (!token) {
          return false;
        }

        // // `/me` only requires the user to be logged in
        return !!token;
      },
    },
    pages: {
      signIn: "/login",
    },
  },
);

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

If you decide to implement middleware apart from NextAuth, be aware that two middleware functions may run simultaneously. For more information, refer to https://next-auth.js.org/configuration/nextjs

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 are the steps to resolve the "EADDRINUSE: address already in use :::3000" error in an integration test?

While testing my simple endpoint using jest and superTest in my TypeScript project, I encountered the listen EADDRINUSE: address already in use :::3000 error. The file app.ts is responsible for handling express functionalities and it is the one being impo ...

How to Nest Interfaces in TypeScript

I'm just starting to learn about Angular and I am having trouble getting the interface class to work properly. export interface Header { parentTitles: string; childHeaders: ChildHeader[]; titleIcon: string; url: string; } export interf ...

Vue-Apollo - The 'value' property is not present in the 'Readonly<Ref<Readonly<any>>>' type

MY CURRENT DILEMMA: In my quest to seamlessly integrate vue-apollo v4 with Typescript, I have encountered a challenge. I am in the process of retrieving data from a simple query using useQuery along with useResult. The default return type of useResult i ...

Asynchronously retrieving data in .NET using Angular

Initially, I am attempting to retrieve all projects from the database based on the provided userId from the URL. This operation is performed in the ngOnInit() lifecycle hook. Each project contains a field named Languages, which represents a list of objec ...

Disabling Firebase error logging for unsuccessful signInWithEmailAndPassword attempts

My current project involves setting up a login system using Firebase auth in NextJS. Strangely, when I call the login function with incorrect credentials, an error is logged to the console even though my catch statement for handling errors is empty. Is the ...

Guide on setting up an API route in Next.js to efficiently transmit a CSV file to the frontend

From what I understand (please correct me if I'm mistaken), the usual process for downloading a file involves the frontend making a call to an API route, with most of the operations occurring on the server side. My current task involves reading data ...

What is the best way to pass an array as a parameter in Angular?

I have set up my routing module like this: const routes: Routes = [ { path: "engineering/:branches", component: BranchesTabsComponent }, { path: "humanities/:branches", component: BranchesTabsComponent }, ]; In the main-contin ...

Encountering a Next.js Strapi error. TypeError: Fetch request unsuccessful

An error occurred during module build: UnhandledSchemeError: The plugin does not support reading from "node:assert" URIs (Unhandled scheme). Webpack natively supports "data:" and "file:" URIs. You might require an extra plugin to handle "node:" URIs. ...

The Kubernetes cluster unexpectedly closes down following a period of processing

My GCP cluster is hosting a NodeJS server. The server functions flawlessly when run locally, but mysteriously stops without any error messages when I attempt to send a post request to a specific route. This post request is supposed to trigger the sending o ...

Retrieving information in NextJS using getServerSideProps yields a Promise with a status of {<pending>}

I'm facing an issue while trying to retrieve data in NextJS using getServerSideProps within my component. All it returns is Promise {}. I'm unsure about what mistake I might be making. Here's the snippet of my code: const MyHomeComponent = ( ...

The data type 'string | undefined' cannot be assigned to the data type 'string' when working with .env variables

Trying to integrate next-auth into my nextjs-13 application, I encountered an error when attempting to use .env variables in the [...nextauth]/route.ts: Type 'string | undefined' is not assignable to type 'string'. https://i.stack.im ...

Evaluating Angular/Typescript and its capabilities

I seem to be struggling with the concept of how eval functions in TypeScript/Angular. Can someone provide some guidance on how to make eval work in this scenario? Although the logic may not be perfect in this demo program, I just need help figuring out how ...

Avoid accessing invariant variables when mocking: __extends

I'm currently in the process of converting a collection of react components from JavaScript to TypeScript, and I've encountered an issue with jest.mock(). Before: "react": "^15.6.1" "jest": "20.0.4" "enzyme": "^2.9.1" CustomDate.js ... import ...

Having trouble retrieving an Enum within an Angular template?

I am trying to use an enum to read a property of an array. However, I encountered an error with the following code: <ng-container *ngFor="let elem of list"> <div class="ui-g-12 ui-sm-12 ui-md-12 ui-lg-12 ui-xl-12"> &l ...

Tips for showcasing unique keywords in Ace Editor within the Angular framework

Can anyone help me with highlighting specific keywords in Angular using ace-builds? I've tried but can't seem to get it right. Here's the code snippet from my component: Check out the code on Stackblitz import { AfterViewInit, Component, ...

Incorporating Firebase administrator into an Angular 4 project

Currently encountering an issue while trying to integrate firebase-admin into my angular project. Despite my efforts, I am unable to resolve the error that keeps popping up (refer to the screenshot below). https://i.stack.imgur.com/kdCoo.png I attempted ...

Leveraging the power of NestJS in conjunction with Apollo Server version 2

I recently delved into learning nestjs and decided to give this graphql example a try. The issue I encountered is that the example was originally designed for apollo-server version 1, and I'm having difficulty adapting it to work with apollo-server v ...

NextJS: Apply middleware specifically for /pages route

Recently, there has been a change in the middleware functionality which you can read about at https://nextjs.org/docs/messages/middleware-upgrade-guide. Now, the middleware is also triggered by requests for /_next and /favicon.ico. What is the most effic ...

The art of connecting models in Angular 2

Hey there! I've got a setup that seems to be giving me some unexpected results. Whenever I make changes to either the Kelvin or Celsius field, I end up with strange outputs like multiplying by 1000 or other inexplicable numbers. I'm new to Angula ...

Deactivate the rows within an Office UI Fabric React DetailsList

I've been attempting to selectively disable mouse click events on specific rows within an OUIF DetailsList, but I'm facing some challenges. I initially tried overriding the onRenderRow function and setting CheckboxVisibility to none, but the row ...