Changing the port when running Next.js apps in dev mode

By default, running npm run dev will start the dev server on port 3000. The automatically generated README says so it self. However, I wanted to reserve that port for my node.js server which provides the API to my app.

Googling "changing the port of Next.js" returns a bunch of unofficial links, which do indeed give the solution. Unfortunately the official page appears very low in the ranking. Here's my attempt at making it go up a bit: https://nextjs.org/docs/pages/api-reference/next-cli#development

Basically you can either run:

  • npx next dev -p 4000
  • PORT=4000 npx next dev

Or with npm, change package.json from:

{
  ...
  "scripts": {
    "dev": "next dev",
    ...
  }
}

to:

{
  ...
  "scripts": {
    "dev": "next dev -p 8080",
    ...
  }
}

and run npm run dev.