Nextjs: how to append jwt token to headers of every API call
Asked Answered
J

1

6

I'm trying to port over my CRA app to NextJs , but there is ONE thing that is stopping me:

I would have to append auth token header to EVERY single one of my hundreds of API calls.

My auth flow is very simple, I call /authenticate with username and password to our Express server API and it returns a JWT token. I need to then pass that token with all of the successive API calls in the header.

I need a way to append it in a middleware or something so I dont have to manually add it to every api call.

In my CRA app i used axios interceptors for this.

Here is my setup: NextJs 13 (using pages though, not /app dir)

Iron-Session version 6

axios latest

I tried this in my 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
}

But this gives me this error:

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.

I've also tried some other random ideas I found on the internet. But i can't get it to work. I've also tried using Next-Auth but was unable to get a good solution with that as well (here's my last attempt how to use an Axios interceptor with Next-Auth )

So is every person using Next manually appending auth token to every single one of their API calls? Am i the only person who needs to do this? This is my second attempt to convert my CRA to next and auth is blocking me, again. I am not married to iron-session or using middleware.ts , any help appreciated.

Jamima answered 31/10, 2022 at 1:54 Comment(2)
Probably you have resolved the issue by now. But i think meaby you should retrieve the JWT from a cookie instead. Meaby?Outboard
I have a similar issue, I want to switch the middleware runtime to NodeJS (That would fix your issue too). But I can't seem to find any solution. config = { runtime: 'nodejs' } is ignored locally, and setting it at top level is ignored too.Gunnery
P
-1

You are aiming for client-side data fetching, which should be used for the trivial-generic usages (see image below and this documentation page

Try to switch service workers (see firebase's example) nextjs client fetching in documentation

Pyrargyrite answered 16/6, 2024 at 8:55 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.