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.
config = { runtime: 'nodejs' }
is ignored locally, and setting it at top level is ignored too. – Gunnery