Heroku将Next.js React客户端应用HTTP重定向到https

时间:2019-07-02 11:48:42

标签: reactjs ssl heroku https next.js

我在Heroku上部署了一个快递服务器:https://server.mydomain.com

以及也部署在Heroku上的Next.js React应用:https://app.mydomain.com

Heroku都自动配置了它们的SSL证书,当我访问https域时,它们按预期工作。

我遇到的问题是,当我访问http://app.mydomain.com时,它不会重定向到https://app.mydomain.com

我在网上找到的所有解决方案都指向在服务器上强制使用SSL:

/* At the top, with other redirect methods before other routes */
app.get('*',function(req,res,next){
 if(req.headers['x-forwarded-proto']!='https')
   res.redirect('https://app.mydomain.com'+req.url)
 else
   next() /* Continue to other routes if we're not redirecting */
})

这些解决方案对于服务器请求可以很好地运行,但是加载React客户端页面并不一定会触发app.get()。显然,React客户端可以独立于服务器运行。

问题是::有人如何在Heroku上将https强制用于子域Next.js React客户端应用程序?不使用快速服务器方法?

1 个答案:

答案 0 :(得分:2)

我在一个生产应用程序中执行此操作。

我们准备下一个应用程序对象并初始化Express服务器。这是在 server.js 文件中完成的。您可以在docs about a custom server中详细了解它。

Next.js在其github中的examples文件夹中也有一个有关自定义快递服务器的示例。是here

"scripts": {
  "dev": "next",
  "build": "next build",
  "start": "next start"
}

对于部署到Heroku,您应该只需自定义 npm start 脚本即可像这样启动nextjs:

var PdfReader = require("pdfreader").PdfReader;
new PdfReader().parseFileItems("sample.pdf", function(err, item){
  if (item && item.text)
    console.log(item.text);
});

Heroku还会自动运行 npm run build ,因此它应该为您构建应用。