Next.js instrumentation behaves differently with conditional extracted to variable
This issue came from an earlier issue I created, which was resolved, but the underlying behaviour is so baffling I'm desparate to know what is going on.
Next.js has an experimental feature called Instrumentation that allows code to be run on boot-up. It seems to run both server-side and client-side, so a special check is necessary if nodejs-dependent imports are to be used. I have working code that uses this functionality:
export async function register() {
if (process.env.NEXT_RUNTIME === 'nodejs') {
const os = await require('os');
console.log(os.hostname());
}
}
However, the following code does not work:
export async function register() {
const isServer = process.env.NEXT_RUNTIME === 'nodejs'
if (isServer) {
const os = await require('os');
console.log(os.hostname());
}
}
The error is:
- error ./instrumentation.ts:12:21
Module not found: Can't resolve 'os'
10 | const isServer = process.env.NEXT_RUNTIME === 'nodejs'
11 | if (isServer) {
> 12 | const os = await require('os');
| ^
13 | console.log(os.hostname());
14 | }
15 | }
Obviously I can use the first one and be happy. But can anyone explain why the second fails? Perhaps something involving tree shaking, or caching, or...?
Comments
Post a Comment