Next.js has built-in support for loading environment variables from .env.local into process.env.
DB_HOST=localhostDB_USER=myuserDB_PASS=mypassword
// you can use variablesHOSTNAME=localhostPORT=8080HOST=http://$HOSTNAME:$PORTexport 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_
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 HomePageNote: .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.