How to use dotenv for Environment Variable Management In Next.js
Step 1: Setting Up a NextJS Project:
npx create-next-app my-next-app
cd my-next-app
Step 3: Install Dependencies using the following command:
npm install dotenv
Project Structure:
After installation the dependencies will be updated in package.json:
"dependencies": {
"dotenv": "^16.4.5",
"next": "14.2.2",
"react": "^18",
"react-dom": "^18"
},
Step 4: Set Up Environment Variables
# .env.local
API_URL=http://localhost:3000/workout
Example: Below is an example to Handle Environments in a NextJS app.
// next.config.mjs
import dotenv from 'dotenv';
dotenv.config();
const config = {
env: {
API_URL: process.env.API_URL,
},
};
export default config;
// src/api/api.js
const fetchUserData = async () => {
const apiUrl = process.env.API_URL;
const response = await fetch(`${apiUrl}`);
const data = await response.json();
return data;
};
export default fetchUserData;
import React, {
useState,
useEffect
} from 'react';
const Home = () => {
const [apiContent, setApiContent] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch(process.env.API_URL);
if (response.ok) {
const data = await response.json();
setApiContent(data);
} else {
throw new Error('Failed to fetch API data');
}
} catch (error) {
console.error('Error fetching API data:', error);
}
};
fetchData();
}, []);
return (
<div>
<h1>Welcome to my Next.js App</h1>
{apiContent ? (
<div>
<h2>API Content</h2>
<pre>{JSON.stringify(apiContent, null, 2)}</pre>
</div>
) : (
<p>Loading API content...</p>
)}
</div>
);
};
Start your application using the following command:
npm run dev
Output:
How to Handle Different Environments in a Next.js?
Environment variables in NextJS are fundamental settings or values that can change based on the application’s deployment environment. They are crucial for separating sensitive information, such as API keys, database credentials, or configuration details, from the application codebase.
In a NextJS project, managing environment variables is essential for handling sensitive information and configuring applications across different deployment environments.
Table of Content
- Understanding Environment Variables in NextJS
- Setting Up Environment Variables in NextJS
- Using dotenv for Environment Variable Management
- Best Practices for Managing Environment Variables in NextJS
- Conclusion