Nextjs:如何将 jwt 令牌附加到每个 API 调用的标头

Jar*_*red 6 authentication jwt axios next.js

我正在尝试将我的应用程序移植CRANextJs,但有一件事阻止了我:

我必须将身份验证令牌标头附加到数百个 API 调用中的每一个调用中。

我的身份验证流程非常简单,我使用/authenticate用户名和密码调用我们的 Express 服务器 API,它返回一个 JWT 令牌。然后,我需要将该令牌与标头中的所有连续 API 调用一起传递。

我需要一种方法将其附加到中间件或其他东西中,这样我就不必手动将其添加到每个 api 调用中。

在我的 CRA 应用程序中,我axios为此使用了拦截器。

这是我的设置:( 但NextJs 13使用pages,而不是/app dir

Iron-Session版本6

axios最新的

我在我的middleware.ts

import { getIronSession } from 'iron-session'
import { sessionOptions } from './lib/session'
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'

export async function middleware(request: NextRequest) {
    // Clone the request headers and set a new header `x-hello-from-middleware1`
    const res = NextResponse.next()
    const session = await getIronSession(request, res, sessionOptions)
    const requestHeaders = new Headers(request.headers)
    requestHeaders.set('x-hello-from-middleware1', 'hello')
    requestHeaders.set('Authorization', session.user?.jwt || '')

    // You can also set request headers in NextResponse.rewrite
    const response = NextResponse.next({
        request: {
            // New request headers
            headers: requestHeaders
        }
    })

    // Set a new response header `x-hello-from-middleware2`
    response.headers.set('x-hello-from-middleware2', 'hello')
    return response
}

Run Code Online (Sandbox Code Playgroud)

但这给了我这个错误:

error - (middleware)/node_modules/@peculiar/webcrypto/build/webcrypto.es.js (9:0) @ new SubtleCrypto
error - The edge runtime does not support Node.js 'crypto' module.

Run Code Online (Sandbox Code Playgroud)

我还尝试了在互联网上找到的其他一些随机想法。但我无法让它发挥作用。我也尝试过使用Next-Auth,但也无法获得良好的解决方案(这是我最后一次尝试如何将 Axios 拦截器与 Next-Auth 一起使用

那么,是否每个使用 Next 的人都手动将身份验证令牌附加到他们的每一个 API 调用中?我是唯一需要这样做的人吗?这是我第二次尝试将 CRA 转换为下一个,但 auth 再次阻止了我。我没有与iron-session或使用middleware.ts结婚,任何帮助表示赞赏。