I want to basically detect whether the running environment is dev or production in Nextjs. Is there any straight forward way of doing this?
if(env == "dev"){
// do something
}
else if (env == "prod"){
// do something
}
Yes, this should work out of the box if you access env
via process.env.NODE_ENV
.
When you run your application via next dev
this will be development
While building your application and running next start
sets this variable to production.
Therefore this should work:
const env = process.env.NODE_ENV
if(env == "development"){
// do something
}
else if (env == "production"){
// do something
}
Basically the same solution, but I didn't want to pollute my code with the ugly conditional. So I factored it out into a simple module:
let inDevEnvironment = false;
if (process && process.env.NODE_ENV === 'development') {
inDevEnvironment = true;
}
export {inDevEnvironment};
and now I can just write in server code
import {inDevEnvironment} from '../lib/DevEnv';
...
<div>
{inDevEnvironment || /* ... production only code ... */}
</div>
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With