next.js: Unable to import module 'now__launcher'

Bug report

Describe the bug

When trying to build and deploy to now, everything seems to build fine but at the end of the build process I get the following error:

Unable to import module 'now__launcher': Error
    at Function.Module._resolveFilename (module.js:547:15)
    at Function.Module._load (module.js:474:25)
    at Module.require (module.js:596:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/var/task/next.config.js:2:51)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)

To Reproduce

Steps to reproduce the behavior, please provide code snippets or a repository:

  1. Clone this repo https://github.com/lorenseanstewart/next-blog-starter
  2. npm i from the root
  3. now
  4. To see the error, check logs with now logs <url-provided-by-deploy>

Expected behavior

This project to deploy without errors.

System information

  • macOS
  • Version of Next.js: 7.0.2
  • Version of Now: 2
  • Version of now-cli: 12.1.6

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Comments: 52 (21 by maintainers)

Commits related to this issue

Most upvoted comments

Because this is the first result in google, and there is no link to the other issue, I will leave the fix I found here:

The issue comes due to trying to run bundling work during the production serving phase of next (details here), such as @zeit/next-css, @zeit/next-sass, or @zeit/next-typescript.

The fix is to only run those during the build phase of running next:

next.config.js

const { PHASE_PRODUCTION_SERVER } =
  process.env.NODE_ENV === 'development'
    ? {} // We're never in "production server" phase when in development mode
    : !process.env.NOW_REGION 
      ? require('next/constants') // Get values from `next` package when building locally
      : require('next-server/constants'); // Get values from `next-server` package when building on now v2

module.exports = (phase, { defaultConfig }) => {
  if (phase === PHASE_PRODUCTION_SERVER) {
    // Config used to run in production.
    return {};
  }

  const withCSS = require('@zeit/next-css');

  return withCSS();
};

Update: Still not working? See this comment below

Update 2: Added extra conditional so it builds locally too.

Update 3: Corrected to use NOW_REGION over NOW on now v2.

@efleurine @TLevesque Where is withCss / withSass getting defined? It’s not included in your example.

You must make sure you only require('@zeit/next-css') after you’ve checked if (phase === PHASE_PRODUCTION_SERVER).

ie;

Don’t do this:

// ❌ Don't put this here
const withCSS = require('@zeit/next-css');
const { PHASE_PRODUCTION_SERVER } =
  process.env.NODE_ENV === 'development'
    ? {}
    : !process.env.NOW_REGION
      ? require('next/constants')
      : require('next-server/constants');

module.exports = (phase, { defaultConfig }) => {
  if (phase === PHASE_PRODUCTION_SERVER) {
    // Config used to run in production.
    return {};
  }

  return withCSS();
};

Do this

const { PHASE_PRODUCTION_SERVER } =
  process.env.NODE_ENV === 'development'
    ? {}
    : !process.env.NOW_REGION
      ? require('next/constants')
      : require('next-server/constants');

module.exports = (phase, { defaultConfig }) => {
  if (phase === PHASE_PRODUCTION_SERVER) {
    // Config used to run in production.
    return {};
  }

  // ✅ Put the require call here.
  const withCSS = require('@zeit/next-css');

  return withCSS();
};

Update: added conditional so it will work when building locally too.

Update 2: Corrected to use NOW_REGION over NOW on now v2.

I’m not sure what the issue is 🤔 As per zeit/now-examples#214:

  1. Add now.json
{
  "version": 2,
  "builds": [
    {"src": "package.json", "use": "@now/next"}
  ]
}
  1. Upgrade to Next.js 8 canary
yarn add next@canary
  1. Enable serverless target in next.config.js:
module.exports = {
  target: 'serverless'
}

Or when you’re using plugins:

const withTypescript = require('@zeit/next-typescript')
module.exports = withTypescript({
  target: 'serverless'
})
  1. Add now-build script to package.json:
{
  "scripts": {
    "now-build": "next build"
  }
}

You can read more about the serverless target here: https://github.com/zeit/now-builders/pull/150

And here: https://github.com/zeit/next.js/pull/5927

Then run now. You can verify if you’re running the new serverless mode by checking /_logs for MODE: serverless. If it says MODE: legacy it means your package.json has a Next.js version that doesn’t support target: 'serverless' as per the specification here: https://github.com/zeit/now-builders/pull/150

@alexedev, @carlesandres, @MaksKoseda: 😱 My apologies, I gave you a bum steer; the env var we should be checking against is NOW_REGION (not NOW). I’ve updated the examples above, and copied here for posterity:

const { PHASE_PRODUCTION_SERVER } =
  process.env.NODE_ENV === 'development'
    ? {}
    : !process.env.NOW_REGION // ℹ️ Must be `NOW_REGION`, not `NOW` (my bad)
      ? require('next/constants')
      : require('next-server/constants');

module.exports = (phase, { defaultConfig }) => {
  if (phase === PHASE_PRODUCTION_SERVER) {
    // Config used to run in production.
    return {};
  }

  const withCSS = require('@zeit/next-css');

  return withCSS();
};

The only change is:

     ? {}
-    : !process.env.NOW
+    : !process.env.NOW_REGION
       ? require('next/constants')

Everyone in this issue will want to upgrade their application to this: https://github.com/zeit/now-examples/pull/214

  • Much smaller lambdas
  • Reproducible result
  • No “custom” environment, just what you provide, we don’t override package.json + don’t drop yarn.lock/package-lock.json anymore. We don’t add next-server anymore etc.

More details here: https://github.com/zeit/now-builders/pull/150

@jesstelford OMG I finally got this to work thanks to you!. Thanks a lot man!

@TLevesque Btw, I got mine to work with next-compose-plugins with:

const {PHASE_PRODUCTION_SERVER} =
    process.env.NODE_ENV === "development"
        ? {} // We're never in "production server" phase when in development mode
        : !process.env.NOW_REGION
        ? require("next/constants") // Get values from `next` package when building locally
        : require("next-server/constants"); // Get values from `next-server` package when building on now v2

const nextConfig = {
    webpack: config => {
        // Fixes npm packages that depend on `fs` module
        config.node = {
            fs: "empty"
        };

        config.module.rules = config.module.rules.map(rule => {
            if (rule.loader === "babel-loader") {
                rule.options.cacheDirectory = false;
            }
            return rule;
        });
        return config;
    }
};

module.exports = (phase, {defaultConfig}) => {
    if (phase === PHASE_PRODUCTION_SERVER) {
        return {};
    }

    //const withImages = require("next-images");
    const withSass = require("@zeit/next-sass");
    const {withPlugins} = require("next-compose-plugins");

    return withPlugins([[withSass]], nextConfig)(phase, defaultConfig);
};

Worth noting, that considering this issue, the documentation here is incorrect then: https://www.npmjs.com/package/@zeit/next-typescript

@jesstelford thanks but I am still getting the error

by the way it should be next/constants

my code below but errors keep comming

const { PHASE_PRODUCTION_SERVER } =
  process.env.NODE_ENV === "development" ? {} : require("next/constants");

module.exports = (phase, { defaultConfig }) => {
  if (phase === PHASE_PRODUCTION_SERVER) {
    // Config used to run in production.
    return {};
  }

  return withPlugins(
    [
      withCss,
      withSass
    ],
    {
      webpack(config, { isServer }) {
        if (ANALYZE) {
          config.plugins.push(
            new BundleAnalyzerPlugin({
              analyzerMode: "server",
              analyzerPort: isServer ? 8888 : 8889,
              openAnalyzer: true
            })
          );
          config.plugins.push(new WebpackBundleSizeAnalyzerPlugin("stats.txt"));
        }

        config.module.rules.push({
          test: /\.(png|svg|eot|otf|ttf|woff|woff2)$/,
          use: {
            loader: "url-loader",
            options: {
              limit: 100000,
              publicPath: "./",
              outputPath: "static/",
              name: "[name].[ext]"
            }
          }
        });

        // config.plugins.push(new AntdScssThemePlugin(path.join(__dirname, "assets", "theme.scss")));

        return config;
      }
      // generateBuildId: async () => {
      //   const fromGit = await nextBuildId({ dir: __dirname });
      //   return fromGit.id;
      // },
    }
  );
};

As it is explained here no custom server can be used with lambdas deployed with now v2. Does it mean next-routes cannot be used? What about dynamic pages with clean urls?

Exactly 🙏 No workarounds and a lot of benefits 👍

@timneutkens ok great, so none of the workarounds above that we had to do are necessary anymore! Fantastic! Thanks you for your hard work

@jesstelford that change:

     ? {}
-    : !process.env.NOW
+    : !process.env.NOW_REGION
       ? require('next/constants')

fixed my problem with deploying to now v2. Thanks!

Hi

Unfortunately, I still get that error. My config is:

require('dotenv').config();

const { PHASE_PRODUCTION_SERVER } =
  process.env.NODE_ENV === 'development'
    ? {}
    : !process.env.NOW
    ? require('next/constants')
    : require('next-server/constants');

const config = {
  publicRuntimeConfig: {
    endpoint: process.env.ENDPOINT,
    username: process.env.USERNAME,
    password: process.env.PASSWORD
  }
};

module.exports = (phase, { defaultConfig }) => {
  if (phase === PHASE_PRODUCTION_SERVER) {
    return config;
  }

  const withCSS = require('@zeit/next-css');

  return withCSS(config);
};

Ah, looks like that module doesn’t exist locally.

I guess there should be a check for if its running on now’s servers or not. I think there’s NOW env var we could use?

Does this work both locally and when deploying for you?

const { PHASE_PRODUCTION_SERVER } =
  process.env.NODE_ENV === 'development'
    ? {}
    : !!process.env.NOW
      ? require('next/constants')
      : require('next-server/constants');

Nope, same error on local building.

Edit: Ok, looks like the condition was wrong. This works:

const { PHASE_PRODUCTION_SERVER } =
  process.env.NODE_ENV === 'development'
    ? {}
    : !process.env.NOW
      ? require('next/constants')
      : require('next-server/constants');

Here is the content of the next.config.js file which is working properly on now v2, for a complex example with several plugins from Nextjs and its community, like dotenv, next-images, @zeit/next-sass, webpack-bundle-size-analyzer, @zeit/next-bundle-analyzer and next-plugin-transpile-modules. Here is the repo if it can help someone: https://github.com/TLevesque/platform-trials

@jesstelford, just to make sure, can you confirm that this is the correct syntax to use in term of best practices:

const { PHASE_PRODUCTION_SERVER } =
  process.env.NODE_ENV === "development"
    ? {}
    : require("next-server/constants");

module.exports = (phase, { defaultConfig }) => {
  if (phase === PHASE_PRODUCTION_SERVER) {
    // Config used to run in production.
    return {};
  }

  const sass = require("@zeit/next-sass");
  const images = require("next-images");
  require("dotenv").config();
  const path = require("path");
  const Dotenv = require("dotenv-webpack");
  const withBundleAnalyzer = require("@zeit/next-bundle-analyzer");
  const {
    WebpackBundleSizeAnalyzerPlugin
  } = require("webpack-bundle-size-analyzer");
  const withTM = require("next-plugin-transpile-modules");
  const { ANALYZE } = process.env;

  return withBundleAnalyzer(
    images(
      sass(
        withTM({
          analyzeServer: ["server", "both"].includes(
            process.env.BUNDLE_ANALYZE
          ),
          analyzeBrowser: ["browser", "both"].includes(
            process.env.BUNDLE_ANALYZE
          ),
          bundleAnalyzerConfig: {
            server: {
              analyzerMode: "static",
              reportFilename: "../bundles/server.html"
            },
            browser: {
              analyzerMode: "static",
              reportFilename: "./bundles/client.html"
            }
          },
          transpileModules: ["lodash-es"],
          webpack: config => {
            config.plugins = config.plugins || [];
            config.plugins = [
              ...config.plugins,
              new Dotenv({
                path: path.join(__dirname, ".env"),
                systemvars: true
              })
            ];
            if (ANALYZE) {
              config.plugins.push(
                new WebpackBundleSizeAnalyzerPlugin("stats.txt")
              );
            }
            config.externals = Array.isArray(config.externals)
              ? config.externals.map(fn =>
                  typeof fn === "function"
                    ? (context, request, callback) => {
                        if (request === "lodash-es") {
                          return callback(null, "commonjs lodash");
                        }
                        return fn(context, request, callback);
                      }
                    : fn
                )
              : config.externals;
            return config;
          }
        })
      )
    )
  );
};

@efleurine Just for info, apparently next-compose-plugins package + next-sass doesn’t work with this pattern suggested by jesstelford : https://github.com/cyrilwanner/next-compose-plugins/issues/13

An alternative to dotenv as @alexedev describes is dotenv-webpack:

const { PHASE_PRODUCTION_SERVER } =
  process.env.NODE_ENV === 'development'
    ? {}
    : !process.env.NOW_REGION
    ? require('next/constants')
    : require('next-server/constants');

module.exports = phase => {
  if (phase === PHASE_PRODUCTION_SERVER) {
    return {};
  }

  const DotEnv = require('dotenv-webpack');

  return {
    webpack: config => {
      config.plugins.push(new DotEnv());
      return config;
    }
  };
};

Then you can use process.env.* directly as it will be read from .env and replaced during build.

This is the exact same problem I had when trying to directly implement with-dotenv from the Next.JS examples.

Thank you @webpro, @alexedev and @jesstelford !!! It worked perfectly. You don’t know how many hours I’ve wasted in this and how many more I would’ve wasted without you guys. Thanks!

An alternative to dotenv as @alexedev describes is dotenv-webpack:

const { PHASE_PRODUCTION_SERVER } =
  process.env.NODE_ENV === 'development'
    ? {}
    : !process.env.NOW_REGION
    ? require('next/constants')
    : require('next-server/constants');

module.exports = phase => {
  if (phase === PHASE_PRODUCTION_SERVER) {
    return {};
  }

  const DotEnv = require('dotenv-webpack');

  return {
    webpack: config => {
      config.plugins.push(new DotEnv());
      return config;
    }
  };
};

Then you can use process.env.* directly as it will be read from .env and replaced during build.

well, I finally resolved my problem…

Lambda failed (error 502) because I relied on dotenv package to take env values from .env file but two things went wrong:

  1. .env is ignored by now
  2. deployment is broken if require('dotenv').config(); is called in now environment (I did not understand the reason yet).

Instead, env values should be referenced in now.json the values are becoming available automatically with no need to call dotenv and such see https://zeit.co/docs/v2/deployments/environment-variables-and-secrets/

my now.json looks like

{
  "version": 2,
  "builds": [{ "src": "next.config.js", "use": "@now/next" }],
  "env": {
    "ENDPOINT": "@endpoint",
    "USERNAME": "@username",
    "PASSWORD": "@password"
  }
}

So here is how the fixed next.config.js looks like:

if (!process.env.NOW_REGION) {
  // if deploying with now-ci env values are taken not from .env but from now.json
  // https://zeit.co/docs/v2/deployments/environment-variables-and-secrets/
  // now deployment breaks if dotenv used
  require('dotenv').config();
}

const { PHASE_PRODUCTION_SERVER } =
  process.env.NODE_ENV === 'development'
    ? {}
    : !process.env.NOW_REGION
    ? require('next/constants')
    : require('next-server/constants');

const config = {
  publicRuntimeConfig: {
    endpoint: process.env.ENDPOINT,
    username: process.env.USERNAME,
    password: process.env.PASSWORD
  }
};

module.exports = (phase, { defaultConfig }) => {
  if (phase === PHASE_PRODUCTION_SERVER) {
    // Config used to run in production
    return config;
  }

  const withCSS = require('@zeit/next-css');

  return withCSS(config);
};

this can get a bit more readable by assigning process.env.NOW_REGION to a constant but I wanted to be explicit

If you have any other suggestions for more eloquent fix, please let me know

Just opened #5846 to discuss/address this issue

It looks good to me, and if it works, then I’d say you’re good to go 🎉

Thank you very much @jesstelford for your help!

For anyone stumbling into this, the issue is not necessarily related to next-css. I got the same problem having withBundleAnalyzer(...) returned from next.config.js.

Wrapping it the same way as described above helped.