如何在 Next Js 13 中将数据从中间件传递到组件/api?

Sur*_*uvy 6 javascript middleware next.js

我只是尝试 Next Js 13 中间件功能。但我很困惑如何将数据从中间件传递到组件/页面/api。

例如,我尝试传递有效负载或当前正在登录的用户。

通常没有中间件功能,我只是制作中间件文件,如果 jwt 验证为 true,我会将有效负载数据发送/传递到我的组件/api

import {example} from 'middleware/example'

const payload = await example(req, res)
Run Code Online (Sandbox Code Playgroud)

但是如果我使用 Next Js 13 功能并且阅读文档,我只是找到如何发送响应,例如

return new NextResponse(
  JSON.stringify({
    success: false,
    message: 'authentication failed'
  }),
  { status: 401, headers: { 'content-type': 'application/json' } }
)
Run Code Online (Sandbox Code Playgroud)

如果我使用它,它将返回 json 数据,并且不会继续中间件链,如果我使用

return NextResponse.next()
Run Code Online (Sandbox Code Playgroud)

它将继续中间件链,但我如何将有效负载数据传递到组件/页面/api?我想这样

return NextResponse.next({tes: "tes"})
Run Code Online (Sandbox Code Playgroud)

但我找不到如何从组件/api 获取该数据。

这是我的中间件代码

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()
    }
Run Code Online (Sandbox Code Playgroud)

hyy*_*010 3

我只找到了一种方法,通过 request.header

中间件.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',
}
Run Code Online (Sandbox Code Playgroud)

/用户/服务器/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>
  )
}
Run Code Online (Sandbox Code Playgroud)

next.js 版本是 13.4.1,使用应用程序路由器。