Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to detect Production or Dev environment in NextJs?

Tags:

next.js

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
}
like image 306
agastya teja Avatar asked Nov 11 '20 19:11

agastya teja


2 Answers

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
}
like image 83
manuelkruisz Avatar answered Nov 07 '22 05:11

manuelkruisz


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>
...
like image 37
Stefan Becker Avatar answered Nov 07 '22 05:11

Stefan Becker