Photo by Eric Er on Unsplash

Next.js has built-in support for loading environment variables from .env.local into process.env.

.env.local
DB_HOST=localhost
DB_USER=myuser
DB_PASS=mypassword
// you can use variables
HOSTNAME=localhost
PORT=8080
HOST=http://$HOSTNAME:$PORT
pages/index.js
export async function getStaticProps() {
const db = await myDB.connect({
host: process.env.DB_HOST,
username: process.env.DB_USER,
password: process.env.DB_PASS,
})
// You cannot use destructuring, it will fail:
// const { NEXT_PUBLIC_PUBLISHABLE_KEY } = process.env.
// ...
}

By default all environment variables loaded through .env.local are only available in the Node.js environment, meaning they won’t be exposed to the browser. In order to expose a variable to the browser you have to prefix the variable with NEXT_PUBLIC_

pages/index.js
import setupAnalyticsService from '../lib/my-analytics-service'
// NEXT_PUBLIC_ANALYTICS_ID can be used here as it's prefixed by NEXT_PUBLIC_
setupAnalyticsService(process.env.NEXT_PUBLIC_ANALYTICS_ID)
function HomePage() {
return <h1>Hello World</h1>
}
export default HomePage

Note: .env, .env.development, and .env.production files should be included in your repository as they define defaults. .env*.local should be added to .gitignore, as those files are intended to be ignored. .env.local is where secrets can be stored.

Search articles

Type a word to search published articles.

Open the search page