The objects initialised in instrumentation.ts
are not available in the rest of the code (server side).
#84445
-
SummaryI am new to Next.JS and my previous experience is with Vite. Let's say I have a module called global-vars.ts with the following content: // global-vars.ts
const globalData = {}
export { globalData }; Then in my instrumentation.ts, I put some data in the // instrumentation.ts
import { globalData } from "./lib/global-vars";
export function register() {
Object.assign(globalData, { id: "test" });
console.log(globalData);
} Now the problem is that the content inside the variable import { NextResponse, NextRequest } from 'next/server'
import { globalData } from './global-vars';
// This function can be marked `async` if using `await` inside
export function middleware(request: NextRequest) {
console.log(globalData);
return Response.json({ message: 'Hello World' })
} writes In a normal Javascript/Typescript project, the state of a module is preserved when it is called at different places. So I wonder if I am doing something wrong here or this is the way Nest.JS works. Additional informationThe online documentation says that ExampleNo response |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
Just speaking to what's happening. If everything was running on the same thread, then it'd work, but there's different layers going on here. Some work is done inside workers, edge middleware is packed into a different environment, etc... |
Beta Was this translation helpful? Give feedback.
Btw, you can append stuff to
globalThis
, the problem is typically more with singletons, but if you did something like:And then in
instrumentation
:And then in your server component, you can do
console.log(globalThis.data)
and there'll be data, but doing this:I wouldn't rely this too much though. Middleware will also see the value. You can segment out by
pro…