beforeAll
This callback is executed before each middleware. It can be used to write cookies or execute some custom logic.
It must return a valid NextResponse
instance.
Note that you must use the res
param inside your middlewares to access the "mapped" version from beforeAll
Good Usage
middleware.ts
export default handlePaths([
{
path: "/a/b/:path*",
handler: (req, res) => {
console.log(res.cookies.get('my-cookie')?.value) // => '123'
return res
}
}
], {
beforeAll: (req, res) => {
res.cookies.set('my-cookie', 123.toString())
return res
}
})
Bad Usage
middleware.ts
export default handlePaths([
{
path: "/a/b/:path*",
handler: (req) => {
const res = NextResponse.next()
console.log(res.cookies.get('my-cookie')?.value) // => undefined
return res
}
}
], {
beforeAll: (req, res) => {
response.cookies.set('my-cookie', 123.toString())
return res
}
})
Example with redirect
middleware.ts
export default handlePaths([
{
path: "/old-path",
handler: (req, res) => {
console.log(res.cookies.get('my-cookie')?.value) // => '123'
const url = req.nextUrl.clone()
url.pathname = "/new-path"
return NextResponse.redirect(url, res)
}
}
], {
beforeAll: (req, res) => {
response.cookies.set('my-cookie', 123.toString())
return res
}
})