Search code examples
next.jsenvironment-variablestsconfig

How can i organize .env files in Nextjs project?


.env files works just fine in Root directory but I want to organize all env files in to one folder like below.

ProjectRoot
└ env
  └ .env.development
  └ .env.local
(...)

But Nextjs doesn't read varialble from the forder.

I tried adding env path to tsconfig.json

{
  "compilerOptions" : { (...) },
  "include" : [
    (...),
   "env/.env*"
  ],
  (...)
}

didn't work..

This is my package.json and next.config.js file.

// package.json
{
  (...),
  "dependencies": {
    "@emotion/react": "^11.10.4",
    "@emotion/styled": "^11.10.4",
    "@mui/icons-material": "^5.10.9",
    "@mui/material": "^5.10.9",
    "axios": "^1.1.3",
    "babel-preset-next": "^1.4.0",
    "cross-env": "^7.0.3",
    "next": "12.3.1",
    "next-translate": "^1.6.0",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "react-icons": "^4.6.0",
    "react-markdown": "^6.0.0",
    "react-spring": "^9.0.0",
    "react-syntax-highlighter": "^15.5.0",
    "react-use-measure": "^2.1.1",
    "react-wordcloud": "^1.2.7",
    "rehype-raw": "^6.1.1",
    "styled-components": "^5.3.6",
    "styled-reset": "^4.4.2",
    "swr": "^1.3.0"
  },
  "devDependencies": {
    "@svgr/webpack": "^6.5.0",
    "@types/node": "18.8.4",
    "@types/react": "18.0.21",
    "@types/react-dom": "18.0.6",
    "@types/react-syntax-highlighter": "^15.5.5",
    "@types/styled-components": "^5.1.26",
    "babel-plugin-styled-components": "^2.0.7",
    "eslint": "8.25.0",
    "eslint-config-next": "12.3.1",
    "typescript": "4.8.4"
  }
}

// next.config.js
const nextConfig = {
  reactStrictMode: true,
  swcMinify: true,
  trailingSlash: true,
  webpack: (config) => {
    config.module.rules.push({
      test: /\.svg$/i,
      issuer: /\.[jt]sx?$/,
      use: ["@svgr/webpack"],
    });
    return config;
  },
};

module.exports = nextConfig;

Any helps?


Solution

  • You can use dotenv-webpack npm package.

    In next.cnfig.js

    const Dotenv = require('dotenv-webpack');
    
    module.exports = {
        webpack(config) {
            config.plugins.push(new webpack.Dotenv({
             path: './yourNewEnvDirectory',
              }))
            return config
        }
    }