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
Add a ment  | 

2 Answers 2

Reset to default 7

I 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