dotenv + nextjs


  • administrators

    新版NextJS(我用的是V9)是支持dotenv的。
    只需要:

    npm install dotenv
    

    然後在next.config.js裡加入一行:

    require("dotenv").config();
    

    無需很多過時的網絡教程說的要通過webpack把env導入config裡。
    但是要注意:

    • PORT = 5000 不能用 - 好像next.config.js是在APP運行後才加載的,那是默認3000已經定了
    • dotenv是服務器端的事,因為它要從文件系統裡讀取.env 所以你可能需要publicRuntimeConfig.
    • publicRuntimeConfig 不能和 target:serverless合用。
      我現在的next.config.js如下:
    const withPlugins = require("next-compose-plugins");
    const css = require("@zeit/next-css");
    
    require("dotenv").config();
    
    const nextConfig = {
      // target: "serverless",
      webpack(config) {
        config.module.rules.push({
          test: /\.(png|svg|eot|otf|ttf|woff|woff2)$/,
          use: {
            loader: "url-loader",
            options: {
              limit: 8192,
              publicPath: "/_next/static/",
              outputPath: "static/",
              name: "[name].[ext]"
            }
          }
        });
        return config;
      },
      publicRuntimeConfig: {
        // Will be available on both server and client
        API_HOST: process.env.API_HOST
      }
    };
    
    module.exports = withPlugins([[css]], nextConfig);
    

    在page/*.js下讀取publicRuntimeConfg 是這樣的: (有點麻煩)

    import getConfig from "next/config";
    const { publicRuntimeConfig } = getConfig();
    const authenticate = e => {
        e.preventDefault();
        if (username != "" && password != "") {
          axios
            .post(publicRuntimeConfig.API_HOST + "/authentication", {
              strategy: "local",
              email: username,
              password: password
            })
            .then(function(response) {
              console.log(response);
              signIn(username);
            })
            .catch(function(error) {
              console.log(error);
              setMessage("Invalid Login");
            });
        } else {
          setMessage("Please enter your username and password");
        }
      };
    

  • administrators

    其實在next.config.js裡加env,這個值會在build的時候被用上。

    const withPlugins = require("next-compose-plugins");
    const css = require("@zeit/next-css");
    
    // require("dotenv").config();
    
    const nextConfig = {
      target: "serverless",
      webpack(config) {
        config.module.rules.push({
          test: /\.(png|svg|eot|otf|ttf|woff|woff2)$/,
          use: {
            loader: "url-loader",
            options: {
              limit: 8192,
              publicPath: "/_next/static/",
              outputPath: "static/",
              name: "[name].[ext]"
            }
          }
        });
        return config;
      },
      env: {
        API_HOST: "http://www.localhost:3030"
      }
      // publicRuntimeConfig: {
      //   // Will be available on both server and client
      //   API_HOST: process.env.API_HOST
      // }
    };
    
    module.exports = withPlugins([[css]], nextConfig);
    

    這樣更好。
    注意使用"now"來部署是serverless,所以用不了publicRuntimeConfig。


  • administrators

    https://gist.github.com/robksawyer/83df60e6ea85d500dceab1e6d9f9b491

    const nextConfig = {
      distDir: '_next',
      // serverRuntimeConfig: { // Will only be available on the server side
      //   wordpressApiUrl: process.env.WORDPRESS_API_URL
      // },
      // publicRuntimeConfig: { // Will be available on both server and client
      //   staticFolder: '/public',
      //   port: 8081 // The server port
      // },
      // pageExtensions: ['jsx', 'js'],
      // Removes the [BABEL] Note: The code generator has deoptimised the styling of
      compact: true,
    

  • administrators