乐闻世界logo
搜索文章和话题

How to set port in next js?

1个答案

1

In Next.js, you can set the application's port in two primary ways:

1. Using Command Line Parameters

You can specify the port via command line when launching the Next.js application. By default, Next.js applications run on port 3000. However, to change the port, you can use the -p flag with the npm run dev or yarn dev command, specifying the desired port number. For example, to run the application on port 5000, you can do the following:

bash
npm run dev -p 5000 # or yarn dev -p 5000

2. Setting in Code

If you need to configure the port at the code level, you can do this in the custom server script for Next.js. For example, if you're using Express.js as the custom server, you can set the port in the server.js file as follows:

javascript
const express = require('express'); const next = require('next'); const port = parseInt(process.env.PORT, 10) || 5000; const dev = process.env.NODE_ENV !== 'production'; const app = next({ dev }); const handle = app.getRequestHandler(); app.prepare().then(() => { const server = express(); server.all('*', (req, res) => { return handle(req, res); }); server.listen(port, (err) => { if (err) throw err; console.log(`> Ready on http://localhost:${port}`); }); });

In the above code example, the port is set to the value of the environment variable PORT, defaulting to 5000 if not specified. This allows you to flexibly change the port by setting environment variables.

Environment Variables

Additionally, you can set the port using environment variables in a .env.local file. However, note that Next.js does not directly support setting the port via environment variables; you need to read the environment variables in your custom server code to set the port.

bash
# .env.local file PORT=5000

Then in server.js, read this environment variable:

javascript
const port = parseInt(process.env.PORT, 10) || 3000;

Conclusion

Typically, using command-line parameters is sufficient for most cases, as it is simple and direct. However, if you need more complex configurations or your application already uses a custom server, you can set the port in the code. Remember, for production deployments, the port is typically determined by the deployment environment. For example, many PaaS (Platform as a Service) like Heroku or Vercel automatically assign the port, so you don't need to set it manually.

2024年6月29日 12:07 回复

你的答案