English 中文(简体)
Next.js - Environment Variables
  • 时间:2024-09-17

Next.js - Environment Variables


Previous Page Next Page  

Next.js, has support for pubpshing 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.


DB_HOST=localhost
DB_USER=tutorialspoint
DB_PASS=nextjs

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

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
extjs
> next

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

Verify Output

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

Environment Variables Advertisements