In some cases, it may be necessary to have different behavior for a website or app during development compared to its production/live version. Next.js provides an easy way to achieve this by leveraging the value of process.env.NODE_ENV
, which is automatically set to 'development'
when running the application with npm run dev
.
For instance, let’s say we have an API route that should not be publicly accessible. To address this, we can include the following code at the top of the route:
if (process.env.NODE_ENV !== 'development') return null;
With this check in place, the route will not work in production, effectively limiting access only to the development environment.
Similarly, we can apply the same approach to a page component by rendering a blank page when accessed in production:
{
process.env.NODE_ENV === 'development' && <div>hi</div>
}
By wrapping the JSX code in the above condition, the component will only display the “hi” message during development mode.
These techniques allow us to add specific features or behavior during development, while ensuring that they remain hidden in production. By using Next.js and harnessing the power of process.env.NODE_ENV
, we can easily differentiate between the two modes and tailor our code accordingly.