Reputation: 2563
Below is the code from package.json file
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
},
Below is my next.config.js file, here console.log always undefined
require("dotenv").config();
console.log(process.env.BASE_URL)
module.exports = {
env: {
API_BASE_URL: process.env.BASE_URL
},
reactStrictMode: true,
}
And this is in the .env.development
BASE_URL: 'http://localhost:3000'
When I ran the npm run dev command, it prints on terminal "Loaded env from /var/www/html/next/next-SC/.env.development"
So, why the console prints undefined always.
I'm using next js version "10.0.4"
Upvotes: 2
Views: 10956
Reputation: 1
in next.config.js
const { resolve,join } = require('path');
const {config} = require('dotenv');
let path=resolve('../')
config({ path: join(path,'.env') })
let MAIN_URL=process.env.NEXT_PUBLIC_BASE_URL_MAIN
console.log("MAIN_URL",MAIN_URL)
const nextConfig = {
reactStrictMode: true,
env: {
API_BASE_URL: MAIN_URL
},
}
module.exports = nextConfig
Upvotes: -1
Reputation: 610
I assume you are using React with nextjs. If not, then please disregard this answer. I am doing the same thing. React has built in support for env vars. All you need to do is to prefix REACT_APP to your environment vars. So, in your .env.development or .env.staging, etc., you can have REACT_APP_BASE_URL=https://blah.com. You can then access them in your app using process.env.REACT_APP_BASE_URL. Then to build based on environment, I have (I am using craco, you would just use your normal build command)
"build:nightly": "env-cmd -f .env.nightly craco build",
"build:nightly": "env-cmd -f .env.staging craco build",
"build:nightly": "env-cmd -f .env.beta craco build",
...
Upvotes: 1
Reputation: 6603
For development environment, name the file .env.development
, for production .env.production
.
Next.js has built-in loader for environment variables. So dotenv
or similar packages aren't needed. Just add the files. It will be loaded automatically (see documentation).
Upvotes: 0