DEV Community

Jack Whiting
Jack Whiting

Posted on • Updated on • Originally published at jackwhiting.co.uk

Handling Redirects in Nuxt.js through Middleware

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 handle redirects simplistically through pure Nuxt (no server, no advanced configuration).

To do this we'll need to leverage the serverMiddleware, you can learn more about this from the official Nuxt.js docs, but in short, it allows for us to handle additional routes that aren't defined within the folder structure (for example an API). In our case, we will be using the serverMiddleware to read the redirects and take us to the appropriate route.

We are going to create a JSON file to hold all of our redirects and then let the middleware read the start destination and send us to the final destination.

Create JSON

Create a new JSON file in your project and place it in your desired location. For this example, place the file in the following destination /data/redirects.json.

Our JSON should contain an array of elements with a from and to, please see the below example and adjust this to your own needs.

[
  {
    "from": "/",
    "new": "/home"
  },
  {
    "from": "/get-in-touch",
    "to": "/contact"
  }
]
Enter fullscreen mode Exit fullscreen mode

Create the serverMiddleware

Next, we need to create a file which can handle the reading of the JSON and the logic to handle the redirect. Create a new file in /serverMiddleware/redirects.js with the following code:

const redirects = require('../data/redirects.json') // update to your file path

export default function(req, rest, next) {
  // find the redirect if it exists where the from === the requested url
  const redirect = redirects.find(r => r.from === req.url)

  // If it exists, redirect the page with a 301 response else carry on
  if (redirect) {
    res.writeHead(301, { Location: redirect.to })
    res.end()
  } else {
    next()
  }
}
Enter fullscreen mode Exit fullscreen mode

The above file checks that the URL exists and if so, redirects to the destination. If not, the Nuxt application will move on and return the requested page.

Add to Nuxt.config.js

Before anything will work, we need to add the newly created redirects middleware into the nuxt.config.js . Edit the nuxt.config.js file and add the following in:

...
serverMiddleware: [
    '~/serverMiddleware/redirects.js'
],
...
Enter fullscreen mode Exit fullscreen mode

Recompile the code and check that everything is working.

Bonus

If you need to take the redirects a bit further or if you don't mind using third party packages there is an awesome package available at https://github.com/nuxt-community/redirect-module that can handle this for you.


Like what you read? You can find more articles on my blog at https://jackwhiting.co.uk

Top comments (7)

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' ?