unjs / redirect-ssl

Connect/Express middleware to enforce https using is-https
MIT License
100 stars 15 forks source link

Connection refused on new non index routes (Nuxt.js / Heroku) #40

Closed gellerby closed 3 years ago

gellerby commented 3 years ago

This is probably a terribly specific issue and if you don't have time I completely understand, but I have a Nuxt.js app running on Heroku and I'm trying to force HTTPS. I've used the config outlined in your README however when I enable the module, I get some unwanted results.

Without Module:

With Module:

Detailed error:
Error: connect ECONNREFUSED 127.0.0.1:443 at TCPConnectWrap.afterConnect [as oncomplete]

This is running on Heroku, below is the relevant bits of the nuxt config file:

import redirectSSL from 'redirect-ssl'

export default {
  target: 'server',
  components: true,
  buildModules: [
    '@nuxtjs/eslint-module'
  ],
  serverMiddleware: [
    redirectSSL.create({
      enabled: process.env.NODE_ENV === 'production'
     }),
  ],
  modules: [
    '@nuxtjs/axios',
    '@nuxtjs/proxy',
    '@nuxtjs/redirect-module'
  ],
  redirect: [
    { from: '^/digital/(.*)$', to: '/' }
  ],
}

Any help/ideas would be greatly appreciated

pi0 commented 3 years ago

Hi @gellerby. I think it is because you have a server-side fetch/HTTP request. Without redirect-ssl, it is not forced and goes well for server-side using insecure requests to port 80 but with it, the server is also forced but actual nuxt server is not listening to https (heroku is terminating SSL connections).

We may use conditional headers to detect this situation:

const isProd = process.env.NODE_ENV === 'production'
const redirectMiddleware = (req, res, next) => {
  const ua = req.headers['user-agent'] || ''
  const enabled = isProd && /Mozilla|Chrome|Safari/.test(ua)
  return enabled ? redirectSSL(req, res, next) : next()
}

// nuxt.config
export default {
  serverMiddleware: [
    redirectMiddleware
  ]
}

(above code is not tested but should give the idea. You can also use request.connection.remoteAddress === '127.0.0.1' for example.)

gellerby commented 3 years ago

fantastic, thank you!