I've been experimenting with the Next Js 13 middleware feature and I'm a bit confused about how to pass data from the middleware to components/pages/api.
For example, when trying to pass payload data or determine who the currently logged-in user is.
In the past, without using the middleware feature, I would create a middleware file and if jwt verification was successful, I would send/pass the payload data to my components/api like this:
import {example} from 'middleware/example'
const payload = await example(req, res)
However, with the Next Js 13 feature, after reading the docs, I only found examples of how to send responses like:
return new NextResponse(
JSON.stringify({
success: false,
message: 'authentication failed'
}),
{ status: 401, headers: { 'content-type': 'application/json' } }
)
If I use that method, it will return json data and not continue the middleware chain. If I try:
return NextResponse.next()
It will continue the middleware chain, but then how do I pass my payload data to components/pages/apis? I attempted something like this:
return NextResponse.next({tes: "test"})
But I couldn't figure out how to retrieve that data in my components/pages/api.
This is an excerpt from my middleware code:
if (request.nextUrl.pathname.startsWith('/api/posts')) {
const requestHeaders = new Headers(request.headers)
const authorization = requestHeaders.get('authorization')
if (!authorization) {
return new NextResponse(
JSON.stringify({
success: false,
message: 'authentication failed'
}),
{ status: 401, headers: { 'content-type': 'application/json' }
)
}
const authSplit = authorization.split(' ')
const [authType, authToken] = [
authSplit[0],
authSplit[1]
]
if (authType !== 'Bearer') {
return new NextResponse(
JSON.stringify({
success: false,
message: 'authentication failed'
}),
{ status: 401, headers: { 'content-type': 'application/json' } }
)
}
const payload = await verify(authToken)
if (!payload) {
return new NextResponse(
JSON.stringify({
success: false,
message: 'authentication failed'
}),
{ status: 401, headers: { 'content-type': 'application/json' } }
)
}
return NextResponse.next()
}