admin管理员组文章数量:1399823
i just trying Next Js 13 middleware feature. But i confuse how to passing data from middleware to ponents/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 ponents/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 ponents/page/api?. im trying like this
return NextResponse.next({tes: "tes"})
but i can't find how to get that data from ponents/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()
}
i just trying Next Js 13 middleware feature. But i confuse how to passing data from middleware to ponents/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 ponents/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 ponents/page/api?. im trying like this
return NextResponse.next({tes: "tes"})
but i can't find how to get that data from ponents/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()
}
Share
Improve this question
edited May 21, 2023 at 15:31
juliomalves
50.6k23 gold badges178 silver badges169 bronze badges
asked Feb 3, 2023 at 3:57
SurezluvySurezluvy
931 silver badge4 bronze badges
2 Answers
Reset to default 7I only found one way that by request.header
middleware.ts:
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
// This function can be marked `async` if using `await` inside
export function middleware(request: NextRequest) {
console.log('middleware.ts, request.url:', request.url)
const headers = new Headers(request.headers);
headers.set('middlewareSet', 'mydata');
const resp = NextResponse.next({
request: {
headers
}
});
return resp;
}
// See "Matching Paths" below to learn more
export const config = {
matcher: '/user/server',
}
/user/server/page.tsx
import { headers } from 'next/headers'
export default function Server() {
const headersList = headers()
const middlewareSet = headersList.get('middlewareSet')
return (
<div>
<p>middlewareSet: {JSON.stringify(middlewareSet)}</p>
<p>headersList: {JSON.stringify(headersList)}</p>
</div>
)
}
The next.js version is 13.4.1, using app router.
I have the same problem. It should have a simpler approach in Next.js server-side rendering to pass variables from middleware to child ponents.
Just something like:
export async function middleware(req: NextRequest) {
const data = 'Hello from middleware!';
req.someData= data;
return NextResponse.next();
}
本文标签: javascriptHow to passing data from middleware to componentsapi in Next Js 13Stack Overflow
版权声明:本文标题:javascript - How to passing data from middleware to componentsapi in Next Js 13? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744186665a2594320.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论