Easy redirects in Nuxt.js
Redirects are ideally handled in your web server (e.g. Apache, Nginx) configuration. But if you’re in a pinch it is possible to manage redirects from inside your Nuxt.js project, complete with HTTP redirect codes and JavaScript logic.
First create ridirects.js
inside the middleware folder in your project root:
// middleware/redirects.js
export default function(ctx) {
if(ctx.route.fullPath == '/apply') {
ctx.redirect(301, '/register')
}
}
The above shows a simple scenario but you can obviously incorporate your own application logic, use Regex or whatever you like.
All that’s left to do is reference redirects.js
inside your nuxt.config.js
:
```javascript // nuxt.config.js
export default { router: { middleware: [‘auth’, ‘redirects’], }, }