We now have a youtube channel. Subscribe!

Next.js | Environment Variables

Next.js Environment Variables


Hello folks! welcome back to a new section of our tutorial on Next.js. In this tutorial, we will be studying about Next.js Environment Variables.

Next.js supports publishing of environment variables in node which we can make use of to connect to server, database, etc. For this, we need to create a .env.local file in the root directory. We can create .env.production as well.

Create .env.local

Create .env.local in root directory using the following content -

DB_HOST=localhost
DB_USER=webdesigntutorialz
DB_PASS=nextjs

Create env.js

Create a page env.js via the below 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 (
      <>
         <Container>
            <Head>
               <title>Environment Variables</title>
            </Head>
            <h1>Database Credentials</h1>
               <p>Host: {props.host}</p>
               <p>Username: {props.username}</p>
               <p>Password: {props.password}</p>
         </Container>
      </>	  
   )
}

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
      }
   }
}

Start the Server

Next.js will detect .env.local and display the following 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

Output

Open http://localhost:3000/posts/env in a browser to see the following result -



Alright guys! This is where we are going to be rounding up for this tutorial. In our next tutorial, we are going to be studying about Next.js Deployment.

Feel free to ask your questions where necessary and we will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.

Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.

Thanks for reading and bye for now.

Post a Comment

Hello dear readers! Please kindly try your best to make sure your comments comply with our comment policy guidelines. You can visit our comment policy page to view these guidelines which are clearly stated. Thank you.
© 2022 ‧ WebDesignTutorialz. All rights reserved. Developed by Jago Desain