skip to Main Content

i have a app/middleware.ts but it didn’t trigger,

import { NextResponse, NextRequest } from 'next/server'
 
// This function can be marked `async` if using `await` inside
export function middleware(request: NextRequest) {
  return NextResponse.redirect(new URL('/home', request.url))
}
 
export const config = {
  matcher: '/about/:path*',
}

enter image description here

enter image description here

enter image description here

when i visit /about, it didn’t redirect to /home, do anyone know what is the problem? all the structure are shown on the pictures.

2

Answers


  1. middleware.ts should located in the root of your project. not the app directory

    Login or Signup to reply.
  2. For NextJs 14.x the middleware.js or middleware.ts file is used to define middleware that runs on the server before a request is fully processed.

    It allows you to alter the response based on the incoming request by performing actions like rewriting, redirecting, adjusting request or response headers, or even directly sending a response.

    To define middleware, use the middleware.js or middleware.ts file located in the root of your project. Such as at the same level as the app or pages directory, or inside the src folder if applicable.

    Example of possible folder and file structures:

    root level:

    project-root/
    │
    ├── app/
    │   ├── rest of the code 
    │
    ├── pages/
    │   ├── rest of the code 
    │
    ├── middleware.ts
    │
    └── package.json
    

    inside src folder:

    project-root/
    │
    ├── src/
    │   ├── app/
    │   │   ├── rest of the code 
    │   │
    │   ├── pages/
    │   │   ├── rest of the code 
    │   │
    │   ├── middleware.ts
    │
    └── package.json
    

    For more read the NextJs Docs.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search