To change the port on a Next.js
To change the port on a Next.js application, you can specify the PORT
environment variable when running the development server. Here's how to do it:
Method 1: Using package.json
Scripts
If you use npm
or yarn
, you can modify the dev
script in your package.json
to specify a different port.
- Open your
package.json
. - Locate the
scripts
section and modify thedev
script to include the-p
or--port
option followed by the desired port number.
For example, to use port 4000
:
"scripts": {
"dev": "next dev -p 4000",
"build": "next build",
"start": "next start"
}
Now, running npm run dev
or yarn dev
will start your Next.js app on port 4000.
Method 2: Using Environment Variables
You can also set the port using an environment variable:
- Create a
.env.local
file in the root of your project (if it doesn’t exist). - Add the following line to specify the desired port:
PORT=4000
Next.js will read this environment variable and start the app on port 4000 when you run the dev
script.
Method 3: Setting Port Directly in the Command Line
If you want to quickly start your Next.js app on a custom port without modifying any files, you can do it directly in the command line:
PORT=4000 npm run dev
or if you're using yarn
:
PORT=4000 yarn dev
This will override the default port for that specific run.
Summary
- Modify the
dev
script inpackage.json
withnext dev -p <port>
. - Alternatively, set the
PORT
in.env.local
or directly in the command line.
Let me know if you need further clarification!
댓글
댓글 쓰기