这是我的中间件.ts文件。我可以确认它被击中并做了所有它应该做的事情:
// packages/webapp/middleware.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import jwt from 'jsonwebtoken'
export async function middleware(request: NextRequest) {
const requestHeaders = new Headers(request.headers)
const authorizationHeader = requestHeaders.get('authorization')
const bearerToken = authorizationHeader?.split(' ')[1]
const decodedToken = jwt.decode(bearerToken!)
if (typeof decodedToken !== 'object' || decodedToken === null) {
return new NextResponse(
JSON.stringify({ success: false, message: 'Authentication failed' }),
{ status: 401, headers: { 'content-type': 'application/json' } }
)
}
const response = NextResponse.next({
request: {
headers: requestHeaders,
},
})
response.headers.set('x-user-id', decodedToken.user_id)
return response
}
// See "Matching Paths" below to learn more
export const config = {
matcher: '/api/:path*',
}
字符串
在我的API中,我有:
// src/app/(authenticated)/conversations/api/route.ts
import { Conversation } from "common/types/db";
import { NextResponse } from "next/server";
import { v4 as uuidv4 } from 'uuid';
export async function GET(request: Request) {
console.log('headers', request.headers)
console.log('userId', request.headers.get('x-user-id'))
const conversations = ...
return NextResponse.json({ data: conversations })
}
型
但我没有设置x-user-id
。我做错了什么?我正在使用Next.js 13和App Router。
1条答案
按热度按时间hrirmatl1#
在创建响应之前设置头对我来说是有效的。如下所示:
字符串