NextJS: How can I create a server side request context

3.1k Views Asked by At

I need to forward a header from the browser to an external API I call from the server side.
The external API is called from getServerSideProps and API routes.

I was thinking about implementing some sort of a request context (using AsyncLocalStorage for example) that I can access from anywhere in the server side code.
That way I could create a middleware that will save the header to the context, and in the external API client I'll fetch it from the context and add it to the requests.

For example:

// context.ts
export const context = new AsyncLocalStorage<string>();
// middleware.ts
export function middleware(request: NextRequest) {
  const store = request.headers[SOME_HEADER];
  return context.run(store, () => NextResponse.next());
}
// client.ts
axios.post(EXTERNAL_API, DATA, {
  headers: {
    SOME_HEADER: context.getStore()
  }
}).then(...)

Currently I simply send it as a parameter which is pretty tedious.
Is there a way of achieving it?
I tried adding async_hooks to my project but it got really messy when I tried to build the project.

1

There are 1 best solutions below

0
On

Next.js 13, when using app directory, already implement a server context using AsyncLocalStorage. The headers function allows you to access this context to get a header from anywhere in your server-side React tree. The cache function lets you put custom values, I provide a more detailed answer in this similar question.