/

Next.js: How to Show Content in Development and Hide in Production

Next.js: How to Show Content in Development and Hide in Production

When developing a website using Next.js, you might come across a scenario where you want to display certain information only during the development stage on your local machine, but not on the deployed website. In this blog post, I will show you how to achieve this in a simple way.

The first step is to determine whether the website is running in development mode or not. To do this, we can make use of the process.env.NODE_ENV environment variable provided by Next.js. This variable is automatically set to “development” during development and “production” during production.

Here’s how you can check if the website is running in development mode:

1
const isDev = process.env.NODE_ENV === 'development';

In the above code, we are checking if the value of process.env.NODE_ENV is equal to “development” and storing the result in the isDev variable.

Once we have determined whether we are in development mode or not, we can conditionally render the content using a JavaScript if statement or a ternary operator. However, in this case, we can make use of the logical AND operator && to achieve a more concise and readable code.

Here’s an example of how you can conditionally render content only in development mode:

1
2
3
{isDev && (
<p>local only</p>
)}

In the code above, we are using the logical AND operator (&&) to conditionally render the <p> element only if the isDev variable is true. This means that the <p> element will only be rendered in the development environment and not in the production environment.

By following these steps, you can easily display information or components exclusively during the development phase and ensure they are hidden when the website is deployed.

Tags: Next.js, development, production, conditional rendering