In web development, it’s important to be flexible and able to customize things. If you use Next.js, you might need to change the default port your app runs on. This could be to avoid clashes with other services or because your deployment environment requires it. Knowing how to change the port is useful.
This tutorial will help you with step-by-step instructions to change the port in both development and production environments. With these steps, you can run your Next.js app on any port you need, making development and deployment easier.
Prerequisites
- Basic knowledge of JavaScript and Node.js.
- Next.js application set up on your local machine. If you don’t have one, you can create a new Next.js app by running npx create-next-app@latest.
Steps to Change Next.js Port
- Locate the package.json File: This file is available in the root directory of the project.
- Modify the scripts Section: In the package.json file, you will find a scripts section. This section contains commands that can be executed on your application. The default start script usually looks like this:
"scripts": { "dev": "next dev", "build": "next build", "start": "next start" }
- Change the Port for Development Mode:
- If you want to change the port in development mode (when you run `
npm run dev
`), you should modify the dev script. - For example, to change the port to 4000, update the dev script as follows:
"dev": "next dev -p 4000"
- `
-p
` flag is used to specify the port number.
- If you want to change the port in development mode (when you run `
- Change the Port for Production Mode:
- If you need to change the port in production mode (when you run `
npm start
` after building your app), modify the start script. - To change the port to 4000 in production mode, update the start script:
"start": "next start -p 4000"
- If you need to change the port in production mode (when you run `
- Save the package.json File: After making the changes, save the file.
- Run Your Application:
- For development mode, use the command `npm run dev`. Your application should now be running on http://localhost:4000.
- For production mode, first build your app using `npm run build`, then start it with `npm start`. It will be available on http://localhost:4000.
Ensure that the port number you choose is not already in use by another application.
If you’re running your Next.js application in a Docker container or behind a proxy, make sure to update the port settings there as well.
Conclusion
This tutorial helped you to understand about changing the port in a Next.js application in package.json file. This allows you to run your Next.js application on a custom port both in development and production modes. Remember to check for port conflicts to avoid errors.