12

I am struggling to load my .env file in my NextJS app. Here is my code:

My .env is in root /
My index.js is in /pages/index.js

Here is my index.js:

require("dotenv").config({ path: __dirname + '/../.env' })

import React, {Component} from 'react'
import Layout from '../components/layout'
import axios from 'axios'

class Import extends Component{

    uploadCSV = (evt) => {
        evt.preventDefault();

        const uploadURL = process.env.MY_UPLOAD_URL

        let data = new FormData(evt.target)

        axios.post(uploadURL, data, {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        }).then((res) => {
            console.log(res)
        })
    }

    render() {
        return (
            <div>
                <Layout title="Import Chatbot Intents" description="Import Chatbot Intents">
                    <form onSubmit={this.uploadCSV} name="import_csv" className="import_csv">
                        <h2>Import CSV</h2>
                        <div className="form-group">
                            <label htmlFor="csv_file">Upload file here: </label>
                            <input type="file" name="csv_file" id="csv_file" ref="csv_file" />
                        </div>
                        <div className="form-group">
                            <input type="hidden" id="customer_id" name="customer_id" ref="customer_id" value="1"/>
                            <button className="btn btn-success">Submit</button>
                        </div>
                    </form>
                </Layout>
            </div>
        )
    }
}

export default Import

I observe that I can print out .env content in render() function, but I cannot do that in uploadCSV function.

For your info:

  • using just require("dotenv").config() doesn't work
  • using require("dotenv").config({path: "../"}) doesn't work

Updated

My env-config.js:

module.exports = {
    'CSV_UPLOAD_URL': "http://localhost:3000/uploadcsv"
}

My babel.config.js:

const env = require('./env-config')
console.log(env)

module.exports = function(api){

  // console.log({"process": process.env})
  api.cache(false)

  const presets = [
    "next/babel",
    "@zeit/next-typescript/babel"
  ]

  const plugins = [

      "@babel/plugin-transform-runtime",
      [
        'transform-define',
        env
      ]
  ]

  return { presets, plugins }
}

My package.json

{
  "name": "Botadmin",
  "scripts": {
    "dev": "next -p 3001",
    "build": "next build",
    "start": "next start"
  },
  "dependencies": {
    "@babel/runtime": "^7.1.5",
    "@zeit/next-less": "^1.0.1",
    "@zeit/next-typescript": "^1.1.1",
    "@zeit/next-workers": "^1.0.0",
    "axios": "^0.18.0",
    "forever": "^0.15.3",
    "less": "^3.8.1",
    "multer": "^1.4.1",
    "next": "7.0.2",
    "nprogress": "^0.2.0",
    "papaparse": "^4.6.2",
    "react": "16.6.3",
    "react-dom": "16.6.3",
    "typescript": "^3.1.6",
    "worker-loader": "^2.0.0"
  },
  "devDependencies": {
    "@babel/plugin-transform-runtime": "^7.1.0",
    "babel-plugin-transform-define": "^1.3.0",
    "dotenv": "^6.1.0",
    "fork-ts-checker-webpack-plugin": "^0.4.15"
  }
}

The Error:

Module build failed (from ./node_modules/next/dist/build/webpack/loaders/next-babel-loader.js):

TypeError: Property property of MemberExpression expected node to be of a type ["Identifier","PrivateName"] but instead got "StringLiteral"

Jun Yu
  • 375
  • 1
  • 5
  • 21
Ellery Leung
  • 617
  • 3
  • 10
  • 23

5 Answers5

8

If you want to use env in Nextjs

  1. Install babel-plugin-transform-define
  2. create the env-config.js file and define your variables

    const prod = process.env.NODE_ENV === 'production'
    module.exports = {
     'process.env.BACKEND_URL': prod ? 'https://api.example.com' : 'https://localhost:8080'
    }
    
  3. Create the .babelrc.js file

    const env = require('./env-config.js')
    
    module.exports = {
     presets: ['next/babel'],
     plugins: [['transform-define', env]] 
    }
    
  4. Now you have access to the env in your code

     process.env.BACKEND_URL
    

Alternatives: next-env

Alex Munoz
  • 821
  • 8
  • 11
6

As of Next.js 9.4, there is a built-in solution for setting environment variables https://nextjs.org/docs/basic-features/environment-variables

remjx
  • 4,104
  • 3
  • 34
  • 32
  • 4
    BUYER BEWARE the next.js environment only supports "development" via `next dev` and "production". You cannot perform anything other than a production build with next.js environments - you may have more flexibility with the Vercel cloud but you have to pay for that. – Jacksonkr Jun 22 '21 at 21:29
3

Thanks for @Alex for the answer. Another way to solve the same problem is to install dotenv-webpack using npm install -D dotenv-webpack.

Once installed. edit next.config.js:

require('dotenv').config()
const Dotenv = require('dotenv-webpack')

const path = require('path')

const withTypescript = require('@zeit/next-typescript')
const withWorkers = require('@zeit/next-workers')
const withLess = require('@zeit/next-less')

module.exports = withWorkers(withLess(withTypescript({
    context: __dirname,
    generateEtags: false,
    entry: './pages/index.js',
    distDir: 'build',
    pageExtensions: ['js', 'jsx', 'ts', 'tsx'],

    cssModules: false,

    webpack: (config, options) => {

        config.plugins = config.plugins || []

        config.plugins = [
            ...config.plugins,

            // Read the .env file
            new Dotenv({
                path: path.join(__dirname, '.env'),
                systemvars: true
            })
        ]

        // Fixes npm packages that depend on `fs` module
        config.node = {
            fs: 'empty'
        }

        return config
    }
})))
Ellery Leung
  • 617
  • 3
  • 10
  • 23
  • Not sure why, but this one just doens't work when I try to run next build in gitlab ci, for example. The .env is there, locally it works and there...it is just empty if I try to console.log in next.config.js file. Any advice? – Eric Apr 19 '20 at 17:31
2

I know I'm a bit late, but, you can just install dotenv and use it inside of your next.config.js file

require("dotenv").config();

const environment = process.env.NODE_ENV || "dev";
Pilot Tt
  • 23
  • 3
2

if you need to replicate next.js env loading in other files (setupTests.ts, next-logger.config.js) do this:

const { loadEnvConfig } = require('@next/env')

loadEnvConfig(__dirname, true, {
  info: () => null,
  error: console.error,
})

Devin Rhode
  • 23,026
  • 8
  • 58
  • 72