Environment Variables in Next.js
Oct 17, 2021
Today I was trying to use environment variables inside a Next.js project, and it is really easy to work with.
Let’s take a look.
Steps to work with Environment Variables
Create a .env.local
file inside the root of your project.
Then put your private keys inside the file in this format:
// .env.local
API_KEY="...."
Save the file and add it to the .gitignore
file.
// .gitignore
.env*.local
Access your keys with process.env
. You can access your environment variables inside the pages
directory or while you are fetching data with the getServerSideProps
function.
export const getServerSideProps = async () => {
console.log(process.env.API_KEY); const res = await fetch(`${server}/api/?key=${process.env.API_KEY}`)
const articles = await res.json() return {
props: {
articles,
},
}
}
Hope it helps!