A comprehensive guide on utilizing matcher in Next JS middleware

Attempting to utilize a matcher in my Next.js middleware, but the documentation lacks detailed instructions on implementing this functionality.

The only information provided is the following code snippet, without clarification on where it should be placed or how to use the configuration in the middleware file:

export const config = {
  matcher: '/about/:path*',
}

Does anyone have a functional example of setting up the matcher for a middleware file in Next.js?

Appreciate any assistance. Thank you.

Answer №1

1.Step 1: Configuration Matching

To configure your middleware, you need to export an object named config from your middleware file:

middleware.js || middleware.ts

//middleware.js

export function middleware(request: NextRequest) {
  return NextResponse.redirect(new URL('/about-2', request.url))
}

export const config = {
  matcher: '/about/:path*',
}

2.File-Based Routing

|-- pages/
│   ├── auth/
│   │   ├── index.js
│   │   └── middlware.js(1)
│   |
│   |── index.js
|   |── middleware.js(2)
|__________________________


//middleware.js(1) will only run on /auth pages

//middleware.js(2) will run on all routes)

Answer №2

When I was learning this framework, I encountered the same issue. I am using nexjs version 12.2.0. To ensure that the middleware runs properly, you must place the middleware.ts or middleware.js file in the source directory and define the config matcher in it.

In Next.js 12.2, create a single file called middleware.ts in the root directory of your project (next to package.json):

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

export function middleware (request: NextRequest) {
  return NextResponse.next()
}

export const config = {
  matcher: ['/api/hello/:helloId'],
}

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 is the best method for navigating and passing data in dynamic routing with NEXT.JS?

In the process of developing my next.js ecommerce app, I am utilizing Firebase to fetch product data. My goal is to have users click on a product and be redirected to a new page displaying the details of that particular product. However, despite using the ...

NextJS introduces a unique functionality to Typescript's non-null assertion behavior

As per the typescript definition, the use of the non-null assertion operator is not supposed to impact execution. However, I have encountered a scenario where it does. I have been struggling to replicate this issue in a simpler project. In my current proj ...

Creating a realistic typewriter effect by incorporating Code Block as the input

I am looking to add a special touch to my website by showcasing a code segment with the Typewriter effect. I want this code block not only displayed but also "typed" out when the page loads. Unfortunately, I have been unable to find a suitable solution s ...

Having continual issues with OAuthCreateAccount error on Next.js with Next Auth using Google as the provider

I have successfully set up next-auth with the GoogleProvider on my local environment. However, when trying to run it in production, I encountered an OAuthCreateAccount error: api/auth/signin?error=OAuthCreateAccount The error message prompts me to "Try s ...

Integrating FCM with NextJs for enhanced push notification

I'm facing an issue while trying to integrate FCM with next.js. The error message states that there is a problem with registering the default service worker. Can anyone provide assistance regarding the next.config.js file? Encountered FirebaseError: M ...

The environmental factors in Turbo are crucial for optimizing performance

I'm having trouble accessing an environmental variable from my local .env file in one of my turbo packages. Every time I try to use it, it returns as undefined. My project is using Turbo to manage a monorepo and is built with Next.js/React/Typescript. ...

When attempting to launch a Next.js application, the status of the npm run dev command remains unchanged

I recently built a Next Js app using the command npx create-next-app. However, when I attempt to start the application with npm run dev, it gets stuck in the ready status indefinitely (refer to the attached image). No progress is made beyond this point De ...

Is there a way to customize Material UI's <Pagination> component to adhere to dark mode preferences?

I have implemented a Pagination component from Material-UI on my website. Although the control works perfectly fine, it does not adjust to dark mode, resulting in this visual: https://i.stack.imgur.com/hanyl.png The appearance of the Pagination tag is a ...

International component dominates over other elements

While working with the Next.js framework, I encountered an issue where the clipped drawer from MUI was obstructing other page contents. To address this, I decided to include the drawer component in the _app.tsx file as shown below: import '../styles/g ...

What is the best way to add a button over an image using Tailwind CSS in Next.js?

I've been trying to display a button on top of an image using Tailwind CSS and Next.js, but I'm having trouble getting it to align properly. Here is the code snippet I've been working with: <div> <Image src={projectAiWrite ...

Tips for including an ID as the final segment of a URL in next.js

I am attempting to have the ID as the last part of the URL, but I am unsure about the syntax. Can someone assist me with this code in Next.js? <Link href="query/{itm._id}"> {Items.map((itm) => ( <Link href="query/{itm. ...

Troubleshooting routing problems in a Next.js application hosted on Azure's static web app

I recently developed a Next.js application that connects to a database through an API in order to display data in the form of folder structures. If a row in the database is identified as a folder, it should be displayed as such, while if it is not, then it ...

How can we use SWR to fetch user data conditionally based on their logged-in state?

I am facing an issue with setting the UI state based on whether a user is logged in or not. The UI should display different states accordingly. I am currently using SSG for page generation and SWR for user data retrieval. However, I noticed that when call ...

What steps can be taken to resolve the error message "Module '../home/featuredRooms' cannot be found, or its corresponding type declarations"?

Upon deploying my site to Netlify or Vercel, I encountered a strange error. The project runs smoothly on my computer but seems to have issues when deployed. I am using TypeScript with Next.js and even attempted renaming folders to lowercase. Feel free to ...

What is the process for obtaining a client-side cookie using next.js?

I'm currently facing an issue where I can't seem to maintain a constant value for the isAuthenticated variable between server-side and client-side in next.js. In my setup, I am using a custom app.js file to wrap the app with Apollo Provider. The ...

I am looking to change the state of only the element that is being moused over in a React Hooks useState function, rather than changing the

Currently, I have a component from line 61-67 that controls the state of an editIcon. The issue is that it changes the state values for all items in the column, rather than just the specific item or row it should apply to. When hovering over a span element ...

Exploring the power of caching fetch requests with Next.js version 14

Currently, I am retrieving data from Contentful's API to display on my page.tsx files. The process works well, but it seems like the data is being over-cached. Although the content I'm pulling rarely changes, I'd like it to fetch new data ev ...

What causes the disparity in outcomes between an API request using node-fetch versus the built-in fetch in Node.js?

I developed a node application that sends an API request to place a bet on Manifold, a fictional betting website. Using node-fetch successfully triggers the bet, but when relying on the built-in fetch function, it sometimes returns an outdated version of ...

How can I download a PDF file in React.js using TypeScript on Next.js?

I've created a component to download a PDF file. The PDF file is named resumeroshan.pdf and it's located inside the Assets folder. "use client"; import resume from "/../../Assets/resumeroshan.pdf"; export default function Abo ...

In NextJs SSR, external components from a different package do not inherit styles when applied

I have incorporated an external react component into my Next.js app code. Here is a snippet of how the component appears: <AppBar className={clsx(classes.header)}> </AppBar> export const header = makeStyles((theme) => ({ header: { ...