next.js: publicRuntimeConfig undefined in staging environment

  • I have searched the issues of this repository and believe that this is not a duplicate.

Expected Behavior

Steps to Reproduce (for bugs)

next.config.js

module.exports = (phase, { defaultConfig }) => {
  return {
    publicRuntimeConfig: {
      defaultEnvironmentSettings: 'test',
    },
    webpack: (config, { buildId, dev, isServer, defaultLoaders }) => {
      // XXX https://github.com/evanw/node-source-map-support/issues/155
      config.node = {
        fs: 'empty',
        module: 'empty',
      };
      return config;
    },
  };
};

page

const { publicRuntimeConfig } = getConfig();
const { groupSettings, url } = this.props;
const schoolName = url.query.schoolName;
console.log('publicRuntimeConfig', publicRuntimeConfig) // publicRuntimeConfig undefined
console.log('getConfig()', getConfig()) // getConfig()  serverRuntimeConfig:{}, publicRuntimeConfig: undefined

Context

publicRuntimeConfig is undefined

This only happens when I use NODE_ENV staging, it works fine in development mode. (I haven’t tested against production env)

Note that my staging environment is hosted on AWS lambda, but it’s maybe not related to the issue.

About this issue

  • Original URL
  • State: closed
  • Created 9 years ago
  • Reactions: 15
  • Comments: 28 (14 by maintainers)

Most upvoted comments

@wescoder I had the same issue on the test env, but it makes sense because next server doesn’t run during tests. In that case, I simply changed the getConfig() call to:

const { publicRuntimeConfig = {} } = getConfig() || {};

That nulls out the values, you can set appropriate defaults if you need them during tests, we don’t in our case.

I still cannot repro the issue in this thread. We now have this config running in production - out to ~2 million users, built, exported, deployed to CDN configured using assetPrefix using static JS bundles and a custom node server - without issue.

If you run into issues where publicRuntimeConfig is undefined within testcases, you can use the following in a setup file;

// jest.setup.js
import { setConfig } from 'next/config'
import config from './next.config'

// Make sure you can use "publicRuntimeConfig" within tests.
setConfig(config.publicRuntimeConfig)

@robinvdvleuten what worked for me was:

// jest.setup.js
import { setConfig } from 'next/config'
import { publicRuntimeConfig } from './next.config'

// Make sure you can use "publicRuntimeConfig" within tests.
setConfig({ publicRuntimeConfig })

For reference, I was required to mock the next/config singleton to get this working in a Jest test environment. It seems to be required due the way Jest manages its own require.cache, but I’m not sure why no one else has run into this in regards to next/config. Anyways, the below works for me.

// jest.setup.js
import mockEnvConfig from '~/env-config.js';

jest.mock('next/config', () => () => ({ publicRuntimeConfig: mockEnvConfig }));

// jest.config.js
module.exports = {
  setupFiles: ['<rootDir>/jest.setup.js'],
};

@joaovieira yes that’s exactly the same as my code 👍

Just another one to this thread. After a long time struggling to understand why my next/config manual mock wasn’t being run, I found out that after transpilation (babel-jest) the module is renamed to next-server/config (re-exported in https://github.com/zeit/next.js/blob/v8.0.3/packages/next/config.js) and thus not the same module I was mocking. I.e.:

// path.ts
import getConfig from 'next/config';

const { publicRuntimeConfig } = getConfig();
const { assetPrefix = '', basePath = '' } = publicRuntimeConfig;
// path.test.ts
jest.mock('next/config', () => {
  console.log('this is never run!');
  return () => ({
    publicRuntimeConfig: {
      assetPrefix: 'https://example.com',
      basePath: '/base',
    },
 };
}));

import { assetPath, appPath } from './path';

// transpiled path.js
var _interopRequireDefault = require('@babel/runtime-corejs2/helpers/interopRequireDefault');

Object.defineProperty(exports, '__esModule', {
  value: true,
});
exports.appPath = exports.assetPath = void 0;

// ----------------------- HERE IT IS!! ----------------------------
var _config = _interopRequireDefault(require('next-server/config'));

var _getConfig = (0, _config.default)(),
  publicRuntimeConfig = _getConfig.publicRuntimeConfig;

var _publicRuntimeConfig$ = publicRuntimeConfig.assetPrefix,
  assetPrefix = _publicRuntimeConfig$ === void 0 ? '' : _publicRuntimeConfig$,
  _publicRuntimeConfig$2 = publicRuntimeConfig.basePath,
  basePath = _publicRuntimeConfig$2 === void 0 ? '' : _publicRuntimeConfig$2;
// transpiled path.test.js
jest.mock('next/config', function() {
  console.log('this is never run!');
  return function() {
    return {
      publicRuntimeConfig: {
        assetPrefix: 'https://example.com',
        basePath: '/base',
      },
    };
  };
});

var _path = require('./path');

Changing the mock to jest.mock('next-server/config') works as expected… This is horrible to diagnose and I believe this worked correctly before, so not sure something changed in either babel or babel-jest to cause the optimization.

I know this closed but to the original issue of having publicRuntimeConfig undefined in non-dev environments, disabling automatic static optimisation worked for me in this case i.e. overriding _app.js and uncommenting the getInitialProps function. Might be a temporary fix though.

import React from 'react';
import App from 'next/app';

class MyApp extends App {
  // Only uncomment this method if you have blocking data requirements for
  // every single page in your application. This disables the ability to
  // perform automatic static optimization, causing every page in your app to
  // be server-side rendered.
  //
  static async getInitialProps(appContext) {
    // calls page's `getInitialProps` and fills `appProps.pageProps`
    const appProps = await App.getInitialProps(appContext);

    return { ...appProps };
  }

  render() {
    const { Component, pageProps } = this.props;
    return <Component {...pageProps} />;
  }
}

export default MyApp;

In case it helps others, my solution (derived from @Vadorequest) follows.

I determine which “environment” to pull the runtime info from, based on whether the code runs on the server or browser.

import getConfig from 'next/config'

const amBrowser = typeof window !== 'undefined'

let ENV
let PORT
if (amBrowser) {
  const config = getConfig().publicRuntimeConfig
  ENV = config.ENV
  PORT = config.PORT
}
else {
  ENV = process.env.NODE_ENV || 'development'
  PORT = process.env.PORT || 8080
}

I’m running a custom Express server. Here’s my snippet for creating the next app –

const nextConf = {
  serverRuntimeConfig: {},
  publicRuntimeConfig: { ENV, PORT },
}

const DEV = ENV === 'development'
const nextApp = next({ dev:DEV, conf:nextConf, quiet:false })

Right after nextApp is created, getConfig() will return what you expected. Before that point, getConfig() returns undefined.

@joaovieira https://github.com/zeit/next.js/pull/6458, basically what this does is bundle the wrapper module and mark the require for next-server/config etc as external in webpack. That way it achieves the same without doing code modification 👍

@dcalhoun Your answer was very helpful as it solved a similar publicRuntimeConfig error I was receiving, so thank you!!

@codinronan Yeah it makes sense, I tested it this way and it worked fine. Thanks!

Just deployed a create-next-app with the code from your issue: https://create-next-example-app-nagabdohry.now.sh/ as you can see in the console it’s working fine.