How to Set port in next.js
Asked Answered
T

16

258

One application is running on port 3000 and I want to run another application on a different port from the default port, which is 3000. How do I change this in React Next.js? My package.json currently contains:

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "next",
    "build": "next build",
    "start": "next start"
},

And the CLI command that I use to start dev is npm run dev.

Thissa answered 10/2, 2020 at 9:33 Comment(2)
github.com/zeit/next.js/issues/102Aretina
next dev will automatically use another port if port 3000 is in use.Chaffinch
T
499

This work for me:

"scripts": { 
    "dev": "next dev -p 8080",
    "start": "next start -p 8080",
},
Thissa answered 10/2, 2020 at 9:40 Comment(6)
It didn't wokrd out.Leucas
If you're using the dev next command in your script, for me today this only works by specifying after next command, e.g. next dev -p 8080 and next start -p 8080 for prod mode, as opposed to before like this: next -p 8080 dev.Silicium
This works for me in project that created by create-next-app. Thanks a lot.Eigenfunction
Run npm run dev -p 5000 to run the app on port 5000Treaty
@Treaty With that, I got Invalid project directory provided, no such directory. I used npm run dev -- -p 5000 instead and that worked.Proudhon
this doesn't seem to work anymore for start (next 13.5.6). But this works: PORT=3001 npm run start (from the command line), or just changing the "scripts" part of package.jsonto "start": "PORT=3001 next start"Abstractionism
A
80
"scripts": {
    "dev": "next dev -p 8080", // for dev 
    "start": "next start -p 8080" // for prod
},
Aerobiosis answered 13/12, 2020 at 16:10 Comment(1)
This really isn't; the port shouldn't be baked into a startup script.Stimulative
R
45

With yarn, pnpm you can easily pass any arguments:
yarn dev -p 8080 or yarn dev --port=8080

With npm using -- to pass arguments:
npm run dev -- -p 8080

Reggie answered 16/2, 2022 at 11:28 Comment(1)
It was the most practical answer for me. thanksKyanize
P
33

The application will start at http://localhost:3000 by default. The default port can be changed with -p, like so:

 npx next dev -p 4000

Or using the PORT environment variable:

PORT=4000 npx next dev

#note that I used npx not npm

You can also set the hostname to be different from the default of 0.0.0.0, this can be useful for making the application available for other devices on the network. The default hostname can be changed with -H, like so:

 npx next dev -H 192.168.1.2

If you're getting an error that the port is already in use, what you can do to resolve it on windows is

Go to the Task Manager.

Scroll and find a task process named. Node.js: Server-side

End this particular task.
Polyploid answered 12/7, 2021 at 19:39 Comment(0)
M
26

just need to do:

yarn dev -p PORT_YOU_LIKE
Metronome answered 26/6, 2020 at 11:50 Comment(4)
For long term value, please explain why this code solves OP's issue. Code only answers are frowned upon. Explanations help future visitors learn, and apply this knowledge to similar issues that have in their own code. They are also more likely to be upvoted. Consider editing to improve your answer, and keep quality of SO Answers high. Thanks for your contribution.Wholesale
the .env file doesn't work on next js. Anyone who has a working solution can help drop the solutionPantomimist
I like this approach. This worked for me instead of changing PORT in any other file. Thank you.Superconductivity
In my case the port parameter yarn dev -p 4000 was just ignored. App still responded on http://localhost:3000/ not on http://localhost:4000/ (although I could see in the terminal concurrently "npm run server" "npm run client" -port 4000).Brainless
P
19

A workaround using environment variables via .env file

Thanks to this github comment

For development

  1. Create a script for your dev environment in the project root e.g. dev-server.js
// dev-server.js
require('dotenv').config(); // require dotenv
const cli = require('next/dist/cli/next-dev');

cli.nextDev(['-p', process.env.PORT || 3000]);
  1. Then you can set a custom port in your .env like this: PORT=3002

  2. Update the dev command in your package.json to use the dev-server.js script like this:

  "scripts": {
    "dev": "node dev-server.js"
  }
  1. Run npm run dev and the NextJS application will start on port 3002.

For production

  1. Create a script for your prod environment in the project root e.g. prod-server.js
// prod-server.js
require('dotenv').config(); // require dotenv
const cli = require('next/dist/cli/next-start');

cli.nextStart(['-p', process.env.PORT || 3000]);
  1. Then you can set a custom port in your .env like this: PORT=3002

  2. Update the start command in your package.json to use the prod-server.js script like this:

  "scripts": {
    "build": "next build",
    "start": "node prod-server.js"
  }
  1. Run npm run start and the NextJS application will start on port 3002. (Don't forget to build the project before with npm run build)

dotenv should be installed via npm install dotenv, required and configured in the scripts as seen in the code snippets before.

Note from the github comment:

There are some hosting providers that just force us to have server.js/index.js file. The bonus of the above solution is that it doesn't require any additional dependency.

Pocketknife answered 30/10, 2021 at 13:31 Comment(0)
N
14

There are two ways to do so:

In your package.json file, add -p 8080 to the dev/start scripts to start the server on port 8080:

  "scripts": {
    "dev": "next -p 8080",
    "build": "next build",
    "profile-build": "next build --profile",
    "start": "next start -p 8080"
  }

Alternatively, if you don't want to hardcode this in the package.json file, you could start the script with ENV variable PORT.

PORT=8080 npm run dev

Visit vercel documentation for more information.

Namecalling answered 29/6, 2021 at 6:14 Comment(2)
Nice. So curious why this is the only answer (here and elsewhere that I've seen) that mentions using the PORT= variable. There's no reason a port number should be baked into an npm script.Stimulative
'PORT' is not recognized as an internal or external command i am facing thisFaught
B
7

Usually, the port is environment specific so it shouldn't go to git repository. Thus the best practise is to define it in .env.local, and it can be read from there using the following start script:

// package.json
"scripts": {
  "start": "[ -e .env.local ] && set -a && . ./.env.local; next start",
},

Using the set -a will export the sourced environment variables, and the Next.JS start script will use the PORT environment variable if defined. Note that this script won't work in Windows.

Bathrobe answered 18/8, 2022 at 7:45 Comment(2)
Works great for me! The command looks cryptic if you don't know shell scripting, but I prefer this over the alternatives. Thank you!Winograd
Could you explain the elements of the command?Vasiliki
F
5

Setting port number in npm script is not good idea at all.

From terminal you can pass the port number by using following command

SET PORT=3001 && npm start
Faught answered 11/10, 2021 at 8:7 Comment(1)
I am currently testing 2 applications on the same PC, for that having one single PORT variable won't work (because both applications would use the same variable). How can we introduce different port varialbles (like APP1_PORT and APP2_PORT) ?Brainless
T
1

For NextJS 13, all you have to do is specify it in your terminal. Run:

npm run dev -p 4000

To run the app on port 4000

Treaty answered 17/8, 2023 at 12:18 Comment(1)
Shouldn't it be npm run dev -- -p 4000?Stegodon
B
1

You can start your app with this command:

npx env-cmd -f ".env" npm run dev

Where env-cmd -f ".env" loads environment variables. And .env file looks as below:

PORT=4000 # new port

You could also simplify this process by modify package.json scripts:

"dev": "npx env-cmd -f \".env\" next dev"

And after that:

npm run dev
Bangs answered 19/11, 2023 at 9:8 Comment(0)
C
1

Using the -p or --port option with the next dev command allows you to specify a custom port for your Next.js development server.

For example:

next dev -p 4000

This command will start your Next.js development server on port 4000.

Connors answered 28/2 at 12:22 Comment(0)
B
0

following example will be work for nextjs and pm2 combination pm2 start npx --name "next" -- next -p 3001

Binnings answered 21/12, 2022 at 19:22 Comment(0)
D
0

Another way is using a custom Server file in Next.js

So you can just set your port in env file and not having to change anywhere else.

Somehting like below example

const express = require('express');
const next = require('next');
const getConfig = require('../next.config');


const { basePath, port } = getConfig.publicRuntimeConfig;

const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });

app.prepare().then(() => {
  const app = express();

  app.use(express.json());
  app.use(express.urlencoded({ limit: '20kb', extended: false }));


  app.listen(3000, (err) => {
    if (err) throw err;
    console.log('server running on port: ' + 3000);
  });
});
Determinative answered 22/12, 2022 at 13:31 Comment(0)
M
0

For some reason, the answer in https://mcmap.net/q/109300/-how-to-set-port-in-next-js 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());
  }
});
Maurilia answered 29/3, 2023 at 6:29 Comment(0)
D
-3

Apart from hard coding it in package.json, you could do it via .env file:

PORT=4000
Define answered 28/12, 2022 at 14:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.