10

I'm trying to create a middleware to redirect all my routes to https, I think I need a middleware so I've created a redirect.js file in the middleware folder of Nuxt and then I've added this to nuxt.config.js:

router: {
  middleware: ["redirect"]
},

And here is my redirect.js file that gives me a server error:

export default function({ app }) {
  if (process.env.NODE_ENV === "production") {
   if (app.context.req.header("x-forwarded-proto") !== "https") {
  app.context.res.redirect(`https://${app.context.req.header("host")}${app.context.req.url}`);
   }
  }
}
zcserei
  • 577
  • 7
  • 30
yoyojs
  • 1,723
  • 5
  • 24
  • 41

3 Answers3

11

I found an easier way i've added the package redirect-ssl

npm i redirect-ssl

and then i've added this line in my nuxt.config.js :

serverMiddleware: ["redirect-ssl"],
yoyojs
  • 1,723
  • 5
  • 24
  • 41
  • 4
    Try this line if you want to enable it only for production: `import redirectSSL from 'redirect-ssl'; export default { serverMiddleware: [redirectSSL.create({enabled: process.env.NODE_ENV === 'production'})]}` – Alberti Buonarroti Aug 20 '20 at 13:35
  • 1
    @AlbertiBuonarroti i have exactly this copied from https://github.com/nuxt-contrib/redirect-ssl#using-with-nuxtjs but it does not redirect on my Heroku deploy. I have NODE_ENV set to "production" in heroku config vars. – trainoasis Oct 22 '20 at 11:08
  • I spent half a day solving this issue and only this solution fixed the SSL issue. – Sergiu Mare Mar 14 '22 at 13:30
  • just super - thanks... – bhu Boue vidya Jun 06 '22 at 03:36
1

You can configure this in heroku.

For Nuxt static mode:

  1. Add the https://github.com/heroku/heroku-buildpack-static.git buildpack after the heroku/nodejs buildpack under buildpacks
  2. Make sure the buildpacks are added in this order to an app.json in the root directory of your project
  3. Add a static.json in the root directory of your project
    • Make sure root and https_only are set correctly
    • If you want Nuxt to resolve routes instead of Nginx (so that you don't get the Nginx 404 page when you go to an unknown route), set routes as well.

Example static.json:

{
  "root": "dist/",
  "routes": {
    "/**": "index.html"
  },
  "https_only": true
}
user7247147
  • 1,045
  • 1
  • 10
  • 24
0

For nuxt 3 (it works with heroku):

import redirectSSL from 'redirect-ssl'
export default defineEventHandler((event) => {
  const protocol = event.node.req.headers['x-forwarded-proto']; // http || https
  const env = process.env.NODE_ENV; // development || production
  if (protocol === 'http' && env === 'production') {
    return redirectSSL(event.node.req, event.node.res)
  }
})