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}`);
}
}
}
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}`);
}
}
}
Share
Improve this question
edited Jan 15, 2021 at 5:31
zcserei
6657 silver badges32 bronze badges
asked Jun 17, 2019 at 10:46
yoyojsyoyojs
1,7735 gold badges24 silver badges41 bronze badges
3 Answers
Reset to default 11I 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"],
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)
}
})
You can configure this in heroku.
For Nuxt static mode:
- Add the https://github.com/heroku/heroku-buildpack-static.git buildpack after the heroku/nodejs buildpack under buildpacks
- Make sure the buildpacks are added in this order to an
app.json
in the root directory of your project - Add a
static.json
in the root directory of your project- Make sure
root
andhttps_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.
- Make sure
Example static.json:
{
"root": "dist/",
"routes": {
"/**": "index.html"
},
"https_only": true
}