For some reason, the answer in https://stackoverflow.com/a/69780065/6831932 doesn't work for me, but fails with
/path/to/project/node_modules/next/dist/bin/next:147 commands[command]().then((exec)=>exec(forwardedArgs) ^ TypeError: exec is not a function at /path/to/project/node_modules/next/dist/bin/next:147:34 at process.processTicksAndRejections (node:internal/process/task_queues:95:5) Node.js v19.8.1 npm ERR! Lifecycle script `dev` failed with error: npm ERR! Error: command failed npm ERR! in workspace: [email protected] npm ERR! at location: /path/to/project/apps/frontend
My workaround is to use node:child_process to spawn next:
const dotenv = require('dotenv'); // For some reason trying to invoke nextDev() from 'next/dist/cli/next-dev' // doesn't work, even though others report success with it. // So, let's try invoking `next` as a child process... const {spawn} = require('node:child_process'); // I have a monorepo with node_modules and .env only at project root. // If you don't, you can remove the '/../../' part. const projectRoot = process.cwd() + '/../../'; // Get the .env file from the root of the project. dotenv.config({path: projectRoot + '.env'}); // Get next binary path and default args. const nextPath = projectRoot + 'node_modules/.bin/next'; const FRONTEND_PORT = process.env.FRONTEND_PORT || '4000'; const FRONTEND_HOST = process.env.FRONTEND_HOST || 'localhost'; const nextArgs = [ 'dev', '-p', FRONTEND_PORT, '-H', FRONTEND_HOST, ]; // Spawn next process. const next = spawn(nextPath, nextArgs); // Log output from next process. next.stdout.on('data', (data) => { if (typeof data === 'string') { console.log(data); } else { console.log(data.toString()); } }); // Log errors from next process. next.stderr.on('data', (data) => { if (typeof data === 'string') { console.error(data); } else { console.error(data.toString()); } });
next devwill automatically use another port if port 3000 is in use.