Next.js Tutorial
Selected Reading
- Next.js - Discussion
- Next.js - Useful Resources
- Next.js - Quick Guide
- Next.js - CLI
- Next.js - Deployment
- Next.js - Environment Variables
- Next.js - Typescript
- Next.js - Response Helpers
- Next.js - API MiddleWares
- Next.js - API Routes
- Next.js - Shallow Routing
- Next.js - Imperitive Routing
- Next.js - Dynanic API Routes
- Next.js - Routing
- Next.js - Pre-Rendering
- Next.js - Global CSS Support
- Next.js - CSS Support
- Next.js - Meta Data
- Next.js - Static File Serving
- Next.js - Pages
- Next.js - Environment Setup
- Next.js - Overview
- Next.js - Home
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Next.js - Environment Variables
Next.js - Environment Variables
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](/nextjs/images/env.jpg)