Unraveling the Magic of .env Files: Your Friendly Guide to Custom Variables in Next.js

·

3 min read

Have you ever found yourself in a situation where, amidst coding enthusiasm and focus, you accidentally committed an API key or secret onto GitHub? Most developers can relate to this scenario. Thankfully, ".env" files in Next.js React can save us from such blunders.

Introducing the .env File: Your Secret Keeper

Think of .env files as hidden vaults, safeguarding your top-secret info like API keys and database credentials. They protect your data from sneaky commit leaks on GitHub.

The Rules of .env Files in Next.js

  • Your .env file's hideout should be at the root of your project. Don't try to place them elsewhere; they're crafty and won't be found.
  • Next.js has different costumes for the .env files based on their environment:
    • .env: Standard attire for all environments.
    • .env.local: Local disguise. Seen in all environments except 'test.'
    • .env.development, .env.test, .env.production: Specific attire for each environment.
    • .env.development.local, .env.test.local, .env.production.local: Local disguise for specific environments.
  • Name your variables starting with the REACT_APP_ prefix for the mission.

Decoding the NEXT_PUBLIC_ prefix

When using Next.js, variables can only be accessed in the Node.js environment unless you include a prefix of either NEXT_PUBLIC_ or REACT_APP_. Doing so lets you regulate which data remains on the server side and which is sent to the browser.

Here's an illustration:

# .env file
API_KEY_SERVER=12345678    # Only Node.js can see this
NEXT_PUBLIC_API_KEY_CLIENT=87654321  # Node.js and the browser can see this

Deploying Your Secret Variables

Once you've given your variables their correct aliases, you can deploy them using the process.env gadget provided by Node.js. Here's an example:

You have these defined in your .env file:

# .env file
REACT_APP_API_URL=https://api.mywebsite.com
NEXT_PUBLIC_SITE_NAME=MyCoolWebsite

You can then deploy these in your React components:

// SomeReactComponent.js
import React from 'react';

const SomeReactComponent = () => {
  return (
    <div>
      <h1>Welcome to {process.env.NEXT_PUBLIC_SITE_NAME}!</h1>
      <p>We fetch data from: {process.env.REACT_APP_API_URL}</p>
    </div>
  );
};

export default SomeReactComponent;

Custom TypeScript Script and .env.local

In Next.js, the .env.local file is meant to store environment variables that are specific to your local development environment. When you run next dev, Next.js automatically loads the environment variables from .env.local and makes them available in your application.

However, suppose you are trying to access these environment variables from a custom TypeScript script (outside your Next.js application). In that case, it won't be able to read them directly because the next CLI is not involved in running the custom script. The custom TypeScript script is a separate entity unaware of Next.js' environment variables.

Suppose you want your custom TypeScript script to access the environment variables from .env.local. In that case, you can use a package like dotenv, which loads the variables from the .env.local file and makes them available to your script.

Here's how you can do it:

Step 1: Install the dotenv package:

npm install dotenv --save

Step 2: Create a dotenv configuration file in your project (e.g., dotenv-config.ts) and add the following code:

import dotenv from 'dotenv';

// Load environment variables from .env.local file
dotenv.config({ path: '.env.local' });

// Now you can access the environment variables using process.env
const myVariable = process.env.MY_VARIABLE;

Conclusion

These variables will transform into their actual values at build time. They offer flexible disguise options for different environments like development, testing, and production.

So, there you have it—an easy, secure, and flexible way to manage your secrets in Next.js React. Keep your secrets safe and happy coding. Have you ever found yourself in a situation where, amidst coding enthusiasm and focus, you accidentally committed an API key or secret onto GitHub? Most developers can relate to this scenario. Thankfully, ".env" files in Next.js React can save us from such blunders.