在Next.js的app目录中设置自定义请求头似乎不起作用

oiopk7p5  于 2023-08-04  发布在  其他
关注(0)|答案(1)|浏览(137)

这是我的中间件.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。

hrirmatl

hrirmatl1#

在创建响应之前设置头对我来说是有效的。如下所示:

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" },
    });
  }

  requestHeaders.set("x-user-id", decodedToken.user_id); // 👈🏽

  // 👇🏽
  return NextResponse.next({
    request: {
      headers: requestHeaders,
    },
  });
}

字符串

相关问题