'redirect all routes to https in nuxt project hosted in heroku

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}`);
   }
  }
}


Solution 1:[1]

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"],

Solution 2:[2]

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
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 yoyojs
Solution 2 devdev_dev