rsnext/examples/middleware-matcher/README.md
Damien Simonin Feugas 866de41681
docs: documents middleware matcher (#40180)
### 📖 What's in there?

Middleware matchers are powerful, but very few people realized it, because they are not really documented.
This PR tries to bring more clarity, and includes a more advanced example.

The example shows how to exclude several pages (no `/static`, no `/public`), but also allow specific page in excluded paths (`/public/disclaimer`)

### 🧪 How to test?

Run the example: `pnpm next dev examples/middleware-matcher`, then browse to http://localhost:3000
The first 3 links should not match, the last 3 ones should.

Don't forget to clear your localhost cookies if you change the middleware code.

### 🆙 Note to reviewers

Using session cookies to pass information from middleware to the rendered page is not great, because `document.cookie` is not available during SSR, and because cookies persist when refreshing the page (making it hard to try different matchers)

However, I couldn't find a simpler way to convey the information from the middleware to the page, and I meant to have something visual. The other option is to use response headers and curl commands, but...
2022-09-05 13:36:09 +00:00

1.7 KiB
Executable file

Middleware

This example shows how to configure your Next.js Middleware to only match specific pages.

The index page (pages/index.js) has a list of links to dynamic pages, which will tell whether they were matched or not.

The Middleware file (middleware.js) has a special matcher configuration key, allowing you to fine-grained control matched pages.

Please keep in mind that:

  1. Middleware always runs first
  2. Middleware always matches _next routes on server side
  3. matcher must always starts with a '/'

Deploy your own

Deploy the example using Vercel:

Deploy with Vercel

How to use

Execute create-next-app with npm, Yarn, or pnpm to bootstrap the example:

npx create-next-app --example middleware-matcher middleware-matcher-app
yarn create next-app --example middleware-matcher middleware-matcher-app
pnpm create next-app --example middleware-matcher middleware-matcher-app

Deploy it to the cloud with Vercel (Documentation).