|
| 1 | +export const config = { |
| 2 | + matcher: '/about/:path*', |
| 3 | +}; |
| 4 | + |
| 5 | +<JavaScript V8> |
| 6 | +Edge Middleware runs on the Edge Runtime, a runtime built on top of the |
| 7 | +V8 |
| 8 | + JavaScript engine. The Edge Runtime provides a subset of Web APIs for you to use when creating Middleware. This lightweight API layer is built to be performant and execute code with minimal latency. When writing Middleware, you can use any of the supported APIs from the Edge Runtime. |
| 9 | + |
| 10 | +Edge Middleware setup |
| 11 | +To add Middleware to your app, you need to create a middleware.ts or middleware.js file at the same level as your app or pages directory (even if you're using a src directory): |
| 12 | + |
| 13 | +my-project |
| 14 | +app |
| 15 | +middleware.ts |
| 16 | +package.json |
| 17 | +config object |
| 18 | +Middleware will be invoked for every route in your project. If you only want it to be run on specific paths, you can define those either with a custom matcher config or with conditional statements. |
| 19 | + |
| 20 | +While the config option is the preferred method, as it does not get invoked on every request, you can also use conditional statements to only run the Middleware when it matches specific paths. |
| 21 | + |
| 22 | +Match paths based on custom matcher config |
| 23 | +To decide which route the Middleware should be run on, you can use a custom matcher config to filter on specific paths. The matcher property can be used to define either a single path, or using an array syntax for multiple paths. |
| 24 | + |
| 25 | +Edge Middleware runs on every request by default. To run on specific paths instead, use the matcher property of the Middleware config object. Even when using path matching, Edge Middleware runs on all /_next/data/ requests for getServerSideProps and getStaticProps pages for the sake of consistency. For more information, review our docs on Edge Middleware API as well as the Next.js matcher docs. |
| 26 | +Match a single path |
| 27 | +middleware.ts |
| 28 | + |
| 29 | +export const config = { |
| 30 | + matcher: '/about/:path*', |
| 31 | +}; |
| 32 | +Match multiple paths |
| 33 | +middleware.ts |
| 34 | + |
| 35 | +export const config = { |
| 36 | + matcher: ['/about/:path*', '/dashboard/:path*'], |
| 37 | +}; |
| 38 | +Match using regex |
| 39 | +The matcher config has full regex support for cases such as negative lookaheads or character matching. |
| 40 | + |
| 41 | +Match based on a negative lookahead |
| 42 | +To match all request paths except for the ones starting with: |
| 43 | + |
| 44 | +api (API routes) |
| 45 | +_next/static (static files) |
| 46 | +favicon.ico (favicon file) |
| 47 | +middleware.ts |
| 48 | + |
| 49 | +export const config = { |
| 50 | + matcher: ['/((?!api|_next/static|favicon.ico).*)'], |
| 51 | +}; |
| 52 | +Match based on character matching |
| 53 | +To match /blog/123 but not /blog/abc: |
| 54 | + |
| 55 | +middleware.ts |
| 56 | + |
| 57 | +export const config = { |
| 58 | + matcher: ['/blog/:slug(\\d{1,})'], |
| 59 | +}; |
| 60 | +For help on writing your own regex path matcher, review Path to regexp. |
| 61 | + |
| 62 | +Match paths based on conditional statements |
| 63 | +middleware.ts |
| 64 | + |
| 65 | +TypeScript |
| 66 | + |
| 67 | +import { rewrite } from '@vercel/edge'; |
| 68 | + |
| 69 | +export function middleware(request: Request) { |
| 70 | + const url = new URL(request.url); |
| 71 | + |
| 72 | + if (url.pathname.startsWith('/about')) { |
| 73 | + return rewrite(new URL('/about-2', request.url)); |
| 74 | + } |
| 75 | + |
| 76 | + if (url.pathname.startsWith('/dashboard')) { |
| 77 | + return rewrite(new URL('/dashboard/user', request.url)); |
| 78 | + } |
| 79 | +} |
| 80 | +See the @vercel/edge documentation for more information on using the @vercel/edge package. |
| 81 | + |
| 82 | +config properties |
| 83 | +Property |
| 84 | +Type |
| 85 | +Description |
| 86 | +matcher |
| 87 | +string / string[] |
| 88 | +A string or array of strings that define the paths the Middleware should be run on |
| 89 | +Edge Middleware signature |
| 90 | +The Edge Middleware signature is made up of two parameters: request and context. The request parameter is an instance of the Request object, and the context parameter is an object containing the waitUntil method. Both parameters are optional. |
| 91 | + |
| 92 | +Parameter |
| 93 | +Description |
| 94 | +Next.js |
| 95 | +Other Frameworks |
| 96 | +request |
| 97 | +An instance of the Request object |
| 98 | +NextRequest |
| 99 | +Request |
| 100 | +context |
| 101 | +An extension to the standard |
| 102 | +Request |
| 103 | + object |
| 104 | +NextFetchEvent |
| 105 | +RequestContext |
| 106 | +Next.js Middleware comes with built in helpers that are based upon the native |
| 107 | +FetchEvent |
| 108 | +, |
| 109 | +Response |
| 110 | +, and |
| 111 | +Request |
| 112 | + objects. |
| 113 | + |
| 114 | +See the |
| 115 | +next/server |
| 116 | + documentation for more information. |
| 117 | + |
| 118 | +Next.js (/app) |
| 119 | +Next.js (/pages) |
| 120 | +Other frameworks |
| 121 | +middleware.ts |
| 122 | + |
| 123 | +TypeScript |
| 124 | + |
| 125 | +import { NextResponse } from 'next/server'; |
| 126 | +import type { NextRequest } from 'next/server'; |
| 127 | + |
| 128 | +// config with custom matcher |
| 129 | +export const config = { |
| 130 | + matcher: '/about/:path*', |
| 131 | +}; |
| 132 | + |
| 133 | +export default function middleware(request: NextRequest) { |
| 134 | + return NextResponse.redirect(new URL('/about-2', request.url)); |
| 135 | +} |
| 136 | +Request |
| 137 | +The Request object represents an HTTP request. It is a wrapper around the Fetch API Request object. When using TypeScript, you do not need to import the Request object, as it is already available in the global scope. |
| 138 | + |
| 139 | +Request Properties |
| 140 | +Property |
| 141 | +Type |
| 142 | +Description |
| 143 | +url |
| 144 | +string |
| 145 | +The URL of the request |
| 146 | +method |
| 147 | +string |
| 148 | +The HTTP method of the request |
| 149 | +headers |
| 150 | +Headers |
| 151 | +The headers of the request |
| 152 | +body |
| 153 | +ReadableStream |
| 154 | +The body of the request |
| 155 | +bodyUsed |
| 156 | +boolean |
| 157 | +Whether the body has been read |
| 158 | +cache |
| 159 | +string |
| 160 | +The cache mode of the request |
| 161 | +credentials |
| 162 | +string |
| 163 | +The credentials mode of the request |
| 164 | +destination |
| 165 | +string |
| 166 | +The destination of the request |
| 167 | +integrity |
| 168 | +string |
| 169 | +The integrity of the request |
| 170 | +redirect |
| 171 | +string |
| 172 | +The redirect mode of the request |
| 173 | +referrer |
| 174 | +string |
| 175 | +The referrer of the request |
| 176 | +referrerPolicy |
| 177 | +string |
| 178 | +The referrer policy of the request |
| 179 | +mode |
| 180 | +string |
| 181 | +The mode of the request |
| 182 | +signal |
| 183 | +AbortSignal |
| 184 | +The signal of the request |
| 185 | +arrayBuffer |
| 186 | +function |
| 187 | +Returns a promise that resolves with an ArrayBuffer |
| 188 | +blob |
| 189 | +function |
| 190 | +Returns a promise that resolves with a Blob |
| 191 | +formData |
| 192 | +function |
| 193 | +Returns a promise that resolves with a FormData |
| 194 | +json |
| 195 | +function |
| 196 | +Returns a promise that resolves with a JSON object |
| 197 | +text |
| 198 | +function |
| 199 | +Returns a promise that resolves with a string |
| 200 | +clone |
| 201 | +function |
| 202 | +Returns a clone of the request |
| 203 | +To learn more about the |
| 204 | +NextRequest |
| 205 | + object and its properties, visit the Next.js documentation. |
| 206 | + |
| 207 | +waitUntil |
| 208 | +The waitUntil() method is from the |
| 209 | +ExtendableEvent |
| 210 | + interface. It accepts a |
| 211 | +Promise |
| 212 | + as an argument, which will keep the function running until the Promise resolves. |
| 213 | + |
| 214 | +It can be used to keep the function running after a response has been sent. This is useful when you have an async task that you want to keep running after returning a response. |
| 215 | + |
| 216 | +The example below will send a response immediately, but will keep the function running for ten seconds, fetch an album and log it to the console. |
| 217 | + |
| 218 | +Next.js (/app) |
| 219 | +Next.js (/pages) |
| 220 | +Other frameworks |
| 221 | +middleware.ts |
| 222 | + |
| 223 | +TypeScript |
| 224 | + |
| 225 | +import { NextResponse } from 'next/server'; |
| 226 | +import type { NextFetchEvent, NextRequest } from 'next/server'; |
| 227 | + |
| 228 | +export const config = { |
| 229 | + matcher: '/', |
| 230 | +}; |
| 231 | + |
| 232 | +const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); |
| 233 | + |
| 234 | +async function getAlbum() { |
| 235 | + const res = await fetch('https://jsonplaceholder.typicode.com/albums/1'); |
| 236 | + await wait(10000); |
| 237 | + return res.json(); |
| 238 | +} |
| 239 | + |
| 240 | +export default function middleware( |
| 241 | + request: NextRequest, |
| 242 | + context: NextFetchEvent, |
| 243 | +) { |
| 244 | + context.waitUntil(getAlbum().then((json) => console.log({ json }))); |
| 245 | + |
| 246 | + return new NextResponse(JSON.stringify({ hello: 'world' }), { |
| 247 | + status: 200, |
| 248 | + headers: { 'content-type': 'application/json' }, |
| 249 | + }); |
| 250 | +} |
| 251 | +Context properties |
| 252 | +Property |
| 253 | +Type |
| 254 | +Description |
| 255 | +waitUntil |
| 256 | +(promise: Promise<unknown>): void |
| 257 | +Prolongs the execution of the function until the promise passed to waitUntil is resolved |
0 commit comments