简体   繁体   中英

Middleware does not work correctly in NextJS 13

I have the following middleware . I said when the URL is "/contact" or "/admin" or "/about" the middleware must run. but when I go to / or http://localhost:3000 the middleware fires. It must fire when the URL is "/contact" or "/admin" or "/about" .

Why?

import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'


export function middleware (request: NextRequest) {
  console.log(`Runs for '/contact' or '/admin' or 'about'`)
}

export const config = {
  matcher: ['/contact', '/admin','/about']
}

the structure of my pages folder

在此处输入图像描述

"next": "13.2.1"

NOTE:

It works in development and does not work in production

Make sure middleware.js file is on the same level where the package.json in next-13. Before it was inside pages directory with _middleware.js name

you could try this to see if this works.

export async function middleware(req, ev) {
  // showing the related code for your issue
  const { pathname } = req.nextUrl;

  if (pathname.includes("/contact") || pathname.includes("/admin")) {
    // for those routes add your logic
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM