question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Next.js App fails to start with next-i18next-middleware.js in server.js ...

See original GitHub issue

Here is the repo I’m working with: https://github.com/ahmedmusawir/dc_next_pwa_stage_7

  1. To start, my next.config.js looks like this:
const path = require('path');
const WorkboxPlugin = require('workbox-webpack-plugin');

module.exports = {
	publicRuntimeConfig: {
		localeSubpaths: process.env.LOCALE_SUBPATHS === 'true',
	},
	webpack: (config, { buildId, dev }) => {
		/**
		 * Install and Update our Service worker
		 * on our main entry file :)
		 * Reason: https://github.com/ooade/NextSimpleStarter/issues/32
		 */
		const oldEntry = config.entry;

		config.entry = () =>
			oldEntry().then(entry => {
				entry['main.js'] &&
					entry['main.js'].push(path.resolve('./utils/offline'));
				return entry;
			});

		/* Enable only in Production */
		if (!dev) {
			// Service Worker

			config.plugins.push(
				new WorkboxPlugin.InjectManifest({
					swSrc: path.join(__dirname, 'utils', 'sw.js'),
					swDest: path.join(__dirname, '.next', 'sw.js'),
					globDirectory: __dirname,
					globPatterns: [
						'static/**/*.{png,jpg,ico}', // Precache all static assets by default
					],
				}),
			);
		}

		return config;
	},
};

  1. My i18n.js file looks like this:
import NextI18Next from 'next-i18next';

const NextI18NextInstance = new NextI18Next({
	defaultLanguage: 'en',
	otherLanguages: ['de', 'es'],
	localeSubpaths: false,
});

export default NextI18NextInstance;

/* Export class methods as named exports. This is a must! */
export const {
	i18n,
	appWithTranslation,
	withNamespaces,
	Link,
	Trans,
	Router,
} = NextI18NextInstance;

  1. And server.js file looks like this:
const { createServer } = require('http');
const path = require('path');
const next = require('next');
const routes = require('./routes');
const nextI18NextMiddleware = require('next-i18next/middleware'); // LINE 1
const nextI18next = require('./i18n'); // LINE 2

const dev = process.env.NODE_ENV !== 'production';
const app = next({ dir: '.', dev });
const handle = routes.getRequestHandler(app);

const PORT = process.env.PORT || 5001;

app.prepare().then(_ => {
	const server = createServer((req, res) => {
		if (req.url === '/sw.js' || req.url.startsWith('/precache-manifest')) {
			app.serveStatic(req, res, path.join(__dirname, '.next', req.url));
		} else {
			handle(req, res);
		}
	});

	server.use(nextI18NextMiddleware(nextI18next)); // LINE 3

	server.listen(PORT, err => {
		if (err) throw err;

		console.log(`App running on port ${PORT} \n http://localhost:${PORT}`);
	});
});

  1. Plz understand, before I add the 3 lines above. everything works great without issue. But as soon as I’ve added those 3 lines and tried yarn dev to start the app, I get the following:
Mooses-High-Sierra:1.dc_next_pwa_stage_7 moose$ yarn dev
yarn run v1.12.3
$ node server
/Volumes/HDD80GB/Users/moose/Documents/_DEV/react-apps/8-phase-new-design/1.dc_next_pwa_stage_7/i18n.js:1
(function (exports, require, module, __filename, __dirname) { import NextI18Next from 'next-i18next';
                                                              ^^^^^^

SyntaxError: Unexpected token import
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)
    at Module._compile (module.js:617:28)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)
    at Module.require (module.js:597:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/Volumes/HDD80GB/Users/moose/Documents/_DEV/react-apps/8-phase-new-design/1.dc_next_pwa_stage_7/server.js:6:21)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
  1. Then I alter my i18n.js file to the following (as the simple example has):
const NextI18Next = require('next-i18next').default;

const NextI18NextInstance = new NextI18Next({
	defaultLanguage: 'en',
	otherLanguages: ['de', 'es'],
	localeSubpaths: false,
});

  1. And this time when I start with yarn dev, it compiles and stops with the following:
✔ success server compiled in 4s 549ms
(node:90075) UnhandledPromiseRejectionWarning: TypeError: Cannot destructure property `allLanguages` of 'undefined' or 'null'.
    at _default (/Volumes/HDD80GB/Users/moose/Documents/_DEV/react-apps/8-phase-new-design/1.dc_next_pwa_stage_7/node_modules/next-i18next/dist/commonjs/middlewares/next-i18next-middleware.js:29:7)
    at app.prepare.then._ (/Volumes/HDD80GB/Users/moose/Documents/_DEV/react-apps/8-phase-new-design/1.dc_next_pwa_stage_7/server.js:23:13)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:189:7)
(node:90075) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:90075) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

  1. At this point I totally replace my server.js with the examples/simple/server.js and try to restart and get the exact error at above. What exactly I’m doing wrong? But when I remove the middle ware code, things work fine like here: https://dcnextpwa-oucwsvjrbu.now.sh/

Any help or guidance on this will be highly appreciated. Thanx in advance.

  1. O’ya, here is my OS and Node version:
Mooses-High-Sierra:1.dc_next_pwa_stage_7 moose$ node -v
v8.12.0
  1. Also, the following warning keeps showing up at the console even though I’ve declared the namespacesRequired array on every page:
Warn: You have not declared a namespacesRequired array on your page-level componen  t: Error. This will cause all namespaces to be sent down to the client, possibly n  egatively impacting the performance of your app. For more info, see: https://githu  b.com/isaachinman/next-i18next#4-declaring-namespace-dependencies


Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:12 (6 by maintainers)

github_iconTop GitHub Comments

9reactions
isaachinmancommented, Feb 25, 2019

Hi @bndby - transpiling your server code is up to you. You can search the Next repo, there are many people asking about how to do this.

1reaction
ghostcommented, Aug 14, 2019

To everyone: this works

Read more comments on GitHub >

github_iconTop Results From Across the Web

Next.js App fails to start with next-i18next-middleware ... - GitHub
Here is the repo I'm working with: https://github.com/ahmedmusawir/dc_next_pwa_stage_7 To start, my next.config.js looks like this: const ...
Read more >
Next.js app throws an error on the server but not locally
I have the same problem. This app used to work perfectly. I suspect that this started happening when we upgraded Next.js from 11.1.2...
Read more >
Advanced Features: Custom Server - Next.js
Start a Next.js app programmatically using a custom server. ... Most of the time, you will not need this – but it's available...
Read more >
Getting Started | Next.js
Run npm run dev or yarn dev or pnpm dev to start the development server on http://localhost:3000; Visit http://localhost:3000 to view your application...
Read more >
Advanced Features: Error Handling - Next.js
This documentation explains how you can handle development, server-side, and client-side errors. Handling Errors in Development. When there is a runtime error ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found