1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 23:28:02 +00:00

Add Match Middleware On Groups Of Paths as a Next.js TIL

This commit is contained in:
jbranchaud
2024-01-27 17:25:12 -06:00
parent 11d32fad0d
commit f6882f9fec
2 changed files with 37 additions and 1 deletions

View File

@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
_1364 TILs and counting..._
_1365 TILs and counting..._
---
@@ -599,6 +599,7 @@ _1364 TILs and counting..._
- [Create Files And Directories For Dynamic Routes](nextjs/create-files-and-directories-for-dynamic-routes.md)
- [Define URL Redirects In The Next Config](nextjs/define-url-redirects-in-the-next-config.md)
- [Make Environment Variable Publicly Available](nextjs/make-environment-variable-publicly-available.md)
- [Match Middleware On Groups Of Paths](nextjs/match-middleware-on-groups-of-paths.md)
- [Push A Route With A URL Object](nextjs/push-a-route-with-a-url-object.md)
- [Redirect An Unauthorized User](nextjs/redirect-an-unauthorized-user.md)
- [Remove A Query Param From The URL](nextjs/remove-a-query-param-from-the-url.md)

View File

@@ -0,0 +1,35 @@
# Match Middleware On Groups Of Paths
The Next.js middleware takes an array of path matchers in its config to decide
what pages to apply middleware to. These paths can use regex via
[`path-to-regexp`](https://github.com/pillarjs/path-to-regexp#path-to-regexp-1).
Let's say I'm using middleware to do authentication checks for certain pages.
If I want to visits to my `/dashboard` page to run through middleware, I can
configure my matcher like so:
```javascript
export const config = { matcher: ["/dashboard"] };
```
If we want to match against `/dashboard` and any possible sub-structure to that
path, we can apply some regex:
```javascript
export const config = { matcher: ["/dashboard/:all*"] };
```
That will match `/dashboard`, `/dashboard/hello`, `dashboard/hello/world`, etc.
Lastly, let's say I only want to match routes under the `/dashboard` route. I
can replace the `*` (zero-or-more matches) with a `+` (one-or-more matches):
```javascript
export const config = { matcher: ["/dashboard/:all+"] };
```
That will match `/dashboard/hello`, `/dashboard/hello/world`, etc., but not
`/dashboard`.
[source](https://nextjs.org/docs/app/building-your-application/routing/middleware)