Using Environment Variables in Next.js
This article was AI-drafted and has not been reviewed yet. Spotted a mistake? Tell us.
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.
Ready for more? Optional paid resources that pick up where this lesson leaves off.
Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.
Project-based next.js courses if you want a structured paid path after the free lessons. Wait for a sale — prices drop often.
Browse on Udemy →Search Amazon for next.js books — check the publication year so the examples match current versions.
Search Amazon →