Hello Sunil

How to Use .env Files in Vite and Next.js: A Complete Guide for Environment Variables

In modern web development, managing environment variables securely is crucial for both security and flexibility. Whether you’re building a Vite or Next.js app, environment variables allow you to store sensitive information (like API keys or URLs) separate from your code.

In this guide, we’ll walk you through how to use .env files in both Vite and Next.js to make your apps more secure and maintainable.

.env files are plain text files that contain environment-specific variables. These variables help configure your application in different environments (such as development, production, or staging) without hardcoding sensitive information into your code.

For example:

  • API keys
  • Database URLs
  • Authentication tokens

These values are typically loaded into your application at runtime, which makes .env files a great way to securely store configuration data.

  • Security: You can store sensitive things like API keys and passwords in the .env file without showing them in your code.
  • Separation of Concerns: Different configurations for development, testing, and production environments can be managed separately.
  • Easy Configuration: It’s easy to update configuration settings across your app by simply changing the .env file, without touching the code.

Let’s say we’re building a simple Vite app that fetches data from an API using an environment variable for the API URL.

Step 1: Create a Vite Project

If you haven’t already created a Vite project, you can do so by running:

npm create vite@latest my-vite-app --template react
cd my-vite-app
npm install

Step 2: Create .env File

At the root of the project, create an .env file with the following content:

VITE_API_URL=https://api.example.com

💡 Environment-Specific .env Files

Vite supports environment-specific .env files for different build environments:

  • .env (default, applied to all environments)
  • .env.development (applied during development)
  • .env.production (applied during production)

Example: .env.development

VITE_API_URL=https://dev.api.example.com

Example: .env.production

VITE_API_URL=https://prod.api.example.com

Step 3: Access Environment Variables in Code

In your App.js (or wherever you want to use the variable), you can access the API URL as follows:

function App() {
  
  const apiUrl = import.meta.env.VITE_API_URL;

  fetch(apiUrl + "/data")
    .then((response) => response.json())
    .then((data) => {
      console.log(data);
    })
    .catch((error) => console.error("Error fetching data:", error));

  return (
    <>
      <h1>Hello</h1>
    </>
  );
}

export default App;

Step 4: Add .env to .gitignore

To prevent sensitive information from being committed to version control, include .env in your .gitignore file:

.env

Step 5: Run the Application

Start the development server:

npm run dev

When you access the app, it will use the VITE_API_URL variable from the .env file to make an API request.

Next.js is a powerful framework that also supports environment variables. Here’s how to use .env files in Next.js:

1. No Specific Prefix Required: In Next.js, environment variables do not require a specific prefix by default for server-side use. However, to expose them to the client, you must prefix them with NEXT_PUBLIC_.

Example .env file:

NEXT_PUBLIC_API_URL=https://api.example.com
API_SECRET_KEY=your_secret_key_here

Access Variables:

  • For client-side variables:
const apiUrl = process.env.NEXT_PUBLIC_API_URL;
console.log("API URL:", apiUrl);
  • For server-side variables:
const secretKey = process.env.API_SECRET_KEY;
console.log("Secret Key:", secretKey);

2.Environment-Specific Files: Next.js supports environment-specific .env files for different build environments:

  • .env (default, applied to all environments)
  • .env.development (applied during development)
  • .env.production (applied during production)

3.Restart the Server: Restart the Next.js server when .env files are updated.

Now, let’s create a Next.js app that uses both a client-side and a server-side environment variable.

Step 1: Create a Next.js Project

If you don’t have a Next.js app already, create one by running:

npx create-next-app@latest my-next-app
cd my-next-app
npm install

Step 2: Create .env File

In the root of your Next.js project, create an .env file with the following content:

NEXT_PUBLIC_API_URL=https://api.example.com
API_SECRET_KEY=supersecretkey123
  • NEXT_PUBLIC_API_URL will be accessible on the client side (because it’s prefixed with NEXT_PUBLIC_).
  • API_SECRET_KEY will be available only on the server side (because it doesn’t have the NEXT_PUBLIC_ prefix).

Step 3: Use Environment Variables in Code

Client-Side Access:

In the App Router, you typically work with React Server and Client Components.

To access the variable in a Client Component, use process.env.NEXT_PUBLIC_.

Here’s an example of a Client Component (app/page.js):

'use client';

import { useEffect, useState } from 'react';

export default function HomePage() {
  const [data, setData] = useState(null);

  useEffect(() => {
    const apiUrl = process.env.NEXT_PUBLIC_API_URL;

    fetch(`${apiUrl}/data`)
      .then(response => response.json())
      .then(data => setData(data))
      .catch(error => console.error('Error fetching data:', error));
  }, []);

  return (
    <div>
      <h1>Home Page</h1>
      <p>Data from API:</p>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
}

Server-Side Access:

1.Using in Server Components

If you’re working with a Server Component (default in the App Router), you can directly access the variable like this:

//app/dashboard/page.js
export default function DashboardPage() {
  const apiSecretKey = process.env.API_SECRET_KEY; // Server-side variable

  return (
    <div>
      <h1>Dashboard</h1>
      <p>Server-Side Secret Key: {apiSecretKey}</p>
    </div>
  );
}

Kindly note, while you can render the secret variable for debugging purposes, never expose sensitive values like API keys in production.

2.Using in API Routes

You can use environment variables in API routes to perform server-side logic without exposing secrets to the client.

// app/api/get-secret/route.js
export async function GET(request) {
  const secretKey = process.env.API_SECRET_KEY;

  return new Response(
    JSON.stringify({ message: "Server-Side Secret Accessed", secretKey }),
    { status: 200, headers: { "Content-Type": "application/json" } }
  );
}

To test this, start your app and visit /api/get-secret. The API will securely return the secret key.

3. Using in Server Actions

If you’re using Server Actions (a feature in the App Router), you can use environment variables in these functions.

// app/dashboard/actions.js
export async function fetchSecretData() {
  const secretKey = process.env.API_SECRET_KEY;

  // Use the secret key for server-side operations
  return `Server processed data with key: ${secretKey}`;
}

Then use it in a Server Component:

// app/dashboard/page.js
import { fetchSecretData } from './actions';

export default async function DashboardPage() {
  const data = await fetchSecretData();

  return (
    <div>
      <h1>Dashboard</h1>
      <p>{data}</p>
    </div>
  );
}

Step 4: Run the Application

Start the development server:

npm run dev

When you visit http://localhost:3000, the client-side fetch request will use the NEXT_PUBLIC_API_URL, while the secret key is safely used server-side.

  • Do Not Commit .env Files: Always add .env to your .gitignore file to avoid exposing sensitive information in version control.
  • Use Different .env Files for Different Environments: Maintain different .env files for development, production, and testing to handle various settings in different stages of your app’s lifecycle.

Using .env files properly enhances security, scalability, and maintainability in React projects.

Whether you’re building a small app or a large-scale project, this approach will help ensure that your environment variables are handled in the best way possible.

Quick Summary:

Vite:

  • You create an .env file with VITE_ prefixed variables.
  • In the code, you use import.meta.env to access the variables.

Next.js:

  • You create an .env file with NEXT_PUBLIC_ prefixed variables for client-side access.
  • You access server-side variables without the NEXT_PUBLIC_ prefix using process.env.

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Similar articles you may like

Sunil Pradhan

Hi there 👋 I am a front-end developer passionate about cutting-edge, semantic, pixel-perfect design. Writing helps me to understand things better.

Add comment

Stay Updated

Want to be notified when our article is published? Enter your email address below to be the first to know.

Sunil Pradhan

Hi there 👋 I am a front-end developer passionate about cutting-edge, semantic, pixel-perfect design. Writing helps me to understand things better.