Next.js Discord

Discord Forum

Instrumentation.ts behaves differently with code that is logically identical

Unanswered
Red ant posted this in #help-forum
Open in Discord
Red antOP
I'm using the experimental instrumentation feature to run code when my server runs: https://nextjs.org/docs/app/building-your-application/optimizing/instrumentation

Here is the contents of my instrumentation.ts file, that causes a crash when I run next:
export async function register() {
    const isServer = process.env.NEXT_RUNTIME === "nodejs";
    if (isServer) {
        const os = await import("os");
    }
}

Here is the error. It appears to be trying to include server-side code (e.g. os) when it is not available:
- wait compiling /instrumentation (client and server)...
- error ./src/instrumentation.ts:8:25
Module not found: Can't resolve 'os'
   6 |     const isServer = process.env.NEXT_RUNTIME === "nodejs";
   7 |     if (isServer) {
>  8 |         const os = await import("os");
     |                         ^
   9 |     }
  10 | }
  11 | 


However, this works fine:
export async function register() {
    if (process.env.NEXT_RUNTIME === "nodejs") {
        const os = await import("os");
    }
}


The two versions of the code are logically identical. Is something being tree shaken? Or cached? Why would there be a difference?

1 Reply

Red antOP
i really want to know what is going on here!!