Next.js - Environment Variables


Next.js, has support for publishing environment variables in node which we can use in connecting to server, database etc. For this, we need to create .env.local file in root directory. We can also create .env.production.

Create .env.local

Create .env.local in root directory with the following contents.


Create env.js

Create a page named env.js with following contents in pages/posts directory where we'll use the environment variables using process.env.

import Head from 'next/head'
import Container from '../../components/container'

export default function FirstPost(props) {
   return (
               <title>Environment Variables</title>
            <h1>Database Credentials</h1>
               <p>Host: {}</p>
               <p>Username: {props.username}</p>
               <p>Password: {props.password}</p>

export async function getStaticProps() {
   // Connect to Database using DB properties
   return {
      props: { 
         host: process.env.DB_HOST,
         username: process.env.DB_USER,
         password: process.env.DB_PASS

Now start the server.

Next.JS will detect .env.local and show follwing message on console.

npm run dev

> nextjs@1.0.0 dev D:\Node\nextjs
> next

ready - started server on http://localhost:3000
info  - Loaded env from D:\Node\nextjs\.env.local
event - compiled successfully
wait  - compiling...
event - compiled successfully
event - build page: /posts/env
wait  - compiling...
event - compiled successfully

Verify Output

Open localhost:3000/posts/env in a browser and you will see the following output.

Environment Variables