Nextjs 自定义 HTTPs 服务器很慢

问题描述 投票:0回答:1

我正在尝试在生产中运行 Next.js 网站,但该网站加载速度非常慢(加载每个页面约 8 秒)。这与开发形成鲜明对比,每个页面平均加载时间约为 0.4 秒。

我使用带有 Next.js 的自定义服务器来使用 HTTPS 而不是 HTTP。

这是我的服务器代码:

const http = require('http');
const https = require('https');
const fs = require('fs');
const next = require('next');

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

const handle = app.getRequestHandler();

const options = {
  key: fs.readFileSync('/etc/letsencrypt/live/example.com/privkey.pem'),
  cert: fs.readFileSync('/etc/letsencrypt/live/example.com/fullchain.pem')
};

app.prepare().then(() => {
  https.createServer(options, (req, res) => {
    handle(req, res)
  }).listen(443, (err) => {
    if (err) throw err
    console.log('> Ready on https://localhost:443')
  })

  http.createServer((req, res) => {
    res.writeHead(301, {
      Location: `https://${req.headers.host}${req.url}`
    })
    res.end();
  }).listen(80, (err) => {
    if (err) throw err
    console.log('> Ready on http://localhost:8080')
  })
})

这只是我的服务器硬件本身的限制吗?我正在使用 DigitalOcean VPS 来运行此服务器。

另外,我觉得这与我的服务器的构建有关,因为当我运行

server.js
时,它说它正在编译页面,我觉得这应该在我已经创建的构建中。

我已经运行了

next build
,但我不认为自定义服务器正在使用此版本。

以下是日志示例:

joey@WebsiteDroplet:~/Website$ sudo node server
info  - SWC minify release candidate enabled. https://nextjs.link/swcmin
event - compiled client and server successfully in 2s (196 modules)
wait  - compiling...
event - compiled client and server successfully in 292 ms (196 modules)
> Ready on https://localhost:443
> Ready on http://localhost:8080
wait  - compiling /_error (client and server)...
event - compiled client and server successfully in 436 ms (197 modules)
wait  - compiling /about (client and server)...
event - compiled client and server successfully in 486 ms (205 modules)
node.js next.js
1个回答
1
投票

当我运行自定义服务器时,

dev
函数中的
next
选项无意中在以下行中设置为 true:

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

对于生产,我在

next.config.js
文件中设置环境变量,如下所示:

module.exports = {
  env: {
    NODE_ENV: 'production',
  },
}

Next.js 文档中所述。

© www.soinside.com 2019 - 2024. All rights reserved.