intermediate#next.js#environment variables#security
Using Environment Variables in Next.js
Learn how to use environment variables in Next.js to store sensitive data.
Introduction to Environment Variables
Environment variables are used to store sensitive data, such as API keys and database credentials.
Step 1: Create a New Next.js Project
Create a new Next.js project using npx create-next-app my-env.
npx create-next-app my-env
cd my-env
Step 2: Create a .env File
Create a new file called .env in the root of your project.
# .env
API_KEY=YOUR_API_KEY
Step 3: Use Environment Variables in Your Code
Use the environment variables in your code.
// pages/index.js
import { useState, useEffect } from 'react';
const Home = () => {
const [data, setData] = useState([]);
const apiKey = process.env.API_KEY;
useEffect(() => {
fetch(`https://api.example.com/data?api_key=${apiKey}`)
.then((response) => response.json())
.then((data) => setData(data));
}, [apiKey]);
return (
<div>
{data.map((item) => (
<div key={item.id}>{item.name}</div>
))}
</div>
);
};
export default Home;
Conclusion
In this tutorial, you learned how to use environment variables in Next.js to store sensitive data.