DEV Community

Handling Redirects in Nuxt.js through Middleware

Jack Whiting on September 18, 2019

I recently published an article about how to handle redirects in Laravel, since I also use Nuxt.js I thought it would be good to write up how to ha...
Collapse
 
kp profile image
KP

@jackabox good writeup! glad to find another fellow dev using Laravel and Nuxt. How would you do a redirect in nuxt for:

On production:
domain.com -> domain.com/join
On dev:
Don't redirect from homepage( domain.com) to domain.com/join

Collapse
 
jackabox profile image
Jack Whiting

Hey, sorry for the delay.

I'd look into the use of env variables here. Where you get the redirects in the middleware, we can do something like this..

const prodRedirects= require('../data/redirectsProd.json')
let redirects = require('../data/redirects.json')

if (process.env.NODE_ENV === 'production') {
  redirects = [...prodRedirects, ...redirects]
}

This was a pretty quick example but would probably be the way I'd go

Collapse
 
kp profile image
KP

@jackabox good example, thank you!

Collapse
 
saunved profile image
Saunved

Thanks a lot for this! A lot of articles show a res.redirect method (which doesn't exist in Nuxt.js for some reason). This is the right way to do it!

Collapse
 
ovab profile image
Bavo

FYI for those using Nuxt 3: you can skip registering your server middleware in the config by placing it in {root}/server/middleware.

same thing for client middleware but then just in {root}/middleware

Collapse
 
simplenotezy profile image
Mattias Fjellvang

Thanks for this article. I have a file of 3500 redirects. How would performance be in such scenario? And does it work with static generated sites?

Collapse
 
stubar profile image
stubar

the first entry in /data/redirects.json has a 'new' key, should this be 'to' ?