i just trying Next Js 13 middleware feature. But i confuse how to passing data from middleware to components/page/api.
For example i try to pass payload or who user is currently loggin.
Normally without middleware feature, i just make middleware file and if jwt verify true, i will send/pass payload data to my components/api
import {example} from 'middleware/example'
const payload = await example(req, res)
But if i using Next Js 13 feature and i read the docs, i just find how to send response like
return new NextResponse(
JSON.stringify({
success: false,
message: 'authentication failed'
}),
{ status: 401, headers: { 'content-type': 'application/json' } }
)
if i use that, it will return json data, and not continue the middleware chain, if i use
return NextResponse.next()
it will continue the middleware chain, but how do i passing my payload data to components/page/api?.
im trying like this
return NextResponse.next({tes: "tes"})
but i can’t find how to get that data from components/api.
This is 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()
}